Bug Summary

File:build/source/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
Warning:line 11663, column 30
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SLPVectorizer.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-17/lib/clang/17 -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/Transforms/Vectorize -I /build/source/llvm/lib/Transforms/Vectorize -I include -I /build/source/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/source/= -source-date-epoch 1683717183 -O2 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-05-10-133810-16478-1 -x c++ /build/source/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
1//===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10// stores that can be put together into vector-stores. Next, it attempts to
11// construct vectorizable tree using the use-def chains. If a profitable tree
12// was found, the SLP vectorizer performs vectorization on the tree.
13//
14// The pass is inspired by the work described in the paper:
15// "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16//
17//===----------------------------------------------------------------------===//
18
19#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/DenseSet.h"
22#include "llvm/ADT/PostOrderIterator.h"
23#include "llvm/ADT/PriorityQueue.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/SetOperations.h"
26#include "llvm/ADT/SetVector.h"
27#include "llvm/ADT/SmallBitVector.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/SmallSet.h"
30#include "llvm/ADT/SmallString.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/ADT/iterator.h"
33#include "llvm/ADT/iterator_range.h"
34#include "llvm/Analysis/AliasAnalysis.h"
35#include "llvm/Analysis/AssumptionCache.h"
36#include "llvm/Analysis/CodeMetrics.h"
37#include "llvm/Analysis/DemandedBits.h"
38#include "llvm/Analysis/GlobalsModRef.h"
39#include "llvm/Analysis/IVDescriptors.h"
40#include "llvm/Analysis/LoopAccessAnalysis.h"
41#include "llvm/Analysis/LoopInfo.h"
42#include "llvm/Analysis/MemoryLocation.h"
43#include "llvm/Analysis/OptimizationRemarkEmitter.h"
44#include "llvm/Analysis/ScalarEvolution.h"
45#include "llvm/Analysis/ScalarEvolutionExpressions.h"
46#include "llvm/Analysis/TargetLibraryInfo.h"
47#include "llvm/Analysis/TargetTransformInfo.h"
48#include "llvm/Analysis/ValueTracking.h"
49#include "llvm/Analysis/VectorUtils.h"
50#include "llvm/IR/Attributes.h"
51#include "llvm/IR/BasicBlock.h"
52#include "llvm/IR/Constant.h"
53#include "llvm/IR/Constants.h"
54#include "llvm/IR/DataLayout.h"
55#include "llvm/IR/DerivedTypes.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"
61#include "llvm/IR/Instructions.h"
62#include "llvm/IR/IntrinsicInst.h"
63#include "llvm/IR/Intrinsics.h"
64#include "llvm/IR/Module.h"
65#include "llvm/IR/Operator.h"
66#include "llvm/IR/PatternMatch.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"
76#include "llvm/Support/Casting.h"
77#include "llvm/Support/CommandLine.h"
78#include "llvm/Support/Compiler.h"
79#include "llvm/Support/DOTGraphTraits.h"
80#include "llvm/Support/Debug.h"
81#include "llvm/Support/ErrorHandling.h"
82#include "llvm/Support/GraphWriter.h"
83#include "llvm/Support/InstructionCost.h"
84#include "llvm/Support/KnownBits.h"
85#include "llvm/Support/MathExtras.h"
86#include "llvm/Support/raw_ostream.h"
87#include "llvm/Transforms/Utils/InjectTLIMappings.h"
88#include "llvm/Transforms/Utils/Local.h"
89#include "llvm/Transforms/Utils/LoopUtils.h"
90#include <algorithm>
91#include <cassert>
92#include <cstdint>
93#include <iterator>
94#include <memory>
95#include <optional>
96#include <set>
97#include <string>
98#include <tuple>
99#include <utility>
100#include <vector>
101
102using namespace llvm;
103using namespace llvm::PatternMatch;
104using namespace slpvectorizer;
105
106#define SV_NAME"slp-vectorizer" "slp-vectorizer"
107#define DEBUG_TYPE"SLP" "SLP"
108
109STATISTIC(NumVectorInstructions, "Number of vector instructions generated")static llvm::Statistic NumVectorInstructions = {"SLP", "NumVectorInstructions"
, "Number of vector instructions generated"}
;
110
111cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
112 cl::desc("Run the SLP vectorization passes"));
113
114static cl::opt<int>
115 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
116 cl::desc("Only vectorize if you gain more than this "
117 "number "));
118
119static cl::opt<bool>
120ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
121 cl::desc("Attempt to vectorize horizontal reductions"));
122
123static cl::opt<bool> ShouldStartVectorizeHorAtStore(
124 "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
125 cl::desc(
126 "Attempt to vectorize horizontal reductions feeding into a store"));
127
128// NOTE: If AllowHorRdxIdenityOptimization is true, the optimization will run
129// even if we match a reduction but do not vectorize in the end.
130static cl::opt<bool> AllowHorRdxIdenityOptimization(
131 "slp-optimize-identity-hor-reduction-ops", cl::init(true), cl::Hidden,
132 cl::desc("Allow optimization of original scalar identity operations on "
133 "matched horizontal reductions."));
134
135static cl::opt<int>
136MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
137 cl::desc("Attempt to vectorize for this register size in bits"));
138
139static cl::opt<unsigned>
140MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
141 cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
142
143static cl::opt<int>
144MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
145 cl::desc("Maximum depth of the lookup for consecutive stores."));
146
147/// Limits the size of scheduling regions in a block.
148/// It avoid long compile times for _very_ large blocks where vector
149/// instructions are spread over a wide range.
150/// This limit is way higher than needed by real-world functions.
151static cl::opt<int>
152ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
153 cl::desc("Limit the size of the SLP scheduling region per block"));
154
155static cl::opt<int> MinVectorRegSizeOption(
156 "slp-min-reg-size", cl::init(128), cl::Hidden,
157 cl::desc("Attempt to vectorize for this register size in bits"));
158
159static cl::opt<unsigned> RecursionMaxDepth(
160 "slp-recursion-max-depth", cl::init(12), cl::Hidden,
161 cl::desc("Limit the recursion depth when building a vectorizable tree"));
162
163static cl::opt<unsigned> MinTreeSize(
164 "slp-min-tree-size", cl::init(3), cl::Hidden,
165 cl::desc("Only vectorize small trees if they are fully vectorizable"));
166
167// The maximum depth that the look-ahead score heuristic will explore.
168// The higher this value, the higher the compilation time overhead.
169static cl::opt<int> LookAheadMaxDepth(
170 "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
171 cl::desc("The maximum look-ahead depth for operand reordering scores"));
172
173// The maximum depth that the look-ahead score heuristic will explore
174// when it probing among candidates for vectorization tree roots.
175// The higher this value, the higher the compilation time overhead but unlike
176// similar limit for operands ordering this is less frequently used, hence
177// impact of higher value is less noticeable.
178static cl::opt<int> RootLookAheadMaxDepth(
179 "slp-max-root-look-ahead-depth", cl::init(2), cl::Hidden,
180 cl::desc("The maximum look-ahead depth for searching best rooting option"));
181
182static cl::opt<bool>
183 ViewSLPTree("view-slp-tree", cl::Hidden,
184 cl::desc("Display the SLP trees with Graphviz"));
185
186// Limit the number of alias checks. The limit is chosen so that
187// it has no negative effect on the llvm benchmarks.
188static const unsigned AliasedCheckLimit = 10;
189
190// Another limit for the alias checks: The maximum distance between load/store
191// instructions where alias checks are done.
192// This limit is useful for very large basic blocks.
193static const unsigned MaxMemDepDistance = 160;
194
195/// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
196/// regions to be handled.
197static const int MinScheduleRegionSize = 16;
198
199/// Predicate for the element types that the SLP vectorizer supports.
200///
201/// The most important thing to filter here are types which are invalid in LLVM
202/// vectors. We also filter target specific types which have absolutely no
203/// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
204/// avoids spending time checking the cost model and realizing that they will
205/// be inevitably scalarized.
206static bool isValidElementType(Type *Ty) {
207 return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
208 !Ty->isPPC_FP128Ty();
209}
210
211/// \returns True if the value is a constant (but not globals/constant
212/// expressions).
213static bool isConstant(Value *V) {
214 return isa<Constant>(V) && !isa<ConstantExpr, GlobalValue>(V);
215}
216
217/// Checks if \p V is one of vector-like instructions, i.e. undef,
218/// insertelement/extractelement with constant indices for fixed vector type or
219/// extractvalue instruction.
220static bool isVectorLikeInstWithConstOps(Value *V) {
221 if (!isa<InsertElementInst, ExtractElementInst>(V) &&
222 !isa<ExtractValueInst, UndefValue>(V))
223 return false;
224 auto *I = dyn_cast<Instruction>(V);
225 if (!I || isa<ExtractValueInst>(I))
226 return true;
227 if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
228 return false;
229 if (isa<ExtractElementInst>(I))
230 return isConstant(I->getOperand(1));
231 assert(isa<InsertElementInst>(V) && "Expected only insertelement.")(static_cast <bool> (isa<InsertElementInst>(V) &&
"Expected only insertelement.") ? void (0) : __assert_fail (
"isa<InsertElementInst>(V) && \"Expected only insertelement.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 231, __extension__
__PRETTY_FUNCTION__))
;
232 return isConstant(I->getOperand(2));
233}
234
235/// \returns true if all of the instructions in \p VL are in the same block or
236/// false otherwise.
237static bool allSameBlock(ArrayRef<Value *> VL) {
238 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
239 if (!I0)
240 return false;
241 if (all_of(VL, isVectorLikeInstWithConstOps))
242 return true;
243
244 BasicBlock *BB = I0->getParent();
245 for (int I = 1, E = VL.size(); I < E; I++) {
246 auto *II = dyn_cast<Instruction>(VL[I]);
247 if (!II)
248 return false;
249
250 if (BB != II->getParent())
251 return false;
252 }
253 return true;
254}
255
256/// \returns True if all of the values in \p VL are constants (but not
257/// globals/constant expressions).
258static bool allConstant(ArrayRef<Value *> VL) {
259 // Constant expressions and globals can't be vectorized like normal integer/FP
260 // constants.
261 return all_of(VL, isConstant);
262}
263
264/// \returns True if all of the values in \p VL are identical or some of them
265/// are UndefValue.
266static bool isSplat(ArrayRef<Value *> VL) {
267 Value *FirstNonUndef = nullptr;
268 for (Value *V : VL) {
269 if (isa<UndefValue>(V))
270 continue;
271 if (!FirstNonUndef) {
272 FirstNonUndef = V;
273 continue;
274 }
275 if (V != FirstNonUndef)
276 return false;
277 }
278 return FirstNonUndef != nullptr;
279}
280
281/// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
282static bool isCommutative(Instruction *I) {
283 if (auto *Cmp = dyn_cast<CmpInst>(I))
284 return Cmp->isCommutative();
285 if (auto *BO = dyn_cast<BinaryOperator>(I))
286 return BO->isCommutative();
287 // TODO: This should check for generic Instruction::isCommutative(), but
288 // we need to confirm that the caller code correctly handles Intrinsics
289 // for example (does not have 2 operands).
290 return false;
291}
292
293/// \returns inserting index of InsertElement or InsertValue instruction,
294/// using Offset as base offset for index.
295static std::optional<unsigned> getInsertIndex(const Value *InsertInst,
296 unsigned Offset = 0) {
297 int Index = Offset;
298 if (const auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
299 const auto *VT = dyn_cast<FixedVectorType>(IE->getType());
300 if (!VT)
301 return std::nullopt;
302 const auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2));
303 if (!CI)
304 return std::nullopt;
305 if (CI->getValue().uge(VT->getNumElements()))
306 return std::nullopt;
307 Index *= VT->getNumElements();
308 Index += CI->getZExtValue();
309 return Index;
310 }
311
312 const auto *IV = cast<InsertValueInst>(InsertInst);
313 Type *CurrentType = IV->getType();
314 for (unsigned I : IV->indices()) {
315 if (const auto *ST = dyn_cast<StructType>(CurrentType)) {
316 Index *= ST->getNumElements();
317 CurrentType = ST->getElementType(I);
318 } else if (const auto *AT = dyn_cast<ArrayType>(CurrentType)) {
319 Index *= AT->getNumElements();
320 CurrentType = AT->getElementType();
321 } else {
322 return std::nullopt;
323 }
324 Index += I;
325 }
326 return Index;
327}
328
329namespace {
330/// Specifies the way the mask should be analyzed for undefs/poisonous elements
331/// in the shuffle mask.
332enum class UseMask {
333 FirstArg, ///< The mask is expected to be for permutation of 1-2 vectors,
334 ///< check for the mask elements for the first argument (mask
335 ///< indices are in range [0:VF)).
336 SecondArg, ///< The mask is expected to be for permutation of 2 vectors, check
337 ///< for the mask elements for the second argument (mask indices
338 ///< are in range [VF:2*VF))
339 UndefsAsMask ///< Consider undef mask elements (-1) as placeholders for
340 ///< future shuffle elements and mark them as ones as being used
341 ///< in future. Non-undef elements are considered as unused since
342 ///< they're already marked as used in the mask.
343};
344} // namespace
345
346/// Prepares a use bitset for the given mask either for the first argument or
347/// for the second.
348static SmallBitVector buildUseMask(int VF, ArrayRef<int> Mask,
349 UseMask MaskArg) {
350 SmallBitVector UseMask(VF, true);
351 for (auto [Idx, Value] : enumerate(Mask)) {
352 if (Value == PoisonMaskElem) {
353 if (MaskArg == UseMask::UndefsAsMask)
354 UseMask.reset(Idx);
355 continue;
356 }
357 if (MaskArg == UseMask::FirstArg && Value < VF)
358 UseMask.reset(Value);
359 else if (MaskArg == UseMask::SecondArg && Value >= VF)
360 UseMask.reset(Value - VF);
361 }
362 return UseMask;
363}
364
365/// Checks if the given value is actually an undefined constant vector.
366/// Also, if the \p UseMask is not empty, tries to check if the non-masked
367/// elements actually mask the insertelement buildvector, if any.
368template <bool IsPoisonOnly = false>
369static SmallBitVector isUndefVector(const Value *V,
370 const SmallBitVector &UseMask = {}) {
371 SmallBitVector Res(UseMask.empty() ? 1 : UseMask.size(), true);
372 using T = std::conditional_t<IsPoisonOnly, PoisonValue, UndefValue>;
373 if (isa<T>(V))
374 return Res;
375 auto *VecTy = dyn_cast<FixedVectorType>(V->getType());
376 if (!VecTy)
377 return Res.reset();
378 auto *C = dyn_cast<Constant>(V);
379 if (!C) {
380 if (!UseMask.empty()) {
381 const Value *Base = V;
382 while (auto *II = dyn_cast<InsertElementInst>(Base)) {
383 Base = II->getOperand(0);
384 if (isa<T>(II->getOperand(1)))
385 continue;
386 std::optional<unsigned> Idx = getInsertIndex(II);
387 if (!Idx)
388 continue;
389 if (*Idx < UseMask.size() && !UseMask.test(*Idx))
390 Res.reset(*Idx);
391 }
392 // TODO: Add analysis for shuffles here too.
393 if (V == Base) {
394 Res.reset();
395 } else {
396 SmallBitVector SubMask(UseMask.size(), false);
397 Res &= isUndefVector<IsPoisonOnly>(Base, SubMask);
398 }
399 } else {
400 Res.reset();
401 }
402 return Res;
403 }
404 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
405 if (Constant *Elem = C->getAggregateElement(I))
406 if (!isa<T>(Elem) &&
407 (UseMask.empty() || (I < UseMask.size() && !UseMask.test(I))))
408 Res.reset(I);
409 }
410 return Res;
411}
412
413/// Checks if the vector of instructions can be represented as a shuffle, like:
414/// %x0 = extractelement <4 x i8> %x, i32 0
415/// %x3 = extractelement <4 x i8> %x, i32 3
416/// %y1 = extractelement <4 x i8> %y, i32 1
417/// %y2 = extractelement <4 x i8> %y, i32 2
418/// %x0x0 = mul i8 %x0, %x0
419/// %x3x3 = mul i8 %x3, %x3
420/// %y1y1 = mul i8 %y1, %y1
421/// %y2y2 = mul i8 %y2, %y2
422/// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
423/// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
424/// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
425/// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
426/// ret <4 x i8> %ins4
427/// can be transformed into:
428/// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
429/// i32 6>
430/// %2 = mul <4 x i8> %1, %1
431/// ret <4 x i8> %2
432/// We convert this initially to something like:
433/// %x0 = extractelement <4 x i8> %x, i32 0
434/// %x3 = extractelement <4 x i8> %x, i32 3
435/// %y1 = extractelement <4 x i8> %y, i32 1
436/// %y2 = extractelement <4 x i8> %y, i32 2
437/// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
438/// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
439/// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
440/// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
441/// %5 = mul <4 x i8> %4, %4
442/// %6 = extractelement <4 x i8> %5, i32 0
443/// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
444/// %7 = extractelement <4 x i8> %5, i32 1
445/// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
446/// %8 = extractelement <4 x i8> %5, i32 2
447/// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
448/// %9 = extractelement <4 x i8> %5, i32 3
449/// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
450/// ret <4 x i8> %ins4
451/// InstCombiner transforms this into a shuffle and vector mul
452/// Mask will return the Shuffle Mask equivalent to the extracted elements.
453/// TODO: Can we split off and reuse the shuffle mask detection from
454/// ShuffleVectorInst/getShuffleCost?
455static std::optional<TargetTransformInfo::ShuffleKind>
456isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
457 const auto *It =
458 find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
459 if (It == VL.end())
460 return std::nullopt;
461 auto *EI0 = cast<ExtractElementInst>(*It);
462 if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
463 return std::nullopt;
464 unsigned Size =
465 cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
466 Value *Vec1 = nullptr;
467 Value *Vec2 = nullptr;
468 enum ShuffleMode { Unknown, Select, Permute };
469 ShuffleMode CommonShuffleMode = Unknown;
470 Mask.assign(VL.size(), PoisonMaskElem);
471 for (unsigned I = 0, E = VL.size(); I < E; ++I) {
472 // Undef can be represented as an undef element in a vector.
473 if (isa<UndefValue>(VL[I]))
474 continue;
475 auto *EI = cast<ExtractElementInst>(VL[I]);
476 if (isa<ScalableVectorType>(EI->getVectorOperandType()))
477 return std::nullopt;
478 auto *Vec = EI->getVectorOperand();
479 // We can extractelement from undef or poison vector.
480 if (isUndefVector(Vec).all())
481 continue;
482 // All vector operands must have the same number of vector elements.
483 if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
484 return std::nullopt;
485 if (isa<UndefValue>(EI->getIndexOperand()))
486 continue;
487 auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
488 if (!Idx)
489 return std::nullopt;
490 // Undefined behavior if Idx is negative or >= Size.
491 if (Idx->getValue().uge(Size))
492 continue;
493 unsigned IntIdx = Idx->getValue().getZExtValue();
494 Mask[I] = IntIdx;
495 // For correct shuffling we have to have at most 2 different vector operands
496 // in all extractelement instructions.
497 if (!Vec1 || Vec1 == Vec) {
498 Vec1 = Vec;
499 } else if (!Vec2 || Vec2 == Vec) {
500 Vec2 = Vec;
501 Mask[I] += Size;
502 } else {
503 return std::nullopt;
504 }
505 if (CommonShuffleMode == Permute)
506 continue;
507 // If the extract index is not the same as the operation number, it is a
508 // permutation.
509 if (IntIdx != I) {
510 CommonShuffleMode = Permute;
511 continue;
512 }
513 CommonShuffleMode = Select;
514 }
515 // If we're not crossing lanes in different vectors, consider it as blending.
516 if (CommonShuffleMode == Select && Vec2)
517 return TargetTransformInfo::SK_Select;
518 // If Vec2 was never used, we have a permutation of a single vector, otherwise
519 // we have permutation of 2 vectors.
520 return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
521 : TargetTransformInfo::SK_PermuteSingleSrc;
522}
523
524/// \returns True if Extract{Value,Element} instruction extracts element Idx.
525static std::optional<unsigned> getExtractIndex(Instruction *E) {
526 unsigned Opcode = E->getOpcode();
527 assert((Opcode == Instruction::ExtractElement ||(static_cast <bool> ((Opcode == Instruction::ExtractElement
|| Opcode == Instruction::ExtractValue) && "Expected extractelement or extractvalue instruction."
) ? void (0) : __assert_fail ("(Opcode == Instruction::ExtractElement || Opcode == Instruction::ExtractValue) && \"Expected extractelement or extractvalue instruction.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 529, __extension__
__PRETTY_FUNCTION__))
528 Opcode == Instruction::ExtractValue) &&(static_cast <bool> ((Opcode == Instruction::ExtractElement
|| Opcode == Instruction::ExtractValue) && "Expected extractelement or extractvalue instruction."
) ? void (0) : __assert_fail ("(Opcode == Instruction::ExtractElement || Opcode == Instruction::ExtractValue) && \"Expected extractelement or extractvalue instruction.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 529, __extension__
__PRETTY_FUNCTION__))
529 "Expected extractelement or extractvalue instruction.")(static_cast <bool> ((Opcode == Instruction::ExtractElement
|| Opcode == Instruction::ExtractValue) && "Expected extractelement or extractvalue instruction."
) ? void (0) : __assert_fail ("(Opcode == Instruction::ExtractElement || Opcode == Instruction::ExtractValue) && \"Expected extractelement or extractvalue instruction.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 529, __extension__
__PRETTY_FUNCTION__))
;
530 if (Opcode == Instruction::ExtractElement) {
531 auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
532 if (!CI)
533 return std::nullopt;
534 return CI->getZExtValue();
535 }
536 auto *EI = cast<ExtractValueInst>(E);
537 if (EI->getNumIndices() != 1)
538 return std::nullopt;
539 return *EI->idx_begin();
540}
541
542/// Tries to find extractelement instructions with constant indices from fixed
543/// vector type and gather such instructions into a bunch, which highly likely
544/// might be detected as a shuffle of 1 or 2 input vectors. If this attempt was
545/// successful, the matched scalars are replaced by poison values in \p VL for
546/// future analysis.
547static std::optional<TTI::ShuffleKind>
548tryToGatherExtractElements(SmallVectorImpl<Value *> &VL,
549 SmallVectorImpl<int> &Mask) {
550 // Scan list of gathered scalars for extractelements that can be represented
551 // as shuffles.
552 MapVector<Value *, SmallVector<int>> VectorOpToIdx;
553 SmallVector<int> UndefVectorExtracts;
554 for (int I = 0, E = VL.size(); I < E; ++I) {
555 auto *EI = dyn_cast<ExtractElementInst>(VL[I]);
556 if (!EI) {
557 if (isa<UndefValue>(VL[I]))
558 UndefVectorExtracts.push_back(I);
559 continue;
560 }
561 auto *VecTy = dyn_cast<FixedVectorType>(EI->getVectorOperandType());
562 if (!VecTy || !isa<ConstantInt, UndefValue>(EI->getIndexOperand()))
563 continue;
564 std::optional<unsigned> Idx = getExtractIndex(EI);
565 // Undefined index.
566 if (!Idx) {
567 UndefVectorExtracts.push_back(I);
568 continue;
569 }
570 SmallBitVector ExtractMask(VecTy->getNumElements(), true);
571 ExtractMask.reset(*Idx);
572 if (isUndefVector(EI->getVectorOperand(), ExtractMask).all()) {
573 UndefVectorExtracts.push_back(I);
574 continue;
575 }
576 VectorOpToIdx[EI->getVectorOperand()].push_back(I);
577 }
578 // Sort the vector operands by the maximum number of uses in extractelements.
579 MapVector<unsigned, SmallVector<Value *>> VFToVector;
580 for (const auto &Data : VectorOpToIdx)
581 VFToVector[cast<FixedVectorType>(Data.first->getType())->getNumElements()]
582 .push_back(Data.first);
583 for (auto &Data : VFToVector) {
584 stable_sort(Data.second, [&VectorOpToIdx](Value *V1, Value *V2) {
585 return VectorOpToIdx.find(V1)->second.size() >
586 VectorOpToIdx.find(V2)->second.size();
587 });
588 }
589 // Find the best pair of the vectors with the same number of elements or a
590 // single vector.
591 const int UndefSz = UndefVectorExtracts.size();
592 unsigned SingleMax = 0;
593 Value *SingleVec = nullptr;
594 unsigned PairMax = 0;
595 std::pair<Value *, Value *> PairVec(nullptr, nullptr);
596 for (auto &Data : VFToVector) {
597 Value *V1 = Data.second.front();
598 if (SingleMax < VectorOpToIdx[V1].size() + UndefSz) {
599 SingleMax = VectorOpToIdx[V1].size() + UndefSz;
600 SingleVec = V1;
601 }
602 Value *V2 = nullptr;
603 if (Data.second.size() > 1)
604 V2 = *std::next(Data.second.begin());
605 if (V2 && PairMax < VectorOpToIdx[V1].size() + VectorOpToIdx[V2].size() +
606 UndefSz) {
607 PairMax = VectorOpToIdx[V1].size() + VectorOpToIdx[V2].size() + UndefSz;
608 PairVec = std::make_pair(V1, V2);
609 }
610 }
611 if (SingleMax == 0 && PairMax == 0 && UndefSz == 0)
612 return std::nullopt;
613 // Check if better to perform a shuffle of 2 vectors or just of a single
614 // vector.
615 SmallVector<Value *> SavedVL(VL.begin(), VL.end());
616 SmallVector<Value *> GatheredExtracts(
617 VL.size(), PoisonValue::get(VL.front()->getType()));
618 if (SingleMax >= PairMax && SingleMax) {
619 for (int Idx : VectorOpToIdx[SingleVec])
620 std::swap(GatheredExtracts[Idx], VL[Idx]);
621 } else {
622 for (Value *V : {PairVec.first, PairVec.second})
623 for (int Idx : VectorOpToIdx[V])
624 std::swap(GatheredExtracts[Idx], VL[Idx]);
625 }
626 // Add extracts from undefs too.
627 for (int Idx : UndefVectorExtracts)
628 std::swap(GatheredExtracts[Idx], VL[Idx]);
629 // Check that gather of extractelements can be represented as just a
630 // shuffle of a single/two vectors the scalars are extracted from.
631 std::optional<TTI::ShuffleKind> Res =
632 isFixedVectorShuffle(GatheredExtracts, Mask);
633 if (!Res) {
634 // TODO: try to check other subsets if possible.
635 // Restore the original VL if attempt was not successful.
636 VL.swap(SavedVL);
637 return std::nullopt;
638 }
639 // Restore unused scalars from mask, if some of the extractelements were not
640 // selected for shuffle.
641 for (int I = 0, E = GatheredExtracts.size(); I < E; ++I) {
642 auto *EI = dyn_cast<ExtractElementInst>(VL[I]);
643 if (!EI || !isa<FixedVectorType>(EI->getVectorOperandType()) ||
644 !isa<ConstantInt, UndefValue>(EI->getIndexOperand()) ||
645 is_contained(UndefVectorExtracts, I))
646 continue;
647 if (Mask[I] == PoisonMaskElem && !isa<PoisonValue>(GatheredExtracts[I]))
648 std::swap(VL[I], GatheredExtracts[I]);
649 }
650 return Res;
651}
652
653namespace {
654
655/// Main data required for vectorization of instructions.
656struct InstructionsState {
657 /// The very first instruction in the list with the main opcode.
658 Value *OpValue = nullptr;
659
660 /// The main/alternate instruction.
661 Instruction *MainOp = nullptr;
662 Instruction *AltOp = nullptr;
663
664 /// The main/alternate opcodes for the list of instructions.
665 unsigned getOpcode() const {
666 return MainOp ? MainOp->getOpcode() : 0;
667 }
668
669 unsigned getAltOpcode() const {
670 return AltOp ? AltOp->getOpcode() : 0;
671 }
672
673 /// Some of the instructions in the list have alternate opcodes.
674 bool isAltShuffle() const { return AltOp != MainOp; }
675
676 bool isOpcodeOrAlt(Instruction *I) const {
677 unsigned CheckedOpcode = I->getOpcode();
678 return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
679 }
680
681 InstructionsState() = delete;
682 InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
683 : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
684};
685
686} // end anonymous namespace
687
688/// Chooses the correct key for scheduling data. If \p Op has the same (or
689/// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
690/// OpValue.
691static Value *isOneOf(const InstructionsState &S, Value *Op) {
692 auto *I = dyn_cast<Instruction>(Op);
693 if (I && S.isOpcodeOrAlt(I))
694 return Op;
695 return S.OpValue;
696}
697
698/// \returns true if \p Opcode is allowed as part of of the main/alternate
699/// instruction for SLP vectorization.
700///
701/// Example of unsupported opcode is SDIV that can potentially cause UB if the
702/// "shuffled out" lane would result in division by zero.
703static bool isValidForAlternation(unsigned Opcode) {
704 if (Instruction::isIntDivRem(Opcode))
705 return false;
706
707 return true;
708}
709
710static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
711 const TargetLibraryInfo &TLI,
712 unsigned BaseIndex = 0);
713
714/// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
715/// compatible instructions or constants, or just some other regular values.
716static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
717 Value *Op1, const TargetLibraryInfo &TLI) {
718 return (isConstant(BaseOp0) && isConstant(Op0)) ||
719 (isConstant(BaseOp1) && isConstant(Op1)) ||
720 (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
721 !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
722 BaseOp0 == Op0 || BaseOp1 == Op1 ||
723 getSameOpcode({BaseOp0, Op0}, TLI).getOpcode() ||
724 getSameOpcode({BaseOp1, Op1}, TLI).getOpcode();
725}
726
727/// \returns true if a compare instruction \p CI has similar "look" and
728/// same predicate as \p BaseCI, "as is" or with its operands and predicate
729/// swapped, false otherwise.
730static bool isCmpSameOrSwapped(const CmpInst *BaseCI, const CmpInst *CI,
731 const TargetLibraryInfo &TLI) {
732 assert(BaseCI->getOperand(0)->getType() == CI->getOperand(0)->getType() &&(static_cast <bool> (BaseCI->getOperand(0)->getType
() == CI->getOperand(0)->getType() && "Assessing comparisons of different types?"
) ? void (0) : __assert_fail ("BaseCI->getOperand(0)->getType() == CI->getOperand(0)->getType() && \"Assessing comparisons of different types?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 733, __extension__
__PRETTY_FUNCTION__))
733 "Assessing comparisons of different types?")(static_cast <bool> (BaseCI->getOperand(0)->getType
() == CI->getOperand(0)->getType() && "Assessing comparisons of different types?"
) ? void (0) : __assert_fail ("BaseCI->getOperand(0)->getType() == CI->getOperand(0)->getType() && \"Assessing comparisons of different types?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 733, __extension__
__PRETTY_FUNCTION__))
;
734 CmpInst::Predicate BasePred = BaseCI->getPredicate();
735 CmpInst::Predicate Pred = CI->getPredicate();
736 CmpInst::Predicate SwappedPred = CmpInst::getSwappedPredicate(Pred);
737
738 Value *BaseOp0 = BaseCI->getOperand(0);
739 Value *BaseOp1 = BaseCI->getOperand(1);
740 Value *Op0 = CI->getOperand(0);
741 Value *Op1 = CI->getOperand(1);
742
743 return (BasePred == Pred &&
744 areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1, TLI)) ||
745 (BasePred == SwappedPred &&
746 areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0, TLI));
747}
748
749/// \returns analysis of the Instructions in \p VL described in
750/// InstructionsState, the Opcode that we suppose the whole list
751/// could be vectorized even if its structure is diverse.
752static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
753 const TargetLibraryInfo &TLI,
754 unsigned BaseIndex) {
755 // Make sure these are all Instructions.
756 if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
757 return InstructionsState(VL[BaseIndex], nullptr, nullptr);
758
759 bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
760 bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
761 bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
762 CmpInst::Predicate BasePred =
763 IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
764 : CmpInst::BAD_ICMP_PREDICATE;
765 unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
766 unsigned AltOpcode = Opcode;
767 unsigned AltIndex = BaseIndex;
768
769 // Check for one alternate opcode from another BinaryOperator.
770 // TODO - generalize to support all operators (types, calls etc.).
771 auto *IBase = cast<Instruction>(VL[BaseIndex]);
772 Intrinsic::ID BaseID = 0;
773 SmallVector<VFInfo> BaseMappings;
774 if (auto *CallBase = dyn_cast<CallInst>(IBase)) {
775 BaseID = getVectorIntrinsicIDForCall(CallBase, &TLI);
776 BaseMappings = VFDatabase(*CallBase).getMappings(*CallBase);
777 if (!isTriviallyVectorizable(BaseID) && BaseMappings.empty())
778 return InstructionsState(VL[BaseIndex], nullptr, nullptr);
779 }
780 for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
781 auto *I = cast<Instruction>(VL[Cnt]);
782 unsigned InstOpcode = I->getOpcode();
783 if (IsBinOp && isa<BinaryOperator>(I)) {
784 if (InstOpcode == Opcode || InstOpcode == AltOpcode)
785 continue;
786 if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
787 isValidForAlternation(Opcode)) {
788 AltOpcode = InstOpcode;
789 AltIndex = Cnt;
790 continue;
791 }
792 } else if (IsCastOp && isa<CastInst>(I)) {
793 Value *Op0 = IBase->getOperand(0);
794 Type *Ty0 = Op0->getType();
795 Value *Op1 = I->getOperand(0);
796 Type *Ty1 = Op1->getType();
797 if (Ty0 == Ty1) {
798 if (InstOpcode == Opcode || InstOpcode == AltOpcode)
799 continue;
800 if (Opcode == AltOpcode) {
801 assert(isValidForAlternation(Opcode) &&(static_cast <bool> (isValidForAlternation(Opcode) &&
isValidForAlternation(InstOpcode) && "Cast isn't safe for alternation, logic needs to be updated!"
) ? void (0) : __assert_fail ("isValidForAlternation(Opcode) && isValidForAlternation(InstOpcode) && \"Cast isn't safe for alternation, logic needs to be updated!\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 803, __extension__
__PRETTY_FUNCTION__))
802 isValidForAlternation(InstOpcode) &&(static_cast <bool> (isValidForAlternation(Opcode) &&
isValidForAlternation(InstOpcode) && "Cast isn't safe for alternation, logic needs to be updated!"
) ? void (0) : __assert_fail ("isValidForAlternation(Opcode) && isValidForAlternation(InstOpcode) && \"Cast isn't safe for alternation, logic needs to be updated!\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 803, __extension__
__PRETTY_FUNCTION__))
803 "Cast isn't safe for alternation, logic needs to be updated!")(static_cast <bool> (isValidForAlternation(Opcode) &&
isValidForAlternation(InstOpcode) && "Cast isn't safe for alternation, logic needs to be updated!"
) ? void (0) : __assert_fail ("isValidForAlternation(Opcode) && isValidForAlternation(InstOpcode) && \"Cast isn't safe for alternation, logic needs to be updated!\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 803, __extension__
__PRETTY_FUNCTION__))
;
804 AltOpcode = InstOpcode;
805 AltIndex = Cnt;
806 continue;
807 }
808 }
809 } else if (auto *Inst = dyn_cast<CmpInst>(VL[Cnt]); Inst && IsCmpOp) {
810 auto *BaseInst = cast<CmpInst>(VL[BaseIndex]);
811 Type *Ty0 = BaseInst->getOperand(0)->getType();
812 Type *Ty1 = Inst->getOperand(0)->getType();
813 if (Ty0 == Ty1) {
814 assert(InstOpcode == Opcode && "Expected same CmpInst opcode.")(static_cast <bool> (InstOpcode == Opcode && "Expected same CmpInst opcode."
) ? void (0) : __assert_fail ("InstOpcode == Opcode && \"Expected same CmpInst opcode.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 814, __extension__
__PRETTY_FUNCTION__))
;
815 // Check for compatible operands. If the corresponding operands are not
816 // compatible - need to perform alternate vectorization.
817 CmpInst::Predicate CurrentPred = Inst->getPredicate();
818 CmpInst::Predicate SwappedCurrentPred =
819 CmpInst::getSwappedPredicate(CurrentPred);
820
821 if (E == 2 &&
822 (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
823 continue;
824
825 if (isCmpSameOrSwapped(BaseInst, Inst, TLI))
826 continue;
827 auto *AltInst = cast<CmpInst>(VL[AltIndex]);
828 if (AltIndex != BaseIndex) {
829 if (isCmpSameOrSwapped(AltInst, Inst, TLI))
830 continue;
831 } else if (BasePred != CurrentPred) {
832 assert((static_cast <bool> (isValidForAlternation(InstOpcode) &&
"CmpInst isn't safe for alternation, logic needs to be updated!"
) ? void (0) : __assert_fail ("isValidForAlternation(InstOpcode) && \"CmpInst isn't safe for alternation, logic needs to be updated!\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 834, __extension__
__PRETTY_FUNCTION__))
833 isValidForAlternation(InstOpcode) &&(static_cast <bool> (isValidForAlternation(InstOpcode) &&
"CmpInst isn't safe for alternation, logic needs to be updated!"
) ? void (0) : __assert_fail ("isValidForAlternation(InstOpcode) && \"CmpInst isn't safe for alternation, logic needs to be updated!\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 834, __extension__
__PRETTY_FUNCTION__))
834 "CmpInst isn't safe for alternation, logic needs to be updated!")(static_cast <bool> (isValidForAlternation(InstOpcode) &&
"CmpInst isn't safe for alternation, logic needs to be updated!"
) ? void (0) : __assert_fail ("isValidForAlternation(InstOpcode) && \"CmpInst isn't safe for alternation, logic needs to be updated!\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 834, __extension__
__PRETTY_FUNCTION__))
;
835 AltIndex = Cnt;
836 continue;
837 }
838 CmpInst::Predicate AltPred = AltInst->getPredicate();
839 if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
840 AltPred == CurrentPred || AltPred == SwappedCurrentPred)
841 continue;
842 }
843 } else if (InstOpcode == Opcode || InstOpcode == AltOpcode) {
844 if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) {
845 if (Gep->getNumOperands() != 2 ||
846 Gep->getOperand(0)->getType() != IBase->getOperand(0)->getType())
847 return InstructionsState(VL[BaseIndex], nullptr, nullptr);
848 } else if (auto *EI = dyn_cast<ExtractElementInst>(I)) {
849 if (!isVectorLikeInstWithConstOps(EI))
850 return InstructionsState(VL[BaseIndex], nullptr, nullptr);
851 } else if (auto *LI = dyn_cast<LoadInst>(I)) {
852 auto *BaseLI = cast<LoadInst>(IBase);
853 if (!LI->isSimple() || !BaseLI->isSimple())
854 return InstructionsState(VL[BaseIndex], nullptr, nullptr);
855 } else if (auto *Call = dyn_cast<CallInst>(I)) {
856 auto *CallBase = cast<CallInst>(IBase);
857 if (Call->getCalledFunction() != CallBase->getCalledFunction())
858 return InstructionsState(VL[BaseIndex], nullptr, nullptr);
859 if (Call->hasOperandBundles() &&
860 !std::equal(Call->op_begin() + Call->getBundleOperandsStartIndex(),
861 Call->op_begin() + Call->getBundleOperandsEndIndex(),
862 CallBase->op_begin() +
863 CallBase->getBundleOperandsStartIndex()))
864 return InstructionsState(VL[BaseIndex], nullptr, nullptr);
865 Intrinsic::ID ID = getVectorIntrinsicIDForCall(Call, &TLI);
866 if (ID != BaseID)
867 return InstructionsState(VL[BaseIndex], nullptr, nullptr);
868 if (!ID) {
869 SmallVector<VFInfo> Mappings = VFDatabase(*Call).getMappings(*Call);
870 if (Mappings.size() != BaseMappings.size() ||
871 Mappings.front().ISA != BaseMappings.front().ISA ||
872 Mappings.front().ScalarName != BaseMappings.front().ScalarName ||
873 Mappings.front().VectorName != BaseMappings.front().VectorName ||
874 Mappings.front().Shape.VF != BaseMappings.front().Shape.VF ||
875 Mappings.front().Shape.Parameters !=
876 BaseMappings.front().Shape.Parameters)
877 return InstructionsState(VL[BaseIndex], nullptr, nullptr);
878 }
879 }
880 continue;
881 }
882 return InstructionsState(VL[BaseIndex], nullptr, nullptr);
883 }
884
885 return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
886 cast<Instruction>(VL[AltIndex]));
887}
888
889/// \returns true if all of the values in \p VL have the same type or false
890/// otherwise.
891static bool allSameType(ArrayRef<Value *> VL) {
892 Type *Ty = VL[0]->getType();
893 for (int i = 1, e = VL.size(); i < e; i++)
894 if (VL[i]->getType() != Ty)
895 return false;
896
897 return true;
898}
899
900/// \returns True if in-tree use also needs extract. This refers to
901/// possible scalar operand in vectorized instruction.
902static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
903 TargetLibraryInfo *TLI) {
904 unsigned Opcode = UserInst->getOpcode();
905 switch (Opcode) {
906 case Instruction::Load: {
907 LoadInst *LI = cast<LoadInst>(UserInst);
908 return (LI->getPointerOperand() == Scalar);
909 }
910 case Instruction::Store: {
911 StoreInst *SI = cast<StoreInst>(UserInst);
912 return (SI->getPointerOperand() == Scalar);
913 }
914 case Instruction::Call: {
915 CallInst *CI = cast<CallInst>(UserInst);
916 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
917 for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
918 if (isVectorIntrinsicWithScalarOpAtArg(ID, i))
919 return (CI->getArgOperand(i) == Scalar);
920 }
921 [[fallthrough]];
922 }
923 default:
924 return false;
925 }
926}
927
928/// \returns the AA location that is being access by the instruction.
929static MemoryLocation getLocation(Instruction *I) {
930 if (StoreInst *SI = dyn_cast<StoreInst>(I))
931 return MemoryLocation::get(SI);
932 if (LoadInst *LI = dyn_cast<LoadInst>(I))
933 return MemoryLocation::get(LI);
934 return MemoryLocation();
935}
936
937/// \returns True if the instruction is not a volatile or atomic load/store.
938static bool isSimple(Instruction *I) {
939 if (LoadInst *LI = dyn_cast<LoadInst>(I))
940 return LI->isSimple();
941 if (StoreInst *SI = dyn_cast<StoreInst>(I))
942 return SI->isSimple();
943 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
944 return !MI->isVolatile();
945 return true;
946}
947
948/// Shuffles \p Mask in accordance with the given \p SubMask.
949/// \param ExtendingManyInputs Supports reshuffling of the mask with not only
950/// one but two input vectors.
951static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask,
952 bool ExtendingManyInputs = false) {
953 if (SubMask.empty())
954 return;
955 assert((!ExtendingManyInputs || SubMask.size() > Mask.size()) &&(static_cast <bool> ((!ExtendingManyInputs || SubMask.size
() > Mask.size()) && "SubMask with many inputs support must be larger than the mask."
) ? void (0) : __assert_fail ("(!ExtendingManyInputs || SubMask.size() > Mask.size()) && \"SubMask with many inputs support must be larger than the mask.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 956, __extension__
__PRETTY_FUNCTION__))
956 "SubMask with many inputs support must be larger than the mask.")(static_cast <bool> ((!ExtendingManyInputs || SubMask.size
() > Mask.size()) && "SubMask with many inputs support must be larger than the mask."
) ? void (0) : __assert_fail ("(!ExtendingManyInputs || SubMask.size() > Mask.size()) && \"SubMask with many inputs support must be larger than the mask.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 956, __extension__
__PRETTY_FUNCTION__))
;
957 if (Mask.empty()) {
958 Mask.append(SubMask.begin(), SubMask.end());
959 return;
960 }
961 SmallVector<int> NewMask(SubMask.size(), PoisonMaskElem);
962 int TermValue = std::min(Mask.size(), SubMask.size());
963 for (int I = 0, E = SubMask.size(); I < E; ++I) {
964 if ((!ExtendingManyInputs &&
965 (SubMask[I] >= TermValue || Mask[SubMask[I]] >= TermValue)) ||
966 SubMask[I] == PoisonMaskElem)
967 continue;
968 NewMask[I] = Mask[SubMask[I]];
969 }
970 Mask.swap(NewMask);
971}
972
973/// Order may have elements assigned special value (size) which is out of
974/// bounds. Such indices only appear on places which correspond to undef values
975/// (see canReuseExtract for details) and used in order to avoid undef values
976/// have effect on operands ordering.
977/// The first loop below simply finds all unused indices and then the next loop
978/// nest assigns these indices for undef values positions.
979/// As an example below Order has two undef positions and they have assigned
980/// values 3 and 7 respectively:
981/// before: 6 9 5 4 9 2 1 0
982/// after: 6 3 5 4 7 2 1 0
983static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
984 const unsigned Sz = Order.size();
985 SmallBitVector UnusedIndices(Sz, /*t=*/true);
986 SmallBitVector MaskedIndices(Sz);
987 for (unsigned I = 0; I < Sz; ++I) {
988 if (Order[I] < Sz)
989 UnusedIndices.reset(Order[I]);
990 else
991 MaskedIndices.set(I);
992 }
993 if (MaskedIndices.none())
994 return;
995 assert(UnusedIndices.count() == MaskedIndices.count() &&(static_cast <bool> (UnusedIndices.count() == MaskedIndices
.count() && "Non-synced masked/available indices.") ?
void (0) : __assert_fail ("UnusedIndices.count() == MaskedIndices.count() && \"Non-synced masked/available indices.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 996, __extension__
__PRETTY_FUNCTION__))
996 "Non-synced masked/available indices.")(static_cast <bool> (UnusedIndices.count() == MaskedIndices
.count() && "Non-synced masked/available indices.") ?
void (0) : __assert_fail ("UnusedIndices.count() == MaskedIndices.count() && \"Non-synced masked/available indices.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 996, __extension__
__PRETTY_FUNCTION__))
;
997 int Idx = UnusedIndices.find_first();
998 int MIdx = MaskedIndices.find_first();
999 while (MIdx >= 0) {
1000 assert(Idx >= 0 && "Indices must be synced.")(static_cast <bool> (Idx >= 0 && "Indices must be synced."
) ? void (0) : __assert_fail ("Idx >= 0 && \"Indices must be synced.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 1000, __extension__
__PRETTY_FUNCTION__))
;
1001 Order[MIdx] = Idx;
1002 Idx = UnusedIndices.find_next(Idx);
1003 MIdx = MaskedIndices.find_next(MIdx);
1004 }
1005}
1006
1007namespace llvm {
1008
1009static void inversePermutation(ArrayRef<unsigned> Indices,
1010 SmallVectorImpl<int> &Mask) {
1011 Mask.clear();
1012 const unsigned E = Indices.size();
1013 Mask.resize(E, PoisonMaskElem);
1014 for (unsigned I = 0; I < E; ++I)
1015 Mask[Indices[I]] = I;
1016}
1017
1018/// Reorders the list of scalars in accordance with the given \p Mask.
1019static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
1020 ArrayRef<int> Mask) {
1021 assert(!Mask.empty() && "Expected non-empty mask.")(static_cast <bool> (!Mask.empty() && "Expected non-empty mask."
) ? void (0) : __assert_fail ("!Mask.empty() && \"Expected non-empty mask.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 1021, __extension__
__PRETTY_FUNCTION__))
;
1022 SmallVector<Value *> Prev(Scalars.size(),
1023 UndefValue::get(Scalars.front()->getType()));
1024 Prev.swap(Scalars);
1025 for (unsigned I = 0, E = Prev.size(); I < E; ++I)
1026 if (Mask[I] != PoisonMaskElem)
1027 Scalars[Mask[I]] = Prev[I];
1028}
1029
1030/// Checks if the provided value does not require scheduling. It does not
1031/// require scheduling if this is not an instruction or it is an instruction
1032/// that does not read/write memory and all operands are either not instructions
1033/// or phi nodes or instructions from different blocks.
1034static bool areAllOperandsNonInsts(Value *V) {
1035 auto *I = dyn_cast<Instruction>(V);
1036 if (!I)
1037 return true;
1038 return !mayHaveNonDefUseDependency(*I) &&
1039 all_of(I->operands(), [I](Value *V) {
1040 auto *IO = dyn_cast<Instruction>(V);
1041 if (!IO)
1042 return true;
1043 return isa<PHINode>(IO) || IO->getParent() != I->getParent();
1044 });
1045}
1046
1047/// Checks if the provided value does not require scheduling. It does not
1048/// require scheduling if this is not an instruction or it is an instruction
1049/// that does not read/write memory and all users are phi nodes or instructions
1050/// from the different blocks.
1051static bool isUsedOutsideBlock(Value *V) {
1052 auto *I = dyn_cast<Instruction>(V);
1053 if (!I)
1054 return true;
1055 // Limits the number of uses to save compile time.
1056 constexpr int UsesLimit = 8;
1057 return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) &&
1058 all_of(I->users(), [I](User *U) {
1059 auto *IU = dyn_cast<Instruction>(U);
1060 if (!IU)
1061 return true;
1062 return IU->getParent() != I->getParent() || isa<PHINode>(IU);
1063 });
1064}
1065
1066/// Checks if the specified value does not require scheduling. It does not
1067/// require scheduling if all operands and all users do not need to be scheduled
1068/// in the current basic block.
1069static bool doesNotNeedToBeScheduled(Value *V) {
1070 return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V);
1071}
1072
1073/// Checks if the specified array of instructions does not require scheduling.
1074/// It is so if all either instructions have operands that do not require
1075/// scheduling or their users do not require scheduling since they are phis or
1076/// in other basic blocks.
1077static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) {
1078 return !VL.empty() &&
1079 (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts));
1080}
1081
1082namespace slpvectorizer {
1083
1084/// Bottom Up SLP Vectorizer.
1085class BoUpSLP {
1086 struct TreeEntry;
1087 struct ScheduleData;
1088 class ShuffleCostEstimator;
1089 class ShuffleInstructionBuilder;
1090
1091public:
1092 using ValueList = SmallVector<Value *, 8>;
1093 using InstrList = SmallVector<Instruction *, 16>;
1094 using ValueSet = SmallPtrSet<Value *, 16>;
1095 using StoreList = SmallVector<StoreInst *, 8>;
1096 using ExtraValueToDebugLocsMap =
1097 MapVector<Value *, SmallVector<Instruction *, 2>>;
1098 using OrdersType = SmallVector<unsigned, 4>;
1099
1100 BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
1101 TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
1102 DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
1103 const DataLayout *DL, OptimizationRemarkEmitter *ORE)
1104 : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
1105 DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
1106 CodeMetrics::collectEphemeralValues(F, AC, EphValues);
1107 // Use the vector register size specified by the target unless overridden
1108 // by a command-line option.
1109 // TODO: It would be better to limit the vectorization factor based on
1110 // data type rather than just register size. For example, x86 AVX has
1111 // 256-bit registers, but it does not support integer operations
1112 // at that width (that requires AVX2).
1113 if (MaxVectorRegSizeOption.getNumOccurrences())
1114 MaxVecRegSize = MaxVectorRegSizeOption;
1115 else
1116 MaxVecRegSize =
1117 TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
1118 .getFixedValue();
1119
1120 if (MinVectorRegSizeOption.getNumOccurrences())
1121 MinVecRegSize = MinVectorRegSizeOption;
1122 else
1123 MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
1124 }
1125
1126 /// Vectorize the tree that starts with the elements in \p VL.
1127 /// Returns the vectorized root.
1128 Value *vectorizeTree();
1129
1130 /// Vectorize the tree but with the list of externally used values \p
1131 /// ExternallyUsedValues. Values in this MapVector can be replaced but the
1132 /// generated extractvalue instructions.
1133 /// \param ReplacedExternals containd list of replaced external values
1134 /// {scalar, replace} after emitting extractelement for external uses.
1135 Value *
1136 vectorizeTree(const ExtraValueToDebugLocsMap &ExternallyUsedValues,
1137 SmallVectorImpl<std::pair<Value *, Value *>> &ReplacedExternals,
1138 Instruction *ReductionRoot = nullptr);
1139
1140 /// \returns the cost incurred by unwanted spills and fills, caused by
1141 /// holding live values over call sites.
1142 InstructionCost getSpillCost() const;
1143
1144 /// \returns the vectorization cost of the subtree that starts at \p VL.
1145 /// A negative number means that this is profitable.
1146 InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = std::nullopt);
1147
1148 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
1149 /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
1150 void buildTree(ArrayRef<Value *> Roots,
1151 const SmallDenseSet<Value *> &UserIgnoreLst);
1152
1153 /// Construct a vectorizable tree that starts at \p Roots.
1154 void buildTree(ArrayRef<Value *> Roots);
1155
1156 /// Returns whether the root node has in-tree uses.
1157 bool doesRootHaveInTreeUses() const {
1158 return !VectorizableTree.empty() &&
1159 !VectorizableTree.front()->UserTreeIndices.empty();
1160 }
1161
1162 /// Return the scalars of the root node.
1163 ArrayRef<Value *> getRootNodeScalars() const {
1164 assert(!VectorizableTree.empty() && "No graph to get the first node from")(static_cast <bool> (!VectorizableTree.empty() &&
"No graph to get the first node from") ? void (0) : __assert_fail
("!VectorizableTree.empty() && \"No graph to get the first node from\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 1164, __extension__
__PRETTY_FUNCTION__))
;
1165 return VectorizableTree.front()->Scalars;
1166 }
1167
1168 /// Builds external uses of the vectorized scalars, i.e. the list of
1169 /// vectorized scalars to be extracted, their lanes and their scalar users. \p
1170 /// ExternallyUsedValues contains additional list of external uses to handle
1171 /// vectorization of reductions.
1172 void
1173 buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
1174
1175 /// Clear the internal data structures that are created by 'buildTree'.
1176 void deleteTree() {
1177 VectorizableTree.clear();
1178 ScalarToTreeEntry.clear();
1179 MustGather.clear();
1180 EntryToLastInstruction.clear();
1181 ExternalUses.clear();
1182 for (auto &Iter : BlocksSchedules) {
1183 BlockScheduling *BS = Iter.second.get();
1184 BS->clear();
1185 }
1186 MinBWs.clear();
1187 InstrElementSize.clear();
1188 UserIgnoreList = nullptr;
1189 PostponedGathers.clear();
1190 ValueToGatherNodes.clear();
1191 }
1192
1193 unsigned getTreeSize() const { return VectorizableTree.size(); }
1194
1195 /// Perform LICM and CSE on the newly generated gather sequences.
1196 void optimizeGatherSequence();
1197
1198 /// Checks if the specified gather tree entry \p TE can be represented as a
1199 /// shuffled vector entry + (possibly) permutation with other gathers. It
1200 /// implements the checks only for possibly ordered scalars (Loads,
1201 /// ExtractElement, ExtractValue), which can be part of the graph.
1202 std::optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
1203
1204 /// Sort loads into increasing pointers offsets to allow greater clustering.
1205 std::optional<OrdersType> findPartiallyOrderedLoads(const TreeEntry &TE);
1206
1207 /// Gets reordering data for the given tree entry. If the entry is vectorized
1208 /// - just return ReorderIndices, otherwise check if the scalars can be
1209 /// reordered and return the most optimal order.
1210 /// \return std::nullopt if ordering is not important, empty order, if
1211 /// identity order is important, or the actual order.
1212 /// \param TopToBottom If true, include the order of vectorized stores and
1213 /// insertelement nodes, otherwise skip them.
1214 std::optional<OrdersType> getReorderingData(const TreeEntry &TE,
1215 bool TopToBottom);
1216
1217 /// Reorders the current graph to the most profitable order starting from the
1218 /// root node to the leaf nodes. The best order is chosen only from the nodes
1219 /// of the same size (vectorization factor). Smaller nodes are considered
1220 /// parts of subgraph with smaller VF and they are reordered independently. We
1221 /// can make it because we still need to extend smaller nodes to the wider VF
1222 /// and we can merge reordering shuffles with the widening shuffles.
1223 void reorderTopToBottom();
1224
1225 /// Reorders the current graph to the most profitable order starting from
1226 /// leaves to the root. It allows to rotate small subgraphs and reduce the
1227 /// number of reshuffles if the leaf nodes use the same order. In this case we
1228 /// can merge the orders and just shuffle user node instead of shuffling its
1229 /// operands. Plus, even the leaf nodes have different orders, it allows to
1230 /// sink reordering in the graph closer to the root node and merge it later
1231 /// during analysis.
1232 void reorderBottomToTop(bool IgnoreReorder = false);
1233
1234 /// \return The vector element size in bits to use when vectorizing the
1235 /// expression tree ending at \p V. If V is a store, the size is the width of
1236 /// the stored value. Otherwise, the size is the width of the largest loaded
1237 /// value reaching V. This method is used by the vectorizer to calculate
1238 /// vectorization factors.
1239 unsigned getVectorElementSize(Value *V);
1240
1241 /// Compute the minimum type sizes required to represent the entries in a
1242 /// vectorizable tree.
1243 void computeMinimumValueSizes();
1244
1245 // \returns maximum vector register size as set by TTI or overridden by cl::opt.
1246 unsigned getMaxVecRegSize() const {
1247 return MaxVecRegSize;
1248 }
1249
1250 // \returns minimum vector register size as set by cl::opt.
1251 unsigned getMinVecRegSize() const {
1252 return MinVecRegSize;
1253 }
1254
1255 unsigned getMinVF(unsigned Sz) const {
1256 return std::max(2U, getMinVecRegSize() / Sz);
1257 }
1258
1259 unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
1260 unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
1261 MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
1262 return MaxVF ? MaxVF : UINT_MAX(2147483647 *2U +1U);
1263 }
1264
1265 /// Check if homogeneous aggregate is isomorphic to some VectorType.
1266 /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
1267 /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
1268 /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
1269 ///
1270 /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
1271 unsigned canMapToVector(Type *T, const DataLayout &DL) const;
1272
1273 /// \returns True if the VectorizableTree is both tiny and not fully
1274 /// vectorizable. We do not vectorize such trees.
1275 bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
1276
1277 /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
1278 /// can be load combined in the backend. Load combining may not be allowed in
1279 /// the IR optimizer, so we do not want to alter the pattern. For example,
1280 /// partially transforming a scalar bswap() pattern into vector code is
1281 /// effectively impossible for the backend to undo.
1282 /// TODO: If load combining is allowed in the IR optimizer, this analysis
1283 /// may not be necessary.
1284 bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
1285
1286 /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
1287 /// can be load combined in the backend. Load combining may not be allowed in
1288 /// the IR optimizer, so we do not want to alter the pattern. For example,
1289 /// partially transforming a scalar bswap() pattern into vector code is
1290 /// effectively impossible for the backend to undo.
1291 /// TODO: If load combining is allowed in the IR optimizer, this analysis
1292 /// may not be necessary.
1293 bool isLoadCombineCandidate() const;
1294
1295 OptimizationRemarkEmitter *getORE() { return ORE; }
1296
1297 /// This structure holds any data we need about the edges being traversed
1298 /// during buildTree_rec(). We keep track of:
1299 /// (i) the user TreeEntry index, and
1300 /// (ii) the index of the edge.
1301 struct EdgeInfo {
1302 EdgeInfo() = default;
1303 EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1304 : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
1305 /// The user TreeEntry.
1306 TreeEntry *UserTE = nullptr;
1307 /// The operand index of the use.
1308 unsigned EdgeIdx = UINT_MAX(2147483647 *2U +1U);
1309#ifndef NDEBUG
1310 friend inline raw_ostream &operator<<(raw_ostream &OS,
1311 const BoUpSLP::EdgeInfo &EI) {
1312 EI.dump(OS);
1313 return OS;
1314 }
1315 /// Debug print.
1316 void dump(raw_ostream &OS) const {
1317 OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1318 << " EdgeIdx:" << EdgeIdx << "}";
1319 }
1320 LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void dump() const { dump(dbgs()); }
1321#endif
1322 };
1323
1324 /// A helper class used for scoring candidates for two consecutive lanes.
1325 class LookAheadHeuristics {
1326 const TargetLibraryInfo &TLI;
1327 const DataLayout &DL;
1328 ScalarEvolution &SE;
1329 const BoUpSLP &R;
1330 int NumLanes; // Total number of lanes (aka vectorization factor).
1331 int MaxLevel; // The maximum recursion depth for accumulating score.
1332
1333 public:
1334 LookAheadHeuristics(const TargetLibraryInfo &TLI, const DataLayout &DL,
1335 ScalarEvolution &SE, const BoUpSLP &R, int NumLanes,
1336 int MaxLevel)
1337 : TLI(TLI), DL(DL), SE(SE), R(R), NumLanes(NumLanes),
1338 MaxLevel(MaxLevel) {}
1339
1340 // The hard-coded scores listed here are not very important, though it shall
1341 // be higher for better matches to improve the resulting cost. When
1342 // computing the scores of matching one sub-tree with another, we are
1343 // basically counting the number of values that are matching. So even if all
1344 // scores are set to 1, we would still get a decent matching result.
1345 // However, sometimes we have to break ties. For example we may have to
1346 // choose between matching loads vs matching opcodes. This is what these
1347 // scores are helping us with: they provide the order of preference. Also,
1348 // this is important if the scalar is externally used or used in another
1349 // tree entry node in the different lane.
1350
1351 /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1352 static const int ScoreConsecutiveLoads = 4;
1353 /// The same load multiple times. This should have a better score than
1354 /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it
1355 /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for
1356 /// a vector load and 1.0 for a broadcast.
1357 static const int ScoreSplatLoads = 3;
1358 /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1359 static const int ScoreReversedLoads = 3;
1360 /// A load candidate for masked gather.
1361 static const int ScoreMaskedGatherCandidate = 1;
1362 /// ExtractElementInst from same vector and consecutive indexes.
1363 static const int ScoreConsecutiveExtracts = 4;
1364 /// ExtractElementInst from same vector and reversed indices.
1365 static const int ScoreReversedExtracts = 3;
1366 /// Constants.
1367 static const int ScoreConstants = 2;
1368 /// Instructions with the same opcode.
1369 static const int ScoreSameOpcode = 2;
1370 /// Instructions with alt opcodes (e.g, add + sub).
1371 static const int ScoreAltOpcodes = 1;
1372 /// Identical instructions (a.k.a. splat or broadcast).
1373 static const int ScoreSplat = 1;
1374 /// Matching with an undef is preferable to failing.
1375 static const int ScoreUndef = 1;
1376 /// Score for failing to find a decent match.
1377 static const int ScoreFail = 0;
1378 /// Score if all users are vectorized.
1379 static const int ScoreAllUserVectorized = 1;
1380
1381 /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1382 /// \p U1 and \p U2 are the users of \p V1 and \p V2.
1383 /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1384 /// MainAltOps.
1385 int getShallowScore(Value *V1, Value *V2, Instruction *U1, Instruction *U2,
1386 ArrayRef<Value *> MainAltOps) const {
1387 if (!isValidElementType(V1->getType()) ||
1388 !isValidElementType(V2->getType()))
1389 return LookAheadHeuristics::ScoreFail;
1390
1391 if (V1 == V2) {
1392 if (isa<LoadInst>(V1)) {
1393 // Retruns true if the users of V1 and V2 won't need to be extracted.
1394 auto AllUsersAreInternal = [U1, U2, this](Value *V1, Value *V2) {
1395 // Bail out if we have too many uses to save compilation time.
1396 static constexpr unsigned Limit = 8;
1397 if (V1->hasNUsesOrMore(Limit) || V2->hasNUsesOrMore(Limit))
1398 return false;
1399
1400 auto AllUsersVectorized = [U1, U2, this](Value *V) {
1401 return llvm::all_of(V->users(), [U1, U2, this](Value *U) {
1402 return U == U1 || U == U2 || R.getTreeEntry(U) != nullptr;
1403 });
1404 };
1405 return AllUsersVectorized(V1) && AllUsersVectorized(V2);
1406 };
1407 // A broadcast of a load can be cheaper on some targets.
1408 if (R.TTI->isLegalBroadcastLoad(V1->getType(),
1409 ElementCount::getFixed(NumLanes)) &&
1410 ((int)V1->getNumUses() == NumLanes ||
1411 AllUsersAreInternal(V1, V2)))
1412 return LookAheadHeuristics::ScoreSplatLoads;
1413 }
1414 return LookAheadHeuristics::ScoreSplat;
1415 }
1416
1417 auto *LI1 = dyn_cast<LoadInst>(V1);
1418 auto *LI2 = dyn_cast<LoadInst>(V2);
1419 if (LI1 && LI2) {
1420 if (LI1->getParent() != LI2->getParent() || !LI1->isSimple() ||
1421 !LI2->isSimple())
1422 return LookAheadHeuristics::ScoreFail;
1423
1424 std::optional<int> Dist = getPointersDiff(
1425 LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1426 LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1427 if (!Dist || *Dist == 0) {
1428 if (getUnderlyingObject(LI1->getPointerOperand()) ==
1429 getUnderlyingObject(LI2->getPointerOperand()) &&
1430 R.TTI->isLegalMaskedGather(
1431 FixedVectorType::get(LI1->getType(), NumLanes),
1432 LI1->getAlign()))
1433 return LookAheadHeuristics::ScoreMaskedGatherCandidate;
1434 return LookAheadHeuristics::ScoreFail;
1435 }
1436 // The distance is too large - still may be profitable to use masked
1437 // loads/gathers.
1438 if (std::abs(*Dist) > NumLanes / 2)
1439 return LookAheadHeuristics::ScoreMaskedGatherCandidate;
1440 // This still will detect consecutive loads, but we might have "holes"
1441 // in some cases. It is ok for non-power-2 vectorization and may produce
1442 // better results. It should not affect current vectorization.
1443 return (*Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveLoads
1444 : LookAheadHeuristics::ScoreReversedLoads;
1445 }
1446
1447 auto *C1 = dyn_cast<Constant>(V1);
1448 auto *C2 = dyn_cast<Constant>(V2);
1449 if (C1 && C2)
1450 return LookAheadHeuristics::ScoreConstants;
1451
1452 // Extracts from consecutive indexes of the same vector better score as
1453 // the extracts could be optimized away.
1454 Value *EV1;
1455 ConstantInt *Ex1Idx;
1456 if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1457 // Undefs are always profitable for extractelements.
1458 // Compiler can easily combine poison and extractelement <non-poison> or
1459 // undef and extractelement <poison>. But combining undef +
1460 // extractelement <non-poison-but-may-produce-poison> requires some
1461 // extra operations.
1462 if (isa<UndefValue>(V2))
1463 return (isa<PoisonValue>(V2) || isUndefVector(EV1).all())
1464 ? LookAheadHeuristics::ScoreConsecutiveExtracts
1465 : LookAheadHeuristics::ScoreSameOpcode;
1466 Value *EV2 = nullptr;
1467 ConstantInt *Ex2Idx = nullptr;
1468 if (match(V2,
1469 m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1470 m_Undef())))) {
1471 // Undefs are always profitable for extractelements.
1472 if (!Ex2Idx)
1473 return LookAheadHeuristics::ScoreConsecutiveExtracts;
1474 if (isUndefVector(EV2).all() && EV2->getType() == EV1->getType())
1475 return LookAheadHeuristics::ScoreConsecutiveExtracts;
1476 if (EV2 == EV1) {
1477 int Idx1 = Ex1Idx->getZExtValue();
1478 int Idx2 = Ex2Idx->getZExtValue();
1479 int Dist = Idx2 - Idx1;
1480 // The distance is too large - still may be profitable to use
1481 // shuffles.
1482 if (std::abs(Dist) == 0)
1483 return LookAheadHeuristics::ScoreSplat;
1484 if (std::abs(Dist) > NumLanes / 2)
1485 return LookAheadHeuristics::ScoreSameOpcode;
1486 return (Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveExtracts
1487 : LookAheadHeuristics::ScoreReversedExtracts;
1488 }
1489 return LookAheadHeuristics::ScoreAltOpcodes;
1490 }
1491 return LookAheadHeuristics::ScoreFail;
1492 }
1493
1494 auto *I1 = dyn_cast<Instruction>(V1);
1495 auto *I2 = dyn_cast<Instruction>(V2);
1496 if (I1 && I2) {
1497 if (I1->getParent() != I2->getParent())
1498 return LookAheadHeuristics::ScoreFail;
1499 SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1500 Ops.push_back(I1);
1501 Ops.push_back(I2);
1502 InstructionsState S = getSameOpcode(Ops, TLI);
1503 // Note: Only consider instructions with <= 2 operands to avoid
1504 // complexity explosion.
1505 if (S.getOpcode() &&
1506 (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1507 !S.isAltShuffle()) &&
1508 all_of(Ops, [&S](Value *V) {
1509 return cast<Instruction>(V)->getNumOperands() ==
1510 S.MainOp->getNumOperands();
1511 }))
1512 return S.isAltShuffle() ? LookAheadHeuristics::ScoreAltOpcodes
1513 : LookAheadHeuristics::ScoreSameOpcode;
1514 }
1515
1516 if (isa<UndefValue>(V2))
1517 return LookAheadHeuristics::ScoreUndef;
1518
1519 return LookAheadHeuristics::ScoreFail;
1520 }
1521
1522 /// Go through the operands of \p LHS and \p RHS recursively until
1523 /// MaxLevel, and return the cummulative score. \p U1 and \p U2 are
1524 /// the users of \p LHS and \p RHS (that is \p LHS and \p RHS are operands
1525 /// of \p U1 and \p U2), except at the beginning of the recursion where
1526 /// these are set to nullptr.
1527 ///
1528 /// For example:
1529 /// \verbatim
1530 /// A[0] B[0] A[1] B[1] C[0] D[0] B[1] A[1]
1531 /// \ / \ / \ / \ /
1532 /// + + + +
1533 /// G1 G2 G3 G4
1534 /// \endverbatim
1535 /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1536 /// each level recursively, accumulating the score. It starts from matching
1537 /// the additions at level 0, then moves on to the loads (level 1). The
1538 /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1539 /// {B[0],B[1]} match with LookAheadHeuristics::ScoreConsecutiveLoads, while
1540 /// {A[0],C[0]} has a score of LookAheadHeuristics::ScoreFail.
1541 /// Please note that the order of the operands does not matter, as we
1542 /// evaluate the score of all profitable combinations of operands. In
1543 /// other words the score of G1 and G4 is the same as G1 and G2. This
1544 /// heuristic is based on ideas described in:
1545 /// Look-ahead SLP: Auto-vectorization in the presence of commutative
1546 /// operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1547 /// Luís F. W. Góes
1548 int getScoreAtLevelRec(Value *LHS, Value *RHS, Instruction *U1,
1549 Instruction *U2, int CurrLevel,
1550 ArrayRef<Value *> MainAltOps) const {
1551
1552 // Get the shallow score of V1 and V2.
1553 int ShallowScoreAtThisLevel =
1554 getShallowScore(LHS, RHS, U1, U2, MainAltOps);
1555
1556 // If reached MaxLevel,
1557 // or if V1 and V2 are not instructions,
1558 // or if they are SPLAT,
1559 // or if they are not consecutive,
1560 // or if profitable to vectorize loads or extractelements, early return
1561 // the current cost.
1562 auto *I1 = dyn_cast<Instruction>(LHS);
1563 auto *I2 = dyn_cast<Instruction>(RHS);
1564 if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1565 ShallowScoreAtThisLevel == LookAheadHeuristics::ScoreFail ||
1566 (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1567 (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1568 (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1569 ShallowScoreAtThisLevel))
1570 return ShallowScoreAtThisLevel;
1571 assert(I1 && I2 && "Should have early exited.")(static_cast <bool> (I1 && I2 && "Should have early exited."
) ? void (0) : __assert_fail ("I1 && I2 && \"Should have early exited.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 1571, __extension__
__PRETTY_FUNCTION__))
;
1572
1573 // Contains the I2 operand indexes that got matched with I1 operands.
1574 SmallSet<unsigned, 4> Op2Used;
1575
1576 // Recursion towards the operands of I1 and I2. We are trying all possible
1577 // operand pairs, and keeping track of the best score.
1578 for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1579 OpIdx1 != NumOperands1; ++OpIdx1) {
1580 // Try to pair op1I with the best operand of I2.
1581 int MaxTmpScore = 0;
1582 unsigned MaxOpIdx2 = 0;
1583 bool FoundBest = false;
1584 // If I2 is commutative try all combinations.
1585 unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1586 unsigned ToIdx = isCommutative(I2)
1587 ? I2->getNumOperands()
1588 : std::min(I2->getNumOperands(), OpIdx1 + 1);
1589 assert(FromIdx <= ToIdx && "Bad index")(static_cast <bool> (FromIdx <= ToIdx && "Bad index"
) ? void (0) : __assert_fail ("FromIdx <= ToIdx && \"Bad index\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 1589, __extension__
__PRETTY_FUNCTION__))
;
1590 for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1591 // Skip operands already paired with OpIdx1.
1592 if (Op2Used.count(OpIdx2))
1593 continue;
1594 // Recursively calculate the cost at each level
1595 int TmpScore =
1596 getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1597 I1, I2, CurrLevel + 1, std::nullopt);
1598 // Look for the best score.
1599 if (TmpScore > LookAheadHeuristics::ScoreFail &&
1600 TmpScore > MaxTmpScore) {
1601 MaxTmpScore = TmpScore;
1602 MaxOpIdx2 = OpIdx2;
1603 FoundBest = true;
1604 }
1605 }
1606 if (FoundBest) {
1607 // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1608 Op2Used.insert(MaxOpIdx2);
1609 ShallowScoreAtThisLevel += MaxTmpScore;
1610 }
1611 }
1612 return ShallowScoreAtThisLevel;
1613 }
1614 };
1615 /// A helper data structure to hold the operands of a vector of instructions.
1616 /// This supports a fixed vector length for all operand vectors.
1617 class VLOperands {
1618 /// For each operand we need (i) the value, and (ii) the opcode that it
1619 /// would be attached to if the expression was in a left-linearized form.
1620 /// This is required to avoid illegal operand reordering.
1621 /// For example:
1622 /// \verbatim
1623 /// 0 Op1
1624 /// |/
1625 /// Op1 Op2 Linearized + Op2
1626 /// \ / ----------> |/
1627 /// - -
1628 ///
1629 /// Op1 - Op2 (0 + Op1) - Op2
1630 /// \endverbatim
1631 ///
1632 /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1633 ///
1634 /// Another way to think of this is to track all the operations across the
1635 /// path from the operand all the way to the root of the tree and to
1636 /// calculate the operation that corresponds to this path. For example, the
1637 /// path from Op2 to the root crosses the RHS of the '-', therefore the
1638 /// corresponding operation is a '-' (which matches the one in the
1639 /// linearized tree, as shown above).
1640 ///
1641 /// For lack of a better term, we refer to this operation as Accumulated
1642 /// Path Operation (APO).
1643 struct OperandData {
1644 OperandData() = default;
1645 OperandData(Value *V, bool APO, bool IsUsed)
1646 : V(V), APO(APO), IsUsed(IsUsed) {}
1647 /// The operand value.
1648 Value *V = nullptr;
1649 /// TreeEntries only allow a single opcode, or an alternate sequence of
1650 /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1651 /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1652 /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1653 /// (e.g., Add/Mul)
1654 bool APO = false;
1655 /// Helper data for the reordering function.
1656 bool IsUsed = false;
1657 };
1658
1659 /// During operand reordering, we are trying to select the operand at lane
1660 /// that matches best with the operand at the neighboring lane. Our
1661 /// selection is based on the type of value we are looking for. For example,
1662 /// if the neighboring lane has a load, we need to look for a load that is
1663 /// accessing a consecutive address. These strategies are summarized in the
1664 /// 'ReorderingMode' enumerator.
1665 enum class ReorderingMode {
1666 Load, ///< Matching loads to consecutive memory addresses
1667 Opcode, ///< Matching instructions based on opcode (same or alternate)
1668 Constant, ///< Matching constants
1669 Splat, ///< Matching the same instruction multiple times (broadcast)
1670 Failed, ///< We failed to create a vectorizable group
1671 };
1672
1673 using OperandDataVec = SmallVector<OperandData, 2>;
1674
1675 /// A vector of operand vectors.
1676 SmallVector<OperandDataVec, 4> OpsVec;
1677
1678 const TargetLibraryInfo &TLI;
1679 const DataLayout &DL;
1680 ScalarEvolution &SE;
1681 const BoUpSLP &R;
1682
1683 /// \returns the operand data at \p OpIdx and \p Lane.
1684 OperandData &getData(unsigned OpIdx, unsigned Lane) {
1685 return OpsVec[OpIdx][Lane];
1686 }
1687
1688 /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1689 const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1690 return OpsVec[OpIdx][Lane];
1691 }
1692
1693 /// Clears the used flag for all entries.
1694 void clearUsed() {
1695 for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1696 OpIdx != NumOperands; ++OpIdx)
1697 for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1698 ++Lane)
1699 OpsVec[OpIdx][Lane].IsUsed = false;
1700 }
1701
1702 /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1703 void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1704 std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1705 }
1706
1707 /// \param Lane lane of the operands under analysis.
1708 /// \param OpIdx operand index in \p Lane lane we're looking the best
1709 /// candidate for.
1710 /// \param Idx operand index of the current candidate value.
1711 /// \returns The additional score due to possible broadcasting of the
1712 /// elements in the lane. It is more profitable to have power-of-2 unique
1713 /// elements in the lane, it will be vectorized with higher probability
1714 /// after removing duplicates. Currently the SLP vectorizer supports only
1715 /// vectorization of the power-of-2 number of unique scalars.
1716 int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1717 Value *IdxLaneV = getData(Idx, Lane).V;
1718 if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1719 return 0;
1720 SmallPtrSet<Value *, 4> Uniques;
1721 for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1722 if (Ln == Lane)
1723 continue;
1724 Value *OpIdxLnV = getData(OpIdx, Ln).V;
1725 if (!isa<Instruction>(OpIdxLnV))
1726 return 0;
1727 Uniques.insert(OpIdxLnV);
1728 }
1729 int UniquesCount = Uniques.size();
1730 int UniquesCntWithIdxLaneV =
1731 Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1732 Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1733 int UniquesCntWithOpIdxLaneV =
1734 Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1735 if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1736 return 0;
1737 return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1738 UniquesCntWithOpIdxLaneV) -
1739 (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1740 }
1741
1742 /// \param Lane lane of the operands under analysis.
1743 /// \param OpIdx operand index in \p Lane lane we're looking the best
1744 /// candidate for.
1745 /// \param Idx operand index of the current candidate value.
1746 /// \returns The additional score for the scalar which users are all
1747 /// vectorized.
1748 int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1749 Value *IdxLaneV = getData(Idx, Lane).V;
1750 Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1751 // Do not care about number of uses for vector-like instructions
1752 // (extractelement/extractvalue with constant indices), they are extracts
1753 // themselves and already externally used. Vectorization of such
1754 // instructions does not add extra extractelement instruction, just may
1755 // remove it.
1756 if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1757 isVectorLikeInstWithConstOps(OpIdxLaneV))
1758 return LookAheadHeuristics::ScoreAllUserVectorized;
1759 auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1760 if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1761 return 0;
1762 return R.areAllUsersVectorized(IdxLaneI, std::nullopt)
1763 ? LookAheadHeuristics::ScoreAllUserVectorized
1764 : 0;
1765 }
1766
1767 /// Score scaling factor for fully compatible instructions but with
1768 /// different number of external uses. Allows better selection of the
1769 /// instructions with less external uses.
1770 static const int ScoreScaleFactor = 10;
1771
1772 /// \Returns the look-ahead score, which tells us how much the sub-trees
1773 /// rooted at \p LHS and \p RHS match, the more they match the higher the
1774 /// score. This helps break ties in an informed way when we cannot decide on
1775 /// the order of the operands by just considering the immediate
1776 /// predecessors.
1777 int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1778 int Lane, unsigned OpIdx, unsigned Idx,
1779 bool &IsUsed) {
1780 LookAheadHeuristics LookAhead(TLI, DL, SE, R, getNumLanes(),
1781 LookAheadMaxDepth);
1782 // Keep track of the instruction stack as we recurse into the operands
1783 // during the look-ahead score exploration.
1784 int Score =
1785 LookAhead.getScoreAtLevelRec(LHS, RHS, /*U1=*/nullptr, /*U2=*/nullptr,
1786 /*CurrLevel=*/1, MainAltOps);
1787 if (Score) {
1788 int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1789 if (Score <= -SplatScore) {
1790 // Set the minimum score for splat-like sequence to avoid setting
1791 // failed state.
1792 Score = 1;
1793 } else {
1794 Score += SplatScore;
1795 // Scale score to see the difference between different operands
1796 // and similar operands but all vectorized/not all vectorized
1797 // uses. It does not affect actual selection of the best
1798 // compatible operand in general, just allows to select the
1799 // operand with all vectorized uses.
1800 Score *= ScoreScaleFactor;
1801 Score += getExternalUseScore(Lane, OpIdx, Idx);
1802 IsUsed = true;
1803 }
1804 }
1805 return Score;
1806 }
1807
1808 /// Best defined scores per lanes between the passes. Used to choose the
1809 /// best operand (with the highest score) between the passes.
1810 /// The key - {Operand Index, Lane}.
1811 /// The value - the best score between the passes for the lane and the
1812 /// operand.
1813 SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1814 BestScoresPerLanes;
1815
1816 // Search all operands in Ops[*][Lane] for the one that matches best
1817 // Ops[OpIdx][LastLane] and return its opreand index.
1818 // If no good match can be found, return std::nullopt.
1819 std::optional<unsigned>
1820 getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1821 ArrayRef<ReorderingMode> ReorderingModes,
1822 ArrayRef<Value *> MainAltOps) {
1823 unsigned NumOperands = getNumOperands();
1824
1825 // The operand of the previous lane at OpIdx.
1826 Value *OpLastLane = getData(OpIdx, LastLane).V;
1827
1828 // Our strategy mode for OpIdx.
1829 ReorderingMode RMode = ReorderingModes[OpIdx];
1830 if (RMode == ReorderingMode::Failed)
1831 return std::nullopt;
1832
1833 // The linearized opcode of the operand at OpIdx, Lane.
1834 bool OpIdxAPO = getData(OpIdx, Lane).APO;
1835
1836 // The best operand index and its score.
1837 // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1838 // are using the score to differentiate between the two.
1839 struct BestOpData {
1840 std::optional<unsigned> Idx;
1841 unsigned Score = 0;
1842 } BestOp;
1843 BestOp.Score =
1844 BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1845 .first->second;
1846
1847 // Track if the operand must be marked as used. If the operand is set to
1848 // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1849 // want to reestimate the operands again on the following iterations).
1850 bool IsUsed =
1851 RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1852 // Iterate through all unused operands and look for the best.
1853 for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1854 // Get the operand at Idx and Lane.
1855 OperandData &OpData = getData(Idx, Lane);
1856 Value *Op = OpData.V;
1857 bool OpAPO = OpData.APO;
1858
1859 // Skip already selected operands.
1860 if (OpData.IsUsed)
1861 continue;
1862
1863 // Skip if we are trying to move the operand to a position with a
1864 // different opcode in the linearized tree form. This would break the
1865 // semantics.
1866 if (OpAPO != OpIdxAPO)
1867 continue;
1868
1869 // Look for an operand that matches the current mode.
1870 switch (RMode) {
1871 case ReorderingMode::Load:
1872 case ReorderingMode::Constant:
1873 case ReorderingMode::Opcode: {
1874 bool LeftToRight = Lane > LastLane;
1875 Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1876 Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1877 int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1878 OpIdx, Idx, IsUsed);
1879 if (Score > static_cast<int>(BestOp.Score)) {
1880 BestOp.Idx = Idx;
1881 BestOp.Score = Score;
1882 BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1883 }
1884 break;
1885 }
1886 case ReorderingMode::Splat:
1887 if (Op == OpLastLane)
1888 BestOp.Idx = Idx;
1889 break;
1890 case ReorderingMode::Failed:
1891 llvm_unreachable("Not expected Failed reordering mode.")::llvm::llvm_unreachable_internal("Not expected Failed reordering mode."
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 1891)
;
1892 }
1893 }
1894
1895 if (BestOp.Idx) {
1896 getData(*BestOp.Idx, Lane).IsUsed = IsUsed;
1897 return BestOp.Idx;
1898 }
1899 // If we could not find a good match return std::nullopt.
1900 return std::nullopt;
1901 }
1902
1903 /// Helper for reorderOperandVecs.
1904 /// \returns the lane that we should start reordering from. This is the one
1905 /// which has the least number of operands that can freely move about or
1906 /// less profitable because it already has the most optimal set of operands.
1907 unsigned getBestLaneToStartReordering() const {
1908 unsigned Min = UINT_MAX(2147483647 *2U +1U);
1909 unsigned SameOpNumber = 0;
1910 // std::pair<unsigned, unsigned> is used to implement a simple voting
1911 // algorithm and choose the lane with the least number of operands that
1912 // can freely move about or less profitable because it already has the
1913 // most optimal set of operands. The first unsigned is a counter for
1914 // voting, the second unsigned is the counter of lanes with instructions
1915 // with same/alternate opcodes and same parent basic block.
1916 MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1917 // Try to be closer to the original results, if we have multiple lanes
1918 // with same cost. If 2 lanes have the same cost, use the one with the
1919 // lowest index.
1920 for (int I = getNumLanes(); I > 0; --I) {
1921 unsigned Lane = I - 1;
1922 OperandsOrderData NumFreeOpsHash =
1923 getMaxNumOperandsThatCanBeReordered(Lane);
1924 // Compare the number of operands that can move and choose the one with
1925 // the least number.
1926 if (NumFreeOpsHash.NumOfAPOs < Min) {
1927 Min = NumFreeOpsHash.NumOfAPOs;
1928 SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1929 HashMap.clear();
1930 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1931 } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1932 NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1933 // Select the most optimal lane in terms of number of operands that
1934 // should be moved around.
1935 SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1936 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1937 } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1938 NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1939 auto It = HashMap.find(NumFreeOpsHash.Hash);
1940 if (It == HashMap.end())
1941 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1942 else
1943 ++It->second.first;
1944 }
1945 }
1946 // Select the lane with the minimum counter.
1947 unsigned BestLane = 0;
1948 unsigned CntMin = UINT_MAX(2147483647 *2U +1U);
1949 for (const auto &Data : reverse(HashMap)) {
1950 if (Data.second.first < CntMin) {
1951 CntMin = Data.second.first;
1952 BestLane = Data.second.second;
1953 }
1954 }
1955 return BestLane;
1956 }
1957
1958 /// Data structure that helps to reorder operands.
1959 struct OperandsOrderData {
1960 /// The best number of operands with the same APOs, which can be
1961 /// reordered.
1962 unsigned NumOfAPOs = UINT_MAX(2147483647 *2U +1U);
1963 /// Number of operands with the same/alternate instruction opcode and
1964 /// parent.
1965 unsigned NumOpsWithSameOpcodeParent = 0;
1966 /// Hash for the actual operands ordering.
1967 /// Used to count operands, actually their position id and opcode
1968 /// value. It is used in the voting mechanism to find the lane with the
1969 /// least number of operands that can freely move about or less profitable
1970 /// because it already has the most optimal set of operands. Can be
1971 /// replaced with SmallVector<unsigned> instead but hash code is faster
1972 /// and requires less memory.
1973 unsigned Hash = 0;
1974 };
1975 /// \returns the maximum number of operands that are allowed to be reordered
1976 /// for \p Lane and the number of compatible instructions(with the same
1977 /// parent/opcode). This is used as a heuristic for selecting the first lane
1978 /// to start operand reordering.
1979 OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1980 unsigned CntTrue = 0;
1981 unsigned NumOperands = getNumOperands();
1982 // Operands with the same APO can be reordered. We therefore need to count
1983 // how many of them we have for each APO, like this: Cnt[APO] = x.
1984 // Since we only have two APOs, namely true and false, we can avoid using
1985 // a map. Instead we can simply count the number of operands that
1986 // correspond to one of them (in this case the 'true' APO), and calculate
1987 // the other by subtracting it from the total number of operands.
1988 // Operands with the same instruction opcode and parent are more
1989 // profitable since we don't need to move them in many cases, with a high
1990 // probability such lane already can be vectorized effectively.
1991 bool AllUndefs = true;
1992 unsigned NumOpsWithSameOpcodeParent = 0;
1993 Instruction *OpcodeI = nullptr;
1994 BasicBlock *Parent = nullptr;
1995 unsigned Hash = 0;
1996 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1997 const OperandData &OpData = getData(OpIdx, Lane);
1998 if (OpData.APO)
1999 ++CntTrue;
2000 // Use Boyer-Moore majority voting for finding the majority opcode and
2001 // the number of times it occurs.
2002 if (auto *I = dyn_cast<Instruction>(OpData.V)) {
2003 if (!OpcodeI || !getSameOpcode({OpcodeI, I}, TLI).getOpcode() ||
2004 I->getParent() != Parent) {
2005 if (NumOpsWithSameOpcodeParent == 0) {
2006 NumOpsWithSameOpcodeParent = 1;
2007 OpcodeI = I;
2008 Parent = I->getParent();
2009 } else {
2010 --NumOpsWithSameOpcodeParent;
2011 }
2012 } else {
2013 ++NumOpsWithSameOpcodeParent;
2014 }
2015 }
2016 Hash = hash_combine(
2017 Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
2018 AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
2019 }
2020 if (AllUndefs)
2021 return {};
2022 OperandsOrderData Data;
2023 Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
2024 Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
2025 Data.Hash = Hash;
2026 return Data;
2027 }
2028
2029 /// Go through the instructions in VL and append their operands.
2030 void appendOperandsOfVL(ArrayRef<Value *> VL) {
2031 assert(!VL.empty() && "Bad VL")(static_cast <bool> (!VL.empty() && "Bad VL") ?
void (0) : __assert_fail ("!VL.empty() && \"Bad VL\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2031, __extension__
__PRETTY_FUNCTION__))
;
2032 assert((empty() || VL.size() == getNumLanes()) &&(static_cast <bool> ((empty() || VL.size() == getNumLanes
()) && "Expected same number of lanes") ? void (0) : __assert_fail
("(empty() || VL.size() == getNumLanes()) && \"Expected same number of lanes\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2033, __extension__
__PRETTY_FUNCTION__))
2033 "Expected same number of lanes")(static_cast <bool> ((empty() || VL.size() == getNumLanes
()) && "Expected same number of lanes") ? void (0) : __assert_fail
("(empty() || VL.size() == getNumLanes()) && \"Expected same number of lanes\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2033, __extension__
__PRETTY_FUNCTION__))
;
2034 assert(isa<Instruction>(VL[0]) && "Expected instruction")(static_cast <bool> (isa<Instruction>(VL[0]) &&
"Expected instruction") ? void (0) : __assert_fail ("isa<Instruction>(VL[0]) && \"Expected instruction\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2034, __extension__
__PRETTY_FUNCTION__))
;
2035 unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
2036 OpsVec.resize(NumOperands);
2037 unsigned NumLanes = VL.size();
2038 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
2039 OpsVec[OpIdx].resize(NumLanes);
2040 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2041 assert(isa<Instruction>(VL[Lane]) && "Expected instruction")(static_cast <bool> (isa<Instruction>(VL[Lane]) &&
"Expected instruction") ? void (0) : __assert_fail ("isa<Instruction>(VL[Lane]) && \"Expected instruction\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2041, __extension__
__PRETTY_FUNCTION__))
;
2042 // Our tree has just 3 nodes: the root and two operands.
2043 // It is therefore trivial to get the APO. We only need to check the
2044 // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
2045 // RHS operand. The LHS operand of both add and sub is never attached
2046 // to an inversese operation in the linearized form, therefore its APO
2047 // is false. The RHS is true only if VL[Lane] is an inverse operation.
2048
2049 // Since operand reordering is performed on groups of commutative
2050 // operations or alternating sequences (e.g., +, -), we can safely
2051 // tell the inverse operations by checking commutativity.
2052 bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
2053 bool APO = (OpIdx == 0) ? false : IsInverseOperation;
2054 OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
2055 APO, false};
2056 }
2057 }
2058 }
2059
2060 /// \returns the number of operands.
2061 unsigned getNumOperands() const { return OpsVec.size(); }
2062
2063 /// \returns the number of lanes.
2064 unsigned getNumLanes() const { return OpsVec[0].size(); }
2065
2066 /// \returns the operand value at \p OpIdx and \p Lane.
2067 Value *getValue(unsigned OpIdx, unsigned Lane) const {
2068 return getData(OpIdx, Lane).V;
2069 }
2070
2071 /// \returns true if the data structure is empty.
2072 bool empty() const { return OpsVec.empty(); }
2073
2074 /// Clears the data.
2075 void clear() { OpsVec.clear(); }
2076
2077 /// \Returns true if there are enough operands identical to \p Op to fill
2078 /// the whole vector.
2079 /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
2080 bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
2081 bool OpAPO = getData(OpIdx, Lane).APO;
2082 for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
2083 if (Ln == Lane)
2084 continue;
2085 // This is set to true if we found a candidate for broadcast at Lane.
2086 bool FoundCandidate = false;
2087 for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
2088 OperandData &Data = getData(OpI, Ln);
2089 if (Data.APO != OpAPO || Data.IsUsed)
2090 continue;
2091 if (Data.V == Op) {
2092 FoundCandidate = true;
2093 Data.IsUsed = true;
2094 break;
2095 }
2096 }
2097 if (!FoundCandidate)
2098 return false;
2099 }
2100 return true;
2101 }
2102
2103 public:
2104 /// Initialize with all the operands of the instruction vector \p RootVL.
2105 VLOperands(ArrayRef<Value *> RootVL, const TargetLibraryInfo &TLI,
2106 const DataLayout &DL, ScalarEvolution &SE, const BoUpSLP &R)
2107 : TLI(TLI), DL(DL), SE(SE), R(R) {
2108 // Append all the operands of RootVL.
2109 appendOperandsOfVL(RootVL);
2110 }
2111
2112 /// \Returns a value vector with the operands across all lanes for the
2113 /// opearnd at \p OpIdx.
2114 ValueList getVL(unsigned OpIdx) const {
2115 ValueList OpVL(OpsVec[OpIdx].size());
2116 assert(OpsVec[OpIdx].size() == getNumLanes() &&(static_cast <bool> (OpsVec[OpIdx].size() == getNumLanes
() && "Expected same num of lanes across all operands"
) ? void (0) : __assert_fail ("OpsVec[OpIdx].size() == getNumLanes() && \"Expected same num of lanes across all operands\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2117, __extension__
__PRETTY_FUNCTION__))
2117 "Expected same num of lanes across all operands")(static_cast <bool> (OpsVec[OpIdx].size() == getNumLanes
() && "Expected same num of lanes across all operands"
) ? void (0) : __assert_fail ("OpsVec[OpIdx].size() == getNumLanes() && \"Expected same num of lanes across all operands\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2117, __extension__
__PRETTY_FUNCTION__))
;
2118 for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
2119 OpVL[Lane] = OpsVec[OpIdx][Lane].V;
2120 return OpVL;
2121 }
2122
2123 // Performs operand reordering for 2 or more operands.
2124 // The original operands are in OrigOps[OpIdx][Lane].
2125 // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
2126 void reorder() {
2127 unsigned NumOperands = getNumOperands();
2128 unsigned NumLanes = getNumLanes();
2129 // Each operand has its own mode. We are using this mode to help us select
2130 // the instructions for each lane, so that they match best with the ones
2131 // we have selected so far.
2132 SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
2133
2134 // This is a greedy single-pass algorithm. We are going over each lane
2135 // once and deciding on the best order right away with no back-tracking.
2136 // However, in order to increase its effectiveness, we start with the lane
2137 // that has operands that can move the least. For example, given the
2138 // following lanes:
2139 // Lane 0 : A[0] = B[0] + C[0] // Visited 3rd
2140 // Lane 1 : A[1] = C[1] - B[1] // Visited 1st
2141 // Lane 2 : A[2] = B[2] + C[2] // Visited 2nd
2142 // Lane 3 : A[3] = C[3] - B[3] // Visited 4th
2143 // we will start at Lane 1, since the operands of the subtraction cannot
2144 // be reordered. Then we will visit the rest of the lanes in a circular
2145 // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
2146
2147 // Find the first lane that we will start our search from.
2148 unsigned FirstLane = getBestLaneToStartReordering();
2149
2150 // Initialize the modes.
2151 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
2152 Value *OpLane0 = getValue(OpIdx, FirstLane);
2153 // Keep track if we have instructions with all the same opcode on one
2154 // side.
2155 if (isa<LoadInst>(OpLane0))
2156 ReorderingModes[OpIdx] = ReorderingMode::Load;
2157 else if (isa<Instruction>(OpLane0)) {
2158 // Check if OpLane0 should be broadcast.
2159 if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
2160 ReorderingModes[OpIdx] = ReorderingMode::Splat;
2161 else
2162 ReorderingModes[OpIdx] = ReorderingMode::Opcode;
2163 }
2164 else if (isa<Constant>(OpLane0))
2165 ReorderingModes[OpIdx] = ReorderingMode::Constant;
2166 else if (isa<Argument>(OpLane0))
2167 // Our best hope is a Splat. It may save some cost in some cases.
2168 ReorderingModes[OpIdx] = ReorderingMode::Splat;
2169 else
2170 // NOTE: This should be unreachable.
2171 ReorderingModes[OpIdx] = ReorderingMode::Failed;
2172 }
2173
2174 // Check that we don't have same operands. No need to reorder if operands
2175 // are just perfect diamond or shuffled diamond match. Do not do it only
2176 // for possible broadcasts or non-power of 2 number of scalars (just for
2177 // now).
2178 auto &&SkipReordering = [this]() {
2179 SmallPtrSet<Value *, 4> UniqueValues;
2180 ArrayRef<OperandData> Op0 = OpsVec.front();
2181 for (const OperandData &Data : Op0)
2182 UniqueValues.insert(Data.V);
2183 for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
2184 if (any_of(Op, [&UniqueValues](const OperandData &Data) {
2185 return !UniqueValues.contains(Data.V);
2186 }))
2187 return false;
2188 }
2189 // TODO: Check if we can remove a check for non-power-2 number of
2190 // scalars after full support of non-power-2 vectorization.
2191 return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
2192 };
2193
2194 // If the initial strategy fails for any of the operand indexes, then we
2195 // perform reordering again in a second pass. This helps avoid assigning
2196 // high priority to the failed strategy, and should improve reordering for
2197 // the non-failed operand indexes.
2198 for (int Pass = 0; Pass != 2; ++Pass) {
2199 // Check if no need to reorder operands since they're are perfect or
2200 // shuffled diamond match.
2201 // Need to to do it to avoid extra external use cost counting for
2202 // shuffled matches, which may cause regressions.
2203 if (SkipReordering())
2204 break;
2205 // Skip the second pass if the first pass did not fail.
2206 bool StrategyFailed = false;
2207 // Mark all operand data as free to use.
2208 clearUsed();
2209 // We keep the original operand order for the FirstLane, so reorder the
2210 // rest of the lanes. We are visiting the nodes in a circular fashion,
2211 // using FirstLane as the center point and increasing the radius
2212 // distance.
2213 SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
2214 for (unsigned I = 0; I < NumOperands; ++I)
2215 MainAltOps[I].push_back(getData(I, FirstLane).V);
2216
2217 for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
2218 // Visit the lane on the right and then the lane on the left.
2219 for (int Direction : {+1, -1}) {
2220 int Lane = FirstLane + Direction * Distance;
2221 if (Lane < 0 || Lane >= (int)NumLanes)
2222 continue;
2223 int LastLane = Lane - Direction;
2224 assert(LastLane >= 0 && LastLane < (int)NumLanes &&(static_cast <bool> (LastLane >= 0 && LastLane
< (int)NumLanes && "Out of bounds") ? void (0) : __assert_fail
("LastLane >= 0 && LastLane < (int)NumLanes && \"Out of bounds\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2225, __extension__
__PRETTY_FUNCTION__))
2225 "Out of bounds")(static_cast <bool> (LastLane >= 0 && LastLane
< (int)NumLanes && "Out of bounds") ? void (0) : __assert_fail
("LastLane >= 0 && LastLane < (int)NumLanes && \"Out of bounds\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2225, __extension__
__PRETTY_FUNCTION__))
;
2226 // Look for a good match for each operand.
2227 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
2228 // Search for the operand that matches SortedOps[OpIdx][Lane-1].
2229 std::optional<unsigned> BestIdx = getBestOperand(
2230 OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
2231 // By not selecting a value, we allow the operands that follow to
2232 // select a better matching value. We will get a non-null value in
2233 // the next run of getBestOperand().
2234 if (BestIdx) {
2235 // Swap the current operand with the one returned by
2236 // getBestOperand().
2237 swap(OpIdx, *BestIdx, Lane);
2238 } else {
2239 // We failed to find a best operand, set mode to 'Failed'.
2240 ReorderingModes[OpIdx] = ReorderingMode::Failed;
2241 // Enable the second pass.
2242 StrategyFailed = true;
2243 }
2244 // Try to get the alternate opcode and follow it during analysis.
2245 if (MainAltOps[OpIdx].size() != 2) {
2246 OperandData &AltOp = getData(OpIdx, Lane);
2247 InstructionsState OpS =
2248 getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V}, TLI);
2249 if (OpS.getOpcode() && OpS.isAltShuffle())
2250 MainAltOps[OpIdx].push_back(AltOp.V);
2251 }
2252 }
2253 }
2254 }
2255 // Skip second pass if the strategy did not fail.
2256 if (!StrategyFailed)
2257 break;
2258 }
2259 }
2260
2261#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2262 LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) static StringRef getModeStr(ReorderingMode RMode) {
2263 switch (RMode) {
2264 case ReorderingMode::Load:
2265 return "Load";
2266 case ReorderingMode::Opcode:
2267 return "Opcode";
2268 case ReorderingMode::Constant:
2269 return "Constant";
2270 case ReorderingMode::Splat:
2271 return "Splat";
2272 case ReorderingMode::Failed:
2273 return "Failed";
2274 }
2275 llvm_unreachable("Unimplemented Reordering Type")::llvm::llvm_unreachable_internal("Unimplemented Reordering Type"
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2275)
;
2276 }
2277
2278 LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) static raw_ostream &printMode(ReorderingMode RMode,
2279 raw_ostream &OS) {
2280 return OS << getModeStr(RMode);
2281 }
2282
2283 /// Debug print.
2284 LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) static void dumpMode(ReorderingMode RMode) {
2285 printMode(RMode, dbgs());
2286 }
2287
2288 friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
2289 return printMode(RMode, OS);
2290 }
2291
2292 LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) raw_ostream &print(raw_ostream &OS) const {
2293 const unsigned Indent = 2;
2294 unsigned Cnt = 0;
2295 for (const OperandDataVec &OpDataVec : OpsVec) {
2296 OS << "Operand " << Cnt++ << "\n";
2297 for (const OperandData &OpData : OpDataVec) {
2298 OS.indent(Indent) << "{";
2299 if (Value *V = OpData.V)
2300 OS << *V;
2301 else
2302 OS << "null";
2303 OS << ", APO:" << OpData.APO << "}\n";
2304 }
2305 OS << "\n";
2306 }
2307 return OS;
2308 }
2309
2310 /// Debug print.
2311 LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void dump() const { print(dbgs()); }
2312#endif
2313 };
2314
2315 /// Evaluate each pair in \p Candidates and return index into \p Candidates
2316 /// for a pair which have highest score deemed to have best chance to form
2317 /// root of profitable tree to vectorize. Return std::nullopt if no candidate
2318 /// scored above the LookAheadHeuristics::ScoreFail. \param Limit Lower limit
2319 /// of the cost, considered to be good enough score.
2320 std::optional<int>
2321 findBestRootPair(ArrayRef<std::pair<Value *, Value *>> Candidates,
2322 int Limit = LookAheadHeuristics::ScoreFail) {
2323 LookAheadHeuristics LookAhead(*TLI, *DL, *SE, *this, /*NumLanes=*/2,
2324 RootLookAheadMaxDepth);
2325 int BestScore = Limit;
2326 std::optional<int> Index;
2327 for (int I : seq<int>(0, Candidates.size())) {
2328 int Score = LookAhead.getScoreAtLevelRec(Candidates[I].first,
2329 Candidates[I].second,
2330 /*U1=*/nullptr, /*U2=*/nullptr,
2331 /*Level=*/1, std::nullopt);
2332 if (Score > BestScore) {
2333 BestScore = Score;
2334 Index = I;
2335 }
2336 }
2337 return Index;
2338 }
2339
2340 /// Checks if the instruction is marked for deletion.
2341 bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
2342
2343 /// Removes an instruction from its block and eventually deletes it.
2344 /// It's like Instruction::eraseFromParent() except that the actual deletion
2345 /// is delayed until BoUpSLP is destructed.
2346 void eraseInstruction(Instruction *I) {
2347 DeletedInstructions.insert(I);
2348 }
2349
2350 /// Checks if the instruction was already analyzed for being possible
2351 /// reduction root.
2352 bool isAnalyzedReductionRoot(Instruction *I) const {
2353 return AnalyzedReductionsRoots.count(I);
2354 }
2355 /// Register given instruction as already analyzed for being possible
2356 /// reduction root.
2357 void analyzedReductionRoot(Instruction *I) {
2358 AnalyzedReductionsRoots.insert(I);
2359 }
2360 /// Checks if the provided list of reduced values was checked already for
2361 /// vectorization.
2362 bool areAnalyzedReductionVals(ArrayRef<Value *> VL) const {
2363 return AnalyzedReductionVals.contains(hash_value(VL));
2364 }
2365 /// Adds the list of reduced values to list of already checked values for the
2366 /// vectorization.
2367 void analyzedReductionVals(ArrayRef<Value *> VL) {
2368 AnalyzedReductionVals.insert(hash_value(VL));
2369 }
2370 /// Clear the list of the analyzed reduction root instructions.
2371 void clearReductionData() {
2372 AnalyzedReductionsRoots.clear();
2373 AnalyzedReductionVals.clear();
2374 }
2375 /// Checks if the given value is gathered in one of the nodes.
2376 bool isAnyGathered(const SmallDenseSet<Value *> &Vals) const {
2377 return any_of(MustGather, [&](Value *V) { return Vals.contains(V); });
2378 }
2379
2380 /// Check if the value is vectorized in the tree.
2381 bool isVectorized(Value *V) const { return getTreeEntry(V); }
2382
2383 ~BoUpSLP();
2384
2385private:
2386 /// Check if the operands on the edges \p Edges of the \p UserTE allows
2387 /// reordering (i.e. the operands can be reordered because they have only one
2388 /// user and reordarable).
2389 /// \param ReorderableGathers List of all gather nodes that require reordering
2390 /// (e.g., gather of extractlements or partially vectorizable loads).
2391 /// \param GatherOps List of gather operand nodes for \p UserTE that require
2392 /// reordering, subset of \p NonVectorized.
2393 bool
2394 canReorderOperands(TreeEntry *UserTE,
2395 SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
2396 ArrayRef<TreeEntry *> ReorderableGathers,
2397 SmallVectorImpl<TreeEntry *> &GatherOps);
2398
2399 /// Checks if the given \p TE is a gather node with clustered reused scalars
2400 /// and reorders it per given \p Mask.
2401 void reorderNodeWithReuses(TreeEntry &TE, ArrayRef<int> Mask) const;
2402
2403 /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2404 /// if any. If it is not vectorized (gather node), returns nullptr.
2405 TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
2406 ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
2407 TreeEntry *TE = nullptr;
2408 const auto *It = find_if(VL, [this, &TE](Value *V) {
2409 TE = getTreeEntry(V);
2410 return TE;
2411 });
2412 if (It != VL.end() && TE->isSame(VL))
2413 return TE;
2414 return nullptr;
2415 }
2416
2417 /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2418 /// if any. If it is not vectorized (gather node), returns nullptr.
2419 const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
2420 unsigned OpIdx) const {
2421 return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
2422 const_cast<TreeEntry *>(UserTE), OpIdx);
2423 }
2424
2425 /// Checks if all users of \p I are the part of the vectorization tree.
2426 bool areAllUsersVectorized(Instruction *I,
2427 ArrayRef<Value *> VectorizedVals) const;
2428
2429 /// Return information about the vector formed for the specified index
2430 /// of a vector of (the same) instruction.
2431 TargetTransformInfo::OperandValueInfo getOperandInfo(ArrayRef<Value *> VL,
2432 unsigned OpIdx);
2433
2434 /// \returns the cost of the vectorizable entry.
2435 InstructionCost getEntryCost(const TreeEntry *E,
2436 ArrayRef<Value *> VectorizedVals,
2437 SmallPtrSetImpl<Value *> &CheckedExtracts);
2438
2439 /// This is the recursive part of buildTree.
2440 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2441 const EdgeInfo &EI);
2442
2443 /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2444 /// be vectorized to use the original vector (or aggregate "bitcast" to a
2445 /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2446 /// returns false, setting \p CurrentOrder to either an empty vector or a
2447 /// non-identity permutation that allows to reuse extract instructions.
2448 bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2449 SmallVectorImpl<unsigned> &CurrentOrder) const;
2450
2451 /// Vectorize a single entry in the tree.
2452 Value *vectorizeTree(TreeEntry *E);
2453
2454 /// Vectorize a single entry in the tree, the \p Idx-th operand of the entry
2455 /// \p E.
2456 Value *vectorizeOperand(TreeEntry *E, unsigned NodeIdx);
2457
2458 /// Create a new vector from a list of scalar values. Produces a sequence
2459 /// which exploits values reused across lanes, and arranges the inserts
2460 /// for ease of later optimization.
2461 template <typename BVTy, typename ResTy, typename... Args>
2462 ResTy processBuildVector(const TreeEntry *E, Args &...Params);
2463
2464 /// Create a new vector from a list of scalar values. Produces a sequence
2465 /// which exploits values reused across lanes, and arranges the inserts
2466 /// for ease of later optimization.
2467 Value *createBuildVector(const TreeEntry *E);
2468
2469 /// Returns the instruction in the bundle, which can be used as a base point
2470 /// for scheduling. Usually it is the last instruction in the bundle, except
2471 /// for the case when all operands are external (in this case, it is the first
2472 /// instruction in the list).
2473 Instruction &getLastInstructionInBundle(const TreeEntry *E);
2474
2475 /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2476 /// tree entries.
2477 /// \param TE Tree entry checked for permutation.
2478 /// \param VL List of scalars (a subset of the TE scalar), checked for
2479 /// permutations.
2480 /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2481 /// previous tree entries. \p Mask is filled with the shuffle mask.
2482 std::optional<TargetTransformInfo::ShuffleKind>
2483 isGatherShuffledEntry(const TreeEntry *TE, ArrayRef<Value *> VL,
2484 SmallVectorImpl<int> &Mask,
2485 SmallVectorImpl<const TreeEntry *> &Entries);
2486
2487 /// \returns the scalarization cost for this list of values. Assuming that
2488 /// this subtree gets vectorized, we may need to extract the values from the
2489 /// roots. This method calculates the cost of extracting the values.
2490 /// \param ForPoisonSrc true if initial vector is poison, false otherwise.
2491 InstructionCost getGatherCost(ArrayRef<Value *> VL, bool ForPoisonSrc) const;
2492
2493 /// Set the Builder insert point to one after the last instruction in
2494 /// the bundle
2495 void setInsertPointAfterBundle(const TreeEntry *E);
2496
2497 /// \returns a vector from a collection of scalars in \p VL. if \p Root is not
2498 /// specified, the starting vector value is poison.
2499 Value *gather(ArrayRef<Value *> VL, Value *Root);
2500
2501 /// \returns whether the VectorizableTree is fully vectorizable and will
2502 /// be beneficial even the tree height is tiny.
2503 bool isFullyVectorizableTinyTree(bool ForReduction) const;
2504
2505 /// Reorder commutative or alt operands to get better probability of
2506 /// generating vectorized code.
2507 static void reorderInputsAccordingToOpcode(
2508 ArrayRef<Value *> VL, SmallVectorImpl<Value *> &Left,
2509 SmallVectorImpl<Value *> &Right, const TargetLibraryInfo &TLI,
2510 const DataLayout &DL, ScalarEvolution &SE, const BoUpSLP &R);
2511
2512 /// Helper for `findExternalStoreUsersReorderIndices()`. It iterates over the
2513 /// users of \p TE and collects the stores. It returns the map from the store
2514 /// pointers to the collected stores.
2515 DenseMap<Value *, SmallVector<StoreInst *, 4>>
2516 collectUserStores(const BoUpSLP::TreeEntry *TE) const;
2517
2518 /// Helper for `findExternalStoreUsersReorderIndices()`. It checks if the
2519 /// stores in \p StoresVec can form a vector instruction. If so it returns true
2520 /// and populates \p ReorderIndices with the shuffle indices of the the stores
2521 /// when compared to the sorted vector.
2522 bool canFormVector(const SmallVector<StoreInst *, 4> &StoresVec,
2523 OrdersType &ReorderIndices) const;
2524
2525 /// Iterates through the users of \p TE, looking for scalar stores that can be
2526 /// potentially vectorized in a future SLP-tree. If found, it keeps track of
2527 /// their order and builds an order index vector for each store bundle. It
2528 /// returns all these order vectors found.
2529 /// We run this after the tree has formed, otherwise we may come across user
2530 /// instructions that are not yet in the tree.
2531 SmallVector<OrdersType, 1>
2532 findExternalStoreUsersReorderIndices(TreeEntry *TE) const;
2533
2534 struct TreeEntry {
2535 using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2536 TreeEntry(VecTreeTy &Container) : Container(Container) {}
2537
2538 /// \returns true if the scalars in VL are equal to this entry.
2539 bool isSame(ArrayRef<Value *> VL) const {
2540 auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2541 if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2542 return std::equal(VL.begin(), VL.end(), Scalars.begin());
2543 return VL.size() == Mask.size() &&
2544 std::equal(VL.begin(), VL.end(), Mask.begin(),
2545 [Scalars](Value *V, int Idx) {
2546 return (isa<UndefValue>(V) &&
2547 Idx == PoisonMaskElem) ||
2548 (Idx != PoisonMaskElem && V == Scalars[Idx]);
2549 });
2550 };
2551 if (!ReorderIndices.empty()) {
2552 // TODO: implement matching if the nodes are just reordered, still can
2553 // treat the vector as the same if the list of scalars matches VL
2554 // directly, without reordering.
2555 SmallVector<int> Mask;
2556 inversePermutation(ReorderIndices, Mask);
2557 if (VL.size() == Scalars.size())
2558 return IsSame(Scalars, Mask);
2559 if (VL.size() == ReuseShuffleIndices.size()) {
2560 ::addMask(Mask, ReuseShuffleIndices);
2561 return IsSame(Scalars, Mask);
2562 }
2563 return false;
2564 }
2565 return IsSame(Scalars, ReuseShuffleIndices);
2566 }
2567
2568 bool isOperandGatherNode(const EdgeInfo &UserEI) const {
2569 return State == TreeEntry::NeedToGather &&
2570 UserTreeIndices.front().EdgeIdx == UserEI.EdgeIdx &&
2571 UserTreeIndices.front().UserTE == UserEI.UserTE;
2572 }
2573
2574 /// \returns true if current entry has same operands as \p TE.
2575 bool hasEqualOperands(const TreeEntry &TE) const {
2576 if (TE.getNumOperands() != getNumOperands())
2577 return false;
2578 SmallBitVector Used(getNumOperands());
2579 for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2580 unsigned PrevCount = Used.count();
2581 for (unsigned K = 0; K < E; ++K) {
2582 if (Used.test(K))
2583 continue;
2584 if (getOperand(K) == TE.getOperand(I)) {
2585 Used.set(K);
2586 break;
2587 }
2588 }
2589 // Check if we actually found the matching operand.
2590 if (PrevCount == Used.count())
2591 return false;
2592 }
2593 return true;
2594 }
2595
2596 /// \return Final vectorization factor for the node. Defined by the total
2597 /// number of vectorized scalars, including those, used several times in the
2598 /// entry and counted in the \a ReuseShuffleIndices, if any.
2599 unsigned getVectorFactor() const {
2600 if (!ReuseShuffleIndices.empty())
2601 return ReuseShuffleIndices.size();
2602 return Scalars.size();
2603 };
2604
2605 /// A vector of scalars.
2606 ValueList Scalars;
2607
2608 /// The Scalars are vectorized into this value. It is initialized to Null.
2609 WeakTrackingVH VectorizedValue = nullptr;
2610
2611 /// Do we need to gather this sequence or vectorize it
2612 /// (either with vector instruction or with scatter/gather
2613 /// intrinsics for store/load)?
2614 enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2615 EntryState State;
2616
2617 /// Does this sequence require some shuffling?
2618 SmallVector<int, 4> ReuseShuffleIndices;
2619
2620 /// Does this entry require reordering?
2621 SmallVector<unsigned, 4> ReorderIndices;
2622
2623 /// Points back to the VectorizableTree.
2624 ///
2625 /// Only used for Graphviz right now. Unfortunately GraphTrait::NodeRef has
2626 /// to be a pointer and needs to be able to initialize the child iterator.
2627 /// Thus we need a reference back to the container to translate the indices
2628 /// to entries.
2629 VecTreeTy &Container;
2630
2631 /// The TreeEntry index containing the user of this entry. We can actually
2632 /// have multiple users so the data structure is not truly a tree.
2633 SmallVector<EdgeInfo, 1> UserTreeIndices;
2634
2635 /// The index of this treeEntry in VectorizableTree.
2636 int Idx = -1;
2637
2638 private:
2639 /// The operands of each instruction in each lane Operands[op_index][lane].
2640 /// Note: This helps avoid the replication of the code that performs the
2641 /// reordering of operands during buildTree_rec() and vectorizeTree().
2642 SmallVector<ValueList, 2> Operands;
2643
2644 /// The main/alternate instruction.
2645 Instruction *MainOp = nullptr;
2646 Instruction *AltOp = nullptr;
2647
2648 public:
2649 /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2650 void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2651 if (Operands.size() < OpIdx + 1)
2652 Operands.resize(OpIdx + 1);
2653 assert(Operands[OpIdx].empty() && "Already resized?")(static_cast <bool> (Operands[OpIdx].empty() &&
"Already resized?") ? void (0) : __assert_fail ("Operands[OpIdx].empty() && \"Already resized?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2653, __extension__
__PRETTY_FUNCTION__))
;
2654 assert(OpVL.size() <= Scalars.size() &&(static_cast <bool> (OpVL.size() <= Scalars.size() &&
"Number of operands is greater than the number of scalars.")
? void (0) : __assert_fail ("OpVL.size() <= Scalars.size() && \"Number of operands is greater than the number of scalars.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2655, __extension__
__PRETTY_FUNCTION__))
2655 "Number of operands is greater than the number of scalars.")(static_cast <bool> (OpVL.size() <= Scalars.size() &&
"Number of operands is greater than the number of scalars.")
? void (0) : __assert_fail ("OpVL.size() <= Scalars.size() && \"Number of operands is greater than the number of scalars.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2655, __extension__
__PRETTY_FUNCTION__))
;
2656 Operands[OpIdx].resize(OpVL.size());
2657 copy(OpVL, Operands[OpIdx].begin());
2658 }
2659
2660 /// Set the operands of this bundle in their original order.
2661 void setOperandsInOrder() {
2662 assert(Operands.empty() && "Already initialized?")(static_cast <bool> (Operands.empty() && "Already initialized?"
) ? void (0) : __assert_fail ("Operands.empty() && \"Already initialized?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2662, __extension__
__PRETTY_FUNCTION__))
;
2663 auto *I0 = cast<Instruction>(Scalars[0]);
2664 Operands.resize(I0->getNumOperands());
2665 unsigned NumLanes = Scalars.size();
2666 for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2667 OpIdx != NumOperands; ++OpIdx) {
2668 Operands[OpIdx].resize(NumLanes);
2669 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2670 auto *I = cast<Instruction>(Scalars[Lane]);
2671 assert(I->getNumOperands() == NumOperands &&(static_cast <bool> (I->getNumOperands() == NumOperands
&& "Expected same number of operands") ? void (0) : __assert_fail
("I->getNumOperands() == NumOperands && \"Expected same number of operands\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2672, __extension__
__PRETTY_FUNCTION__))
2672 "Expected same number of operands")(static_cast <bool> (I->getNumOperands() == NumOperands
&& "Expected same number of operands") ? void (0) : __assert_fail
("I->getNumOperands() == NumOperands && \"Expected same number of operands\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2672, __extension__
__PRETTY_FUNCTION__))
;
2673 Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2674 }
2675 }
2676 }
2677
2678 /// Reorders operands of the node to the given mask \p Mask.
2679 void reorderOperands(ArrayRef<int> Mask) {
2680 for (ValueList &Operand : Operands)
2681 reorderScalars(Operand, Mask);
2682 }
2683
2684 /// \returns the \p OpIdx operand of this TreeEntry.
2685 ValueList &getOperand(unsigned OpIdx) {
2686 assert(OpIdx < Operands.size() && "Off bounds")(static_cast <bool> (OpIdx < Operands.size() &&
"Off bounds") ? void (0) : __assert_fail ("OpIdx < Operands.size() && \"Off bounds\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2686, __extension__
__PRETTY_FUNCTION__))
;
2687 return Operands[OpIdx];
2688 }
2689
2690 /// \returns the \p OpIdx operand of this TreeEntry.
2691 ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2692 assert(OpIdx < Operands.size() && "Off bounds")(static_cast <bool> (OpIdx < Operands.size() &&
"Off bounds") ? void (0) : __assert_fail ("OpIdx < Operands.size() && \"Off bounds\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2692, __extension__
__PRETTY_FUNCTION__))
;
2693 return Operands[OpIdx];
2694 }
2695
2696 /// \returns the number of operands.
2697 unsigned getNumOperands() const { return Operands.size(); }
2698
2699 /// \return the single \p OpIdx operand.
2700 Value *getSingleOperand(unsigned OpIdx) const {
2701 assert(OpIdx < Operands.size() && "Off bounds")(static_cast <bool> (OpIdx < Operands.size() &&
"Off bounds") ? void (0) : __assert_fail ("OpIdx < Operands.size() && \"Off bounds\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2701, __extension__
__PRETTY_FUNCTION__))
;
2702 assert(!Operands[OpIdx].empty() && "No operand available")(static_cast <bool> (!Operands[OpIdx].empty() &&
"No operand available") ? void (0) : __assert_fail ("!Operands[OpIdx].empty() && \"No operand available\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2702, __extension__
__PRETTY_FUNCTION__))
;
2703 return Operands[OpIdx][0];
2704 }
2705
2706 /// Some of the instructions in the list have alternate opcodes.
2707 bool isAltShuffle() const { return MainOp != AltOp; }
2708
2709 bool isOpcodeOrAlt(Instruction *I) const {
2710 unsigned CheckedOpcode = I->getOpcode();
2711 return (getOpcode() == CheckedOpcode ||
2712 getAltOpcode() == CheckedOpcode);
2713 }
2714
2715 /// Chooses the correct key for scheduling data. If \p Op has the same (or
2716 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2717 /// \p OpValue.
2718 Value *isOneOf(Value *Op) const {
2719 auto *I = dyn_cast<Instruction>(Op);
2720 if (I && isOpcodeOrAlt(I))
2721 return Op;
2722 return MainOp;
2723 }
2724
2725 void setOperations(const InstructionsState &S) {
2726 MainOp = S.MainOp;
2727 AltOp = S.AltOp;
2728 }
2729
2730 Instruction *getMainOp() const {
2731 return MainOp;
2732 }
2733
2734 Instruction *getAltOp() const {
2735 return AltOp;
2736 }
2737
2738 /// The main/alternate opcodes for the list of instructions.
2739 unsigned getOpcode() const {
2740 return MainOp ? MainOp->getOpcode() : 0;
2741 }
2742
2743 unsigned getAltOpcode() const {
2744 return AltOp ? AltOp->getOpcode() : 0;
2745 }
2746
2747 /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2748 /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2749 int findLaneForValue(Value *V) const {
2750 unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2751 assert(FoundLane < Scalars.size() && "Couldn't find extract lane")(static_cast <bool> (FoundLane < Scalars.size() &&
"Couldn't find extract lane") ? void (0) : __assert_fail ("FoundLane < Scalars.size() && \"Couldn't find extract lane\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2751, __extension__
__PRETTY_FUNCTION__))
;
2752 if (!ReorderIndices.empty())
2753 FoundLane = ReorderIndices[FoundLane];
2754 assert(FoundLane < Scalars.size() && "Couldn't find extract lane")(static_cast <bool> (FoundLane < Scalars.size() &&
"Couldn't find extract lane") ? void (0) : __assert_fail ("FoundLane < Scalars.size() && \"Couldn't find extract lane\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2754, __extension__
__PRETTY_FUNCTION__))
;
2755 if (!ReuseShuffleIndices.empty()) {
2756 FoundLane = std::distance(ReuseShuffleIndices.begin(),
2757 find(ReuseShuffleIndices, FoundLane));
2758 }
2759 return FoundLane;
2760 }
2761
2762#ifndef NDEBUG
2763 /// Debug printer.
2764 LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void dump() const {
2765 dbgs() << Idx << ".\n";
2766 for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2767 dbgs() << "Operand " << OpI << ":\n";
2768 for (const Value *V : Operands[OpI])
2769 dbgs().indent(2) << *V << "\n";
2770 }
2771 dbgs() << "Scalars: \n";
2772 for (Value *V : Scalars)
2773 dbgs().indent(2) << *V << "\n";
2774 dbgs() << "State: ";
2775 switch (State) {
2776 case Vectorize:
2777 dbgs() << "Vectorize\n";
2778 break;
2779 case ScatterVectorize:
2780 dbgs() << "ScatterVectorize\n";
2781 break;
2782 case NeedToGather:
2783 dbgs() << "NeedToGather\n";
2784 break;
2785 }
2786 dbgs() << "MainOp: ";
2787 if (MainOp)
2788 dbgs() << *MainOp << "\n";
2789 else
2790 dbgs() << "NULL\n";
2791 dbgs() << "AltOp: ";
2792 if (AltOp)
2793 dbgs() << *AltOp << "\n";
2794 else
2795 dbgs() << "NULL\n";
2796 dbgs() << "VectorizedValue: ";
2797 if (VectorizedValue)
2798 dbgs() << *VectorizedValue << "\n";
2799 else
2800 dbgs() << "NULL\n";
2801 dbgs() << "ReuseShuffleIndices: ";
2802 if (ReuseShuffleIndices.empty())
2803 dbgs() << "Empty";
2804 else
2805 for (int ReuseIdx : ReuseShuffleIndices)
2806 dbgs() << ReuseIdx << ", ";
2807 dbgs() << "\n";
2808 dbgs() << "ReorderIndices: ";
2809 for (unsigned ReorderIdx : ReorderIndices)
2810 dbgs() << ReorderIdx << ", ";
2811 dbgs() << "\n";
2812 dbgs() << "UserTreeIndices: ";
2813 for (const auto &EInfo : UserTreeIndices)
2814 dbgs() << EInfo << ", ";
2815 dbgs() << "\n";
2816 }
2817#endif
2818 };
2819
2820#ifndef NDEBUG
2821 void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2822 InstructionCost VecCost, InstructionCost ScalarCost,
2823 StringRef Banner) const {
2824 dbgs() << "SLP: " << Banner << ":\n";
2825 E->dump();
2826 dbgs() << "SLP: Costs:\n";
2827 dbgs() << "SLP: ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2828 dbgs() << "SLP: VectorCost = " << VecCost << "\n";
2829 dbgs() << "SLP: ScalarCost = " << ScalarCost << "\n";
2830 dbgs() << "SLP: ReuseShuffleCost + VecCost - ScalarCost = "
2831 << ReuseShuffleCost + VecCost - ScalarCost << "\n";
2832 }
2833#endif
2834
2835 /// Create a new VectorizableTree entry.
2836 TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2837 std::optional<ScheduleData *> Bundle,
2838 const InstructionsState &S,
2839 const EdgeInfo &UserTreeIdx,
2840 ArrayRef<int> ReuseShuffleIndices = std::nullopt,
2841 ArrayRef<unsigned> ReorderIndices = std::nullopt) {
2842 TreeEntry::EntryState EntryState =
2843 Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2844 return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2845 ReuseShuffleIndices, ReorderIndices);
2846 }
2847
2848 TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2849 TreeEntry::EntryState EntryState,
2850 std::optional<ScheduleData *> Bundle,
2851 const InstructionsState &S,
2852 const EdgeInfo &UserTreeIdx,
2853 ArrayRef<int> ReuseShuffleIndices = std::nullopt,
2854 ArrayRef<unsigned> ReorderIndices = std::nullopt) {
2855 assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||(static_cast <bool> (((!Bundle && EntryState ==
TreeEntry::NeedToGather) || (Bundle && EntryState !=
TreeEntry::NeedToGather)) && "Need to vectorize gather entry?"
) ? void (0) : __assert_fail ("((!Bundle && EntryState == TreeEntry::NeedToGather) || (Bundle && EntryState != TreeEntry::NeedToGather)) && \"Need to vectorize gather entry?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2857, __extension__
__PRETTY_FUNCTION__))
2856 (Bundle && EntryState != TreeEntry::NeedToGather)) &&(static_cast <bool> (((!Bundle && EntryState ==
TreeEntry::NeedToGather) || (Bundle && EntryState !=
TreeEntry::NeedToGather)) && "Need to vectorize gather entry?"
) ? void (0) : __assert_fail ("((!Bundle && EntryState == TreeEntry::NeedToGather) || (Bundle && EntryState != TreeEntry::NeedToGather)) && \"Need to vectorize gather entry?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2857, __extension__
__PRETTY_FUNCTION__))
2857 "Need to vectorize gather entry?")(static_cast <bool> (((!Bundle && EntryState ==
TreeEntry::NeedToGather) || (Bundle && EntryState !=
TreeEntry::NeedToGather)) && "Need to vectorize gather entry?"
) ? void (0) : __assert_fail ("((!Bundle && EntryState == TreeEntry::NeedToGather) || (Bundle && EntryState != TreeEntry::NeedToGather)) && \"Need to vectorize gather entry?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2857, __extension__
__PRETTY_FUNCTION__))
;
2858 VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2859 TreeEntry *Last = VectorizableTree.back().get();
2860 Last->Idx = VectorizableTree.size() - 1;
2861 Last->State = EntryState;
2862 Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2863 ReuseShuffleIndices.end());
2864 if (ReorderIndices.empty()) {
2865 Last->Scalars.assign(VL.begin(), VL.end());
2866 Last->setOperations(S);
2867 } else {
2868 // Reorder scalars and build final mask.
2869 Last->Scalars.assign(VL.size(), nullptr);
2870 transform(ReorderIndices, Last->Scalars.begin(),
2871 [VL](unsigned Idx) -> Value * {
2872 if (Idx >= VL.size())
2873 return UndefValue::get(VL.front()->getType());
2874 return VL[Idx];
2875 });
2876 InstructionsState S = getSameOpcode(Last->Scalars, *TLI);
2877 Last->setOperations(S);
2878 Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2879 }
2880 if (Last->State != TreeEntry::NeedToGather) {
2881 for (Value *V : VL) {
2882 assert(!getTreeEntry(V) && "Scalar already in tree!")(static_cast <bool> (!getTreeEntry(V) && "Scalar already in tree!"
) ? void (0) : __assert_fail ("!getTreeEntry(V) && \"Scalar already in tree!\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2882, __extension__
__PRETTY_FUNCTION__))
;
2883 ScalarToTreeEntry[V] = Last;
2884 }
2885 // Update the scheduler bundle to point to this TreeEntry.
2886 ScheduleData *BundleMember = *Bundle;
2887 assert((BundleMember || isa<PHINode>(S.MainOp) ||(static_cast <bool> ((BundleMember || isa<PHINode>
(S.MainOp) || isVectorLikeInstWithConstOps(S.MainOp) || doesNotNeedToSchedule
(VL)) && "Bundle and VL out of sync") ? void (0) : __assert_fail
("(BundleMember || isa<PHINode>(S.MainOp) || isVectorLikeInstWithConstOps(S.MainOp) || doesNotNeedToSchedule(VL)) && \"Bundle and VL out of sync\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2890, __extension__
__PRETTY_FUNCTION__))
2888 isVectorLikeInstWithConstOps(S.MainOp) ||(static_cast <bool> ((BundleMember || isa<PHINode>
(S.MainOp) || isVectorLikeInstWithConstOps(S.MainOp) || doesNotNeedToSchedule
(VL)) && "Bundle and VL out of sync") ? void (0) : __assert_fail
("(BundleMember || isa<PHINode>(S.MainOp) || isVectorLikeInstWithConstOps(S.MainOp) || doesNotNeedToSchedule(VL)) && \"Bundle and VL out of sync\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2890, __extension__
__PRETTY_FUNCTION__))
2889 doesNotNeedToSchedule(VL)) &&(static_cast <bool> ((BundleMember || isa<PHINode>
(S.MainOp) || isVectorLikeInstWithConstOps(S.MainOp) || doesNotNeedToSchedule
(VL)) && "Bundle and VL out of sync") ? void (0) : __assert_fail
("(BundleMember || isa<PHINode>(S.MainOp) || isVectorLikeInstWithConstOps(S.MainOp) || doesNotNeedToSchedule(VL)) && \"Bundle and VL out of sync\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2890, __extension__
__PRETTY_FUNCTION__))
2890 "Bundle and VL out of sync")(static_cast <bool> ((BundleMember || isa<PHINode>
(S.MainOp) || isVectorLikeInstWithConstOps(S.MainOp) || doesNotNeedToSchedule
(VL)) && "Bundle and VL out of sync") ? void (0) : __assert_fail
("(BundleMember || isa<PHINode>(S.MainOp) || isVectorLikeInstWithConstOps(S.MainOp) || doesNotNeedToSchedule(VL)) && \"Bundle and VL out of sync\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2890, __extension__
__PRETTY_FUNCTION__))
;
2891 if (BundleMember) {
2892 for (Value *V : VL) {
2893 if (doesNotNeedToBeScheduled(V))
2894 continue;
2895 assert(BundleMember && "Unexpected end of bundle.")(static_cast <bool> (BundleMember && "Unexpected end of bundle."
) ? void (0) : __assert_fail ("BundleMember && \"Unexpected end of bundle.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2895, __extension__
__PRETTY_FUNCTION__))
;
2896 BundleMember->TE = Last;
2897 BundleMember = BundleMember->NextInBundle;
2898 }
2899 }
2900 assert(!BundleMember && "Bundle and VL out of sync")(static_cast <bool> (!BundleMember && "Bundle and VL out of sync"
) ? void (0) : __assert_fail ("!BundleMember && \"Bundle and VL out of sync\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2900, __extension__
__PRETTY_FUNCTION__))
;
2901 } else {
2902 MustGather.insert(VL.begin(), VL.end());
2903 }
2904
2905 if (UserTreeIdx.UserTE)
2906 Last->UserTreeIndices.push_back(UserTreeIdx);
2907
2908 return Last;
2909 }
2910
2911 /// -- Vectorization State --
2912 /// Holds all of the tree entries.
2913 TreeEntry::VecTreeTy VectorizableTree;
2914
2915#ifndef NDEBUG
2916 /// Debug printer.
2917 LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void dumpVectorizableTree() const {
2918 for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2919 VectorizableTree[Id]->dump();
2920 dbgs() << "\n";
2921 }
2922 }
2923#endif
2924
2925 TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2926
2927 const TreeEntry *getTreeEntry(Value *V) const {
2928 return ScalarToTreeEntry.lookup(V);
2929 }
2930
2931 /// Maps a specific scalar to its tree entry.
2932 SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2933
2934 /// Maps a value to the proposed vectorizable size.
2935 SmallDenseMap<Value *, unsigned> InstrElementSize;
2936
2937 /// A list of scalars that we found that we need to keep as scalars.
2938 ValueSet MustGather;
2939
2940 /// A map between the vectorized entries and the last instructions in the
2941 /// bundles. The bundles are built in use order, not in the def order of the
2942 /// instructions. So, we cannot rely directly on the last instruction in the
2943 /// bundle being the last instruction in the program order during
2944 /// vectorization process since the basic blocks are affected, need to
2945 /// pre-gather them before.
2946 DenseMap<const TreeEntry *, Instruction *> EntryToLastInstruction;
2947
2948 /// List of gather nodes, depending on other gather/vector nodes, which should
2949 /// be emitted after the vector instruction emission process to correctly
2950 /// handle order of the vector instructions and shuffles.
2951 SetVector<const TreeEntry *> PostponedGathers;
2952
2953 using ValueToGatherNodesMap =
2954 DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>>;
2955 ValueToGatherNodesMap ValueToGatherNodes;
2956
2957 /// This POD struct describes one external user in the vectorized tree.
2958 struct ExternalUser {
2959 ExternalUser(Value *S, llvm::User *U, int L)
2960 : Scalar(S), User(U), Lane(L) {}
2961
2962 // Which scalar in our function.
2963 Value *Scalar;
2964
2965 // Which user that uses the scalar.
2966 llvm::User *User;
2967
2968 // Which lane does the scalar belong to.
2969 int Lane;
2970 };
2971 using UserList = SmallVector<ExternalUser, 16>;
2972
2973 /// Checks if two instructions may access the same memory.
2974 ///
2975 /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2976 /// is invariant in the calling loop.
2977 bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2978 Instruction *Inst2) {
2979 // First check if the result is already in the cache.
2980 AliasCacheKey key = std::make_pair(Inst1, Inst2);
2981 std::optional<bool> &result = AliasCache[key];
2982 if (result) {
2983 return *result;
2984 }
2985 bool aliased = true;
2986 if (Loc1.Ptr && isSimple(Inst1))
2987 aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2988 // Store the result in the cache.
2989 result = aliased;
2990 return aliased;
2991 }
2992
2993 using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2994
2995 /// Cache for alias results.
2996 /// TODO: consider moving this to the AliasAnalysis itself.
2997 DenseMap<AliasCacheKey, std::optional<bool>> AliasCache;
2998
2999 // Cache for pointerMayBeCaptured calls inside AA. This is preserved
3000 // globally through SLP because we don't perform any action which
3001 // invalidates capture results.
3002 BatchAAResults BatchAA;
3003
3004 /// Temporary store for deleted instructions. Instructions will be deleted
3005 /// eventually when the BoUpSLP is destructed. The deferral is required to
3006 /// ensure that there are no incorrect collisions in the AliasCache, which
3007 /// can happen if a new instruction is allocated at the same address as a
3008 /// previously deleted instruction.
3009 DenseSet<Instruction *> DeletedInstructions;
3010
3011 /// Set of the instruction, being analyzed already for reductions.
3012 SmallPtrSet<Instruction *, 16> AnalyzedReductionsRoots;
3013
3014 /// Set of hashes for the list of reduction values already being analyzed.
3015 DenseSet<size_t> AnalyzedReductionVals;
3016
3017 /// A list of values that need to extracted out of the tree.
3018 /// This list holds pairs of (Internal Scalar : External User). External User
3019 /// can be nullptr, it means that this Internal Scalar will be used later,
3020 /// after vectorization.
3021 UserList ExternalUses;
3022
3023 /// Values used only by @llvm.assume calls.
3024 SmallPtrSet<const Value *, 32> EphValues;
3025
3026 /// Holds all of the instructions that we gathered, shuffle instructions and
3027 /// extractelements.
3028 SetVector<Instruction *> GatherShuffleExtractSeq;
3029
3030 /// A list of blocks that we are going to CSE.
3031 SetVector<BasicBlock *> CSEBlocks;
3032
3033 /// Contains all scheduling relevant data for an instruction.
3034 /// A ScheduleData either represents a single instruction or a member of an
3035 /// instruction bundle (= a group of instructions which is combined into a
3036 /// vector instruction).
3037 struct ScheduleData {
3038 // The initial value for the dependency counters. It means that the
3039 // dependencies are not calculated yet.
3040 enum { InvalidDeps = -1 };
3041
3042 ScheduleData() = default;
3043
3044 void init(int BlockSchedulingRegionID, Value *OpVal) {
3045 FirstInBundle = this;
3046 NextInBundle = nullptr;
3047 NextLoadStore = nullptr;
3048 IsScheduled = false;
3049 SchedulingRegionID = BlockSchedulingRegionID;
3050 clearDependencies();
3051 OpValue = OpVal;
3052 TE = nullptr;
3053 }
3054
3055 /// Verify basic self consistency properties
3056 void verify() {
3057 if (hasValidDependencies()) {
3058 assert(UnscheduledDeps <= Dependencies && "invariant")(static_cast <bool> (UnscheduledDeps <= Dependencies
&& "invariant") ? void (0) : __assert_fail ("UnscheduledDeps <= Dependencies && \"invariant\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3058, __extension__
__PRETTY_FUNCTION__))
;
3059 } else {
3060 assert(UnscheduledDeps == Dependencies && "invariant")(static_cast <bool> (UnscheduledDeps == Dependencies &&
"invariant") ? void (0) : __assert_fail ("UnscheduledDeps == Dependencies && \"invariant\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3060, __extension__
__PRETTY_FUNCTION__))
;
3061 }
3062
3063 if (IsScheduled) {
3064 assert(isSchedulingEntity() &&(static_cast <bool> (isSchedulingEntity() && "unexpected scheduled state"
) ? void (0) : __assert_fail ("isSchedulingEntity() && \"unexpected scheduled state\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3065, __extension__
__PRETTY_FUNCTION__))
3065 "unexpected scheduled state")(static_cast <bool> (isSchedulingEntity() && "unexpected scheduled state"
) ? void (0) : __assert_fail ("isSchedulingEntity() && \"unexpected scheduled state\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3065, __extension__
__PRETTY_FUNCTION__))
;
3066 for (const ScheduleData *BundleMember = this; BundleMember;
3067 BundleMember = BundleMember->NextInBundle) {
3068 assert(BundleMember->hasValidDependencies() &&(static_cast <bool> (BundleMember->hasValidDependencies
() && BundleMember->UnscheduledDeps == 0 &&
"unexpected scheduled state") ? void (0) : __assert_fail ("BundleMember->hasValidDependencies() && BundleMember->UnscheduledDeps == 0 && \"unexpected scheduled state\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3070, __extension__
__PRETTY_FUNCTION__))
3069 BundleMember->UnscheduledDeps == 0 &&(static_cast <bool> (BundleMember->hasValidDependencies
() && BundleMember->UnscheduledDeps == 0 &&
"unexpected scheduled state") ? void (0) : __assert_fail ("BundleMember->hasValidDependencies() && BundleMember->UnscheduledDeps == 0 && \"unexpected scheduled state\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3070, __extension__
__PRETTY_FUNCTION__))
3070 "unexpected scheduled state")(static_cast <bool> (BundleMember->hasValidDependencies
() && BundleMember->UnscheduledDeps == 0 &&
"unexpected scheduled state") ? void (0) : __assert_fail ("BundleMember->hasValidDependencies() && BundleMember->UnscheduledDeps == 0 && \"unexpected scheduled state\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3070, __extension__
__PRETTY_FUNCTION__))
;
3071 assert((BundleMember == this || !BundleMember->IsScheduled) &&(static_cast <bool> ((BundleMember == this || !BundleMember
->IsScheduled) && "only bundle is marked scheduled"
) ? void (0) : __assert_fail ("(BundleMember == this || !BundleMember->IsScheduled) && \"only bundle is marked scheduled\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3072, __extension__
__PRETTY_FUNCTION__))
3072 "only bundle is marked scheduled")(static_cast <bool> ((BundleMember == this || !BundleMember
->IsScheduled) && "only bundle is marked scheduled"
) ? void (0) : __assert_fail ("(BundleMember == this || !BundleMember->IsScheduled) && \"only bundle is marked scheduled\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3072, __extension__
__PRETTY_FUNCTION__))
;
3073 }
3074 }
3075
3076 assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&(static_cast <bool> (Inst->getParent() == FirstInBundle
->Inst->getParent() && "all bundle members must be in same basic block"
) ? void (0) : __assert_fail ("Inst->getParent() == FirstInBundle->Inst->getParent() && \"all bundle members must be in same basic block\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3077, __extension__
__PRETTY_FUNCTION__))
3077 "all bundle members must be in same basic block")(static_cast <bool> (Inst->getParent() == FirstInBundle
->Inst->getParent() && "all bundle members must be in same basic block"
) ? void (0) : __assert_fail ("Inst->getParent() == FirstInBundle->Inst->getParent() && \"all bundle members must be in same basic block\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3077, __extension__
__PRETTY_FUNCTION__))
;
3078 }
3079
3080 /// Returns true if the dependency information has been calculated.
3081 /// Note that depenendency validity can vary between instructions within
3082 /// a single bundle.
3083 bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
3084
3085 /// Returns true for single instructions and for bundle representatives
3086 /// (= the head of a bundle).
3087 bool isSchedulingEntity() const { return FirstInBundle == this; }
3088
3089 /// Returns true if it represents an instruction bundle and not only a
3090 /// single instruction.
3091 bool isPartOfBundle() const {
3092 return NextInBundle != nullptr || FirstInBundle != this || TE;
3093 }
3094
3095 /// Returns true if it is ready for scheduling, i.e. it has no more
3096 /// unscheduled depending instructions/bundles.
3097 bool isReady() const {
3098 assert(isSchedulingEntity() &&(static_cast <bool> (isSchedulingEntity() && "can't consider non-scheduling entity for ready list"
) ? void (0) : __assert_fail ("isSchedulingEntity() && \"can't consider non-scheduling entity for ready list\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3099, __extension__
__PRETTY_FUNCTION__))
3099 "can't consider non-scheduling entity for ready list")(static_cast <bool> (isSchedulingEntity() && "can't consider non-scheduling entity for ready list"
) ? void (0) : __assert_fail ("isSchedulingEntity() && \"can't consider non-scheduling entity for ready list\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3099, __extension__
__PRETTY_FUNCTION__))
;
3100 return unscheduledDepsInBundle() == 0 && !IsScheduled;
3101 }
3102
3103 /// Modifies the number of unscheduled dependencies for this instruction,
3104 /// and returns the number of remaining dependencies for the containing
3105 /// bundle.
3106 int incrementUnscheduledDeps(int Incr) {
3107 assert(hasValidDependencies() &&(static_cast <bool> (hasValidDependencies() && "increment of unscheduled deps would be meaningless"
) ? void (0) : __assert_fail ("hasValidDependencies() && \"increment of unscheduled deps would be meaningless\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3108, __extension__
__PRETTY_FUNCTION__))
3108 "increment of unscheduled deps would be meaningless")(static_cast <bool> (hasValidDependencies() && "increment of unscheduled deps would be meaningless"
) ? void (0) : __assert_fail ("hasValidDependencies() && \"increment of unscheduled deps would be meaningless\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3108, __extension__
__PRETTY_FUNCTION__))
;
3109 UnscheduledDeps += Incr;
3110 return FirstInBundle->unscheduledDepsInBundle();
3111 }
3112
3113 /// Sets the number of unscheduled dependencies to the number of
3114 /// dependencies.
3115 void resetUnscheduledDeps() {
3116 UnscheduledDeps = Dependencies;
3117 }
3118
3119 /// Clears all dependency information.
3120 void clearDependencies() {
3121 Dependencies = InvalidDeps;
3122 resetUnscheduledDeps();
3123 MemoryDependencies.clear();
3124 ControlDependencies.clear();
3125 }
3126
3127 int unscheduledDepsInBundle() const {
3128 assert(isSchedulingEntity() && "only meaningful on the bundle")(static_cast <bool> (isSchedulingEntity() && "only meaningful on the bundle"
) ? void (0) : __assert_fail ("isSchedulingEntity() && \"only meaningful on the bundle\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3128, __extension__
__PRETTY_FUNCTION__))
;
3129 int Sum = 0;
3130 for (const ScheduleData *BundleMember = this; BundleMember;
3131 BundleMember = BundleMember->NextInBundle) {
3132 if (BundleMember->UnscheduledDeps == InvalidDeps)
3133 return InvalidDeps;
3134 Sum += BundleMember->UnscheduledDeps;
3135 }
3136 return Sum;
3137 }
3138
3139 void dump(raw_ostream &os) const {
3140 if (!isSchedulingEntity()) {
3141 os << "/ " << *Inst;
3142 } else if (NextInBundle) {
3143 os << '[' << *Inst;
3144 ScheduleData *SD = NextInBundle;
3145 while (SD) {
3146 os << ';' << *SD->Inst;
3147 SD = SD->NextInBundle;
3148 }
3149 os << ']';
3150 } else {
3151 os << *Inst;
3152 }
3153 }
3154
3155 Instruction *Inst = nullptr;
3156
3157 /// Opcode of the current instruction in the schedule data.
3158 Value *OpValue = nullptr;
3159
3160 /// The TreeEntry that this instruction corresponds to.
3161 TreeEntry *TE = nullptr;
3162
3163 /// Points to the head in an instruction bundle (and always to this for
3164 /// single instructions).
3165 ScheduleData *FirstInBundle = nullptr;
3166
3167 /// Single linked list of all instructions in a bundle. Null if it is a
3168 /// single instruction.
3169 ScheduleData *NextInBundle = nullptr;
3170
3171 /// Single linked list of all memory instructions (e.g. load, store, call)
3172 /// in the block - until the end of the scheduling region.
3173 ScheduleData *NextLoadStore = nullptr;
3174
3175 /// The dependent memory instructions.
3176 /// This list is derived on demand in calculateDependencies().
3177 SmallVector<ScheduleData *, 4> MemoryDependencies;
3178
3179 /// List of instructions which this instruction could be control dependent
3180 /// on. Allowing such nodes to be scheduled below this one could introduce
3181 /// a runtime fault which didn't exist in the original program.
3182 /// ex: this is a load or udiv following a readonly call which inf loops
3183 SmallVector<ScheduleData *, 4> ControlDependencies;
3184
3185 /// This ScheduleData is in the current scheduling region if this matches
3186 /// the current SchedulingRegionID of BlockScheduling.
3187 int SchedulingRegionID = 0;
3188
3189 /// Used for getting a "good" final ordering of instructions.
3190 int SchedulingPriority = 0;
3191
3192 /// The number of dependencies. Constitutes of the number of users of the
3193 /// instruction plus the number of dependent memory instructions (if any).
3194 /// This value is calculated on demand.
3195 /// If InvalidDeps, the number of dependencies is not calculated yet.
3196 int Dependencies = InvalidDeps;
3197
3198 /// The number of dependencies minus the number of dependencies of scheduled
3199 /// instructions. As soon as this is zero, the instruction/bundle gets ready
3200 /// for scheduling.
3201 /// Note that this is negative as long as Dependencies is not calculated.
3202 int UnscheduledDeps = InvalidDeps;
3203
3204 /// True if this instruction is scheduled (or considered as scheduled in the
3205 /// dry-run).
3206 bool IsScheduled = false;
3207 };
3208
3209#ifndef NDEBUG
3210 friend inline raw_ostream &operator<<(raw_ostream &os,
3211 const BoUpSLP::ScheduleData &SD) {
3212 SD.dump(os);
3213 return os;
3214 }
3215#endif
3216
3217 friend struct GraphTraits<BoUpSLP *>;
3218 friend struct DOTGraphTraits<BoUpSLP *>;
3219
3220 /// Contains all scheduling data for a basic block.
3221 /// It does not schedules instructions, which are not memory read/write
3222 /// instructions and their operands are either constants, or arguments, or
3223 /// phis, or instructions from others blocks, or their users are phis or from
3224 /// the other blocks. The resulting vector instructions can be placed at the
3225 /// beginning of the basic block without scheduling (if operands does not need
3226 /// to be scheduled) or at the end of the block (if users are outside of the
3227 /// block). It allows to save some compile time and memory used by the
3228 /// compiler.
3229 /// ScheduleData is assigned for each instruction in between the boundaries of
3230 /// the tree entry, even for those, which are not part of the graph. It is
3231 /// required to correctly follow the dependencies between the instructions and
3232 /// their correct scheduling. The ScheduleData is not allocated for the
3233 /// instructions, which do not require scheduling, like phis, nodes with
3234 /// extractelements/insertelements only or nodes with instructions, with
3235 /// uses/operands outside of the block.
3236 struct BlockScheduling {
3237 BlockScheduling(BasicBlock *BB)
3238 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
3239
3240 void clear() {
3241 ReadyInsts.clear();
3242 ScheduleStart = nullptr;
3243 ScheduleEnd = nullptr;
3244 FirstLoadStoreInRegion = nullptr;
3245 LastLoadStoreInRegion = nullptr;
3246 RegionHasStackSave = false;
3247
3248 // Reduce the maximum schedule region size by the size of the
3249 // previous scheduling run.
3250 ScheduleRegionSizeLimit -= ScheduleRegionSize;
3251 if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
3252 ScheduleRegionSizeLimit = MinScheduleRegionSize;
3253 ScheduleRegionSize = 0;
3254
3255 // Make a new scheduling region, i.e. all existing ScheduleData is not
3256 // in the new region yet.
3257 ++SchedulingRegionID;
3258 }
3259
3260 ScheduleData *getScheduleData(Instruction *I) {
3261 if (BB != I->getParent())
3262 // Avoid lookup if can't possibly be in map.
3263 return nullptr;
3264 ScheduleData *SD = ScheduleDataMap.lookup(I);
3265 if (SD && isInSchedulingRegion(SD))
3266 return SD;
3267 return nullptr;
3268 }
3269
3270 ScheduleData *getScheduleData(Value *V) {
3271 if (auto *I = dyn_cast<Instruction>(V))
3272 return getScheduleData(I);
3273 return nullptr;
3274 }
3275
3276 ScheduleData *getScheduleData(Value *V, Value *Key) {
3277 if (V == Key)
3278 return getScheduleData(V);
3279 auto I = ExtraScheduleDataMap.find(V);
3280 if (I != ExtraScheduleDataMap.end()) {
3281 ScheduleData *SD = I->second.lookup(Key);
3282 if (SD && isInSchedulingRegion(SD))
3283 return SD;
3284 }
3285 return nullptr;
3286 }
3287
3288 bool isInSchedulingRegion(ScheduleData *SD) const {
3289 return SD->SchedulingRegionID == SchedulingRegionID;
3290 }
3291
3292 /// Marks an instruction as scheduled and puts all dependent ready
3293 /// instructions into the ready-list.
3294 template <typename ReadyListType>
3295 void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
3296 SD->IsScheduled = true;
3297 LLVM_DEBUG(dbgs() << "SLP: schedule " << *SD << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: schedule " << *SD <<
"\n"; } } while (false)
;
3298
3299 for (ScheduleData *BundleMember = SD; BundleMember;
3300 BundleMember = BundleMember->NextInBundle) {
3301 if (BundleMember->Inst != BundleMember->OpValue)
3302 continue;
3303
3304 // Handle the def-use chain dependencies.
3305
3306 // Decrement the unscheduled counter and insert to ready list if ready.
3307 auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
3308 doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
3309 if (OpDef && OpDef->hasValidDependencies() &&
3310 OpDef->incrementUnscheduledDeps(-1) == 0) {
3311 // There are no more unscheduled dependencies after
3312 // decrementing, so we can put the dependent instruction
3313 // into the ready list.
3314 ScheduleData *DepBundle = OpDef->FirstInBundle;
3315 assert(!DepBundle->IsScheduled &&(static_cast <bool> (!DepBundle->IsScheduled &&
"already scheduled bundle gets ready") ? void (0) : __assert_fail
("!DepBundle->IsScheduled && \"already scheduled bundle gets ready\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3316, __extension__
__PRETTY_FUNCTION__))
3316 "already scheduled bundle gets ready")(static_cast <bool> (!DepBundle->IsScheduled &&
"already scheduled bundle gets ready") ? void (0) : __assert_fail
("!DepBundle->IsScheduled && \"already scheduled bundle gets ready\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3316, __extension__
__PRETTY_FUNCTION__))
;
3317 ReadyList.insert(DepBundle);
3318 LLVM_DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: gets ready (def): " <<
*DepBundle << "\n"; } } while (false)
3319 << "SLP: gets ready (def): " << *DepBundle << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: gets ready (def): " <<
*DepBundle << "\n"; } } while (false)
;
3320 }
3321 });
3322 };
3323
3324 // If BundleMember is a vector bundle, its operands may have been
3325 // reordered during buildTree(). We therefore need to get its operands
3326 // through the TreeEntry.
3327 if (TreeEntry *TE = BundleMember->TE) {
3328 // Need to search for the lane since the tree entry can be reordered.
3329 int Lane = std::distance(TE->Scalars.begin(),
3330 find(TE->Scalars, BundleMember->Inst));
3331 assert(Lane >= 0 && "Lane not set")(static_cast <bool> (Lane >= 0 && "Lane not set"
) ? void (0) : __assert_fail ("Lane >= 0 && \"Lane not set\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3331, __extension__
__PRETTY_FUNCTION__))
;
3332
3333 // Since vectorization tree is being built recursively this assertion
3334 // ensures that the tree entry has all operands set before reaching
3335 // this code. Couple of exceptions known at the moment are extracts
3336 // where their second (immediate) operand is not added. Since
3337 // immediates do not affect scheduler behavior this is considered
3338 // okay.
3339 auto *In = BundleMember->Inst;
3340 assert(In &&(static_cast <bool> (In && (isa<ExtractValueInst
, ExtractElementInst>(In) || In->getNumOperands() == TE
->getNumOperands()) && "Missed TreeEntry operands?"
) ? void (0) : __assert_fail ("In && (isa<ExtractValueInst, ExtractElementInst>(In) || In->getNumOperands() == TE->getNumOperands()) && \"Missed TreeEntry operands?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3343, __extension__
__PRETTY_FUNCTION__))
3341 (isa<ExtractValueInst, ExtractElementInst>(In) ||(static_cast <bool> (In && (isa<ExtractValueInst
, ExtractElementInst>(In) || In->getNumOperands() == TE
->getNumOperands()) && "Missed TreeEntry operands?"
) ? void (0) : __assert_fail ("In && (isa<ExtractValueInst, ExtractElementInst>(In) || In->getNumOperands() == TE->getNumOperands()) && \"Missed TreeEntry operands?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3343, __extension__
__PRETTY_FUNCTION__))
3342 In->getNumOperands() == TE->getNumOperands()) &&(static_cast <bool> (In && (isa<ExtractValueInst
, ExtractElementInst>(In) || In->getNumOperands() == TE
->getNumOperands()) && "Missed TreeEntry operands?"
) ? void (0) : __assert_fail ("In && (isa<ExtractValueInst, ExtractElementInst>(In) || In->getNumOperands() == TE->getNumOperands()) && \"Missed TreeEntry operands?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3343, __extension__
__PRETTY_FUNCTION__))
3343 "Missed TreeEntry operands?")(static_cast <bool> (In && (isa<ExtractValueInst
, ExtractElementInst>(In) || In->getNumOperands() == TE
->getNumOperands()) && "Missed TreeEntry operands?"
) ? void (0) : __assert_fail ("In && (isa<ExtractValueInst, ExtractElementInst>(In) || In->getNumOperands() == TE->getNumOperands()) && \"Missed TreeEntry operands?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3343, __extension__
__PRETTY_FUNCTION__))
;
3344 (void)In; // fake use to avoid build failure when assertions disabled
3345
3346 for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
3347 OpIdx != NumOperands; ++OpIdx)
3348 if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
3349 DecrUnsched(I);
3350 } else {
3351 // If BundleMember is a stand-alone instruction, no operand reordering
3352 // has taken place, so we directly access its operands.
3353 for (Use &U : BundleMember->Inst->operands())
3354 if (auto *I = dyn_cast<Instruction>(U.get()))
3355 DecrUnsched(I);
3356 }
3357 // Handle the memory dependencies.
3358 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
3359 if (MemoryDepSD->hasValidDependencies() &&
3360 MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
3361 // There are no more unscheduled dependencies after decrementing,
3362 // so we can put the dependent instruction into the ready list.
3363 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
3364 assert(!DepBundle->IsScheduled &&(static_cast <bool> (!DepBundle->IsScheduled &&
"already scheduled bundle gets ready") ? void (0) : __assert_fail
("!DepBundle->IsScheduled && \"already scheduled bundle gets ready\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3365, __extension__
__PRETTY_FUNCTION__))
3365 "already scheduled bundle gets ready")(static_cast <bool> (!DepBundle->IsScheduled &&
"already scheduled bundle gets ready") ? void (0) : __assert_fail
("!DepBundle->IsScheduled && \"already scheduled bundle gets ready\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3365, __extension__
__PRETTY_FUNCTION__))
;
3366 ReadyList.insert(DepBundle);
3367 LLVM_DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: gets ready (mem): " <<
*DepBundle << "\n"; } } while (false)
3368 << "SLP: gets ready (mem): " << *DepBundle << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: gets ready (mem): " <<
*DepBundle << "\n"; } } while (false)
;
3369 }
3370 }
3371 // Handle the control dependencies.
3372 for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
3373 if (DepSD->incrementUnscheduledDeps(-1) == 0) {
3374 // There are no more unscheduled dependencies after decrementing,
3375 // so we can put the dependent instruction into the ready list.
3376 ScheduleData *DepBundle = DepSD->FirstInBundle;
3377 assert(!DepBundle->IsScheduled &&(static_cast <bool> (!DepBundle->IsScheduled &&
"already scheduled bundle gets ready") ? void (0) : __assert_fail
("!DepBundle->IsScheduled && \"already scheduled bundle gets ready\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3378, __extension__
__PRETTY_FUNCTION__))
3378 "already scheduled bundle gets ready")(static_cast <bool> (!DepBundle->IsScheduled &&
"already scheduled bundle gets ready") ? void (0) : __assert_fail
("!DepBundle->IsScheduled && \"already scheduled bundle gets ready\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3378, __extension__
__PRETTY_FUNCTION__))
;
3379 ReadyList.insert(DepBundle);
3380 LLVM_DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: gets ready (ctl): " <<
*DepBundle << "\n"; } } while (false)
3381 << "SLP: gets ready (ctl): " << *DepBundle << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: gets ready (ctl): " <<
*DepBundle << "\n"; } } while (false)
;
3382 }
3383 }
3384
3385 }
3386 }
3387
3388 /// Verify basic self consistency properties of the data structure.
3389 void verify() {
3390 if (!ScheduleStart)
3391 return;
3392
3393 assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&(static_cast <bool> (ScheduleStart->getParent() == ScheduleEnd
->getParent() && ScheduleStart->comesBefore(ScheduleEnd
) && "Not a valid scheduling region?") ? void (0) : __assert_fail
("ScheduleStart->getParent() == ScheduleEnd->getParent() && ScheduleStart->comesBefore(ScheduleEnd) && \"Not a valid scheduling region?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3395, __extension__
__PRETTY_FUNCTION__))
3394 ScheduleStart->comesBefore(ScheduleEnd) &&(static_cast <bool> (ScheduleStart->getParent() == ScheduleEnd
->getParent() && ScheduleStart->comesBefore(ScheduleEnd
) && "Not a valid scheduling region?") ? void (0) : __assert_fail
("ScheduleStart->getParent() == ScheduleEnd->getParent() && ScheduleStart->comesBefore(ScheduleEnd) && \"Not a valid scheduling region?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3395, __extension__
__PRETTY_FUNCTION__))
3395 "Not a valid scheduling region?")(static_cast <bool> (ScheduleStart->getParent() == ScheduleEnd
->getParent() && ScheduleStart->comesBefore(ScheduleEnd
) && "Not a valid scheduling region?") ? void (0) : __assert_fail
("ScheduleStart->getParent() == ScheduleEnd->getParent() && ScheduleStart->comesBefore(ScheduleEnd) && \"Not a valid scheduling region?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3395, __extension__
__PRETTY_FUNCTION__))
;
3396
3397 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3398 auto *SD = getScheduleData(I);
3399 if (!SD)
3400 continue;
3401 assert(isInSchedulingRegion(SD) &&(static_cast <bool> (isInSchedulingRegion(SD) &&
"primary schedule data not in window?") ? void (0) : __assert_fail
("isInSchedulingRegion(SD) && \"primary schedule data not in window?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3402, __extension__
__PRETTY_FUNCTION__))
3402 "primary schedule data not in window?")(static_cast <bool> (isInSchedulingRegion(SD) &&
"primary schedule data not in window?") ? void (0) : __assert_fail
("isInSchedulingRegion(SD) && \"primary schedule data not in window?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3402, __extension__
__PRETTY_FUNCTION__))
;
3403 assert(isInSchedulingRegion(SD->FirstInBundle) &&(static_cast <bool> (isInSchedulingRegion(SD->FirstInBundle
) && "entire bundle in window!") ? void (0) : __assert_fail
("isInSchedulingRegion(SD->FirstInBundle) && \"entire bundle in window!\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3404, __extension__
__PRETTY_FUNCTION__))
3404 "entire bundle in window!")(static_cast <bool> (isInSchedulingRegion(SD->FirstInBundle
) && "entire bundle in window!") ? void (0) : __assert_fail
("isInSchedulingRegion(SD->FirstInBundle) && \"entire bundle in window!\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3404, __extension__
__PRETTY_FUNCTION__))
;
3405 (void)SD;
3406 doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
3407 }
3408
3409 for (auto *SD : ReadyInsts) {
3410 assert(SD->isSchedulingEntity() && SD->isReady() &&(static_cast <bool> (SD->isSchedulingEntity() &&
SD->isReady() && "item in ready list not ready?")
? void (0) : __assert_fail ("SD->isSchedulingEntity() && SD->isReady() && \"item in ready list not ready?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3411, __extension__
__PRETTY_FUNCTION__))
3411 "item in ready list not ready?")(static_cast <bool> (SD->isSchedulingEntity() &&
SD->isReady() && "item in ready list not ready?")
? void (0) : __assert_fail ("SD->isSchedulingEntity() && SD->isReady() && \"item in ready list not ready?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3411, __extension__
__PRETTY_FUNCTION__))
;
3412 (void)SD;
3413 }
3414 }
3415
3416 void doForAllOpcodes(Value *V,
3417 function_ref<void(ScheduleData *SD)> Action) {
3418 if (ScheduleData *SD = getScheduleData(V))
3419 Action(SD);
3420 auto I = ExtraScheduleDataMap.find(V);
3421 if (I != ExtraScheduleDataMap.end())
3422 for (auto &P : I->second)
3423 if (isInSchedulingRegion(P.second))
3424 Action(P.second);
3425 }
3426
3427 /// Put all instructions into the ReadyList which are ready for scheduling.
3428 template <typename ReadyListType>
3429 void initialFillReadyList(ReadyListType &ReadyList) {
3430 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3431 doForAllOpcodes(I, [&](ScheduleData *SD) {
3432 if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
3433 SD->isReady()) {
3434 ReadyList.insert(SD);
3435 LLVM_DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: initially in ready list: "
<< *SD << "\n"; } } while (false)
3436 << "SLP: initially in ready list: " << *SD << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: initially in ready list: "
<< *SD << "\n"; } } while (false)
;
3437 }
3438 });
3439 }
3440 }
3441
3442 /// Build a bundle from the ScheduleData nodes corresponding to the
3443 /// scalar instruction for each lane.
3444 ScheduleData *buildBundle(ArrayRef<Value *> VL);
3445
3446 /// Checks if a bundle of instructions can be scheduled, i.e. has no
3447 /// cyclic dependencies. This is only a dry-run, no instructions are
3448 /// actually moved at this stage.
3449 /// \returns the scheduling bundle. The returned Optional value is not
3450 /// std::nullopt if \p VL is allowed to be scheduled.
3451 std::optional<ScheduleData *>
3452 tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
3453 const InstructionsState &S);
3454
3455 /// Un-bundles a group of instructions.
3456 void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
3457
3458 /// Allocates schedule data chunk.
3459 ScheduleData *allocateScheduleDataChunks();
3460
3461 /// Extends the scheduling region so that V is inside the region.
3462 /// \returns true if the region size is within the limit.
3463 bool extendSchedulingRegion(Value *V, const InstructionsState &S);
3464
3465 /// Initialize the ScheduleData structures for new instructions in the
3466 /// scheduling region.
3467 void initScheduleData(Instruction *FromI, Instruction *ToI,
3468 ScheduleData *PrevLoadStore,
3469 ScheduleData *NextLoadStore);
3470
3471 /// Updates the dependency information of a bundle and of all instructions/
3472 /// bundles which depend on the original bundle.
3473 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
3474 BoUpSLP *SLP);
3475
3476 /// Sets all instruction in the scheduling region to un-scheduled.
3477 void resetSchedule();
3478
3479 BasicBlock *BB;
3480
3481 /// Simple memory allocation for ScheduleData.
3482 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
3483
3484 /// The size of a ScheduleData array in ScheduleDataChunks.
3485 int ChunkSize;
3486
3487 /// The allocator position in the current chunk, which is the last entry
3488 /// of ScheduleDataChunks.
3489 int ChunkPos;
3490
3491 /// Attaches ScheduleData to Instruction.
3492 /// Note that the mapping survives during all vectorization iterations, i.e.
3493 /// ScheduleData structures are recycled.
3494 DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
3495
3496 /// Attaches ScheduleData to Instruction with the leading key.
3497 DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
3498 ExtraScheduleDataMap;
3499
3500 /// The ready-list for scheduling (only used for the dry-run).
3501 SetVector<ScheduleData *> ReadyInsts;
3502
3503 /// The first instruction of the scheduling region.
3504 Instruction *ScheduleStart = nullptr;
3505
3506 /// The first instruction _after_ the scheduling region.
3507 Instruction *ScheduleEnd = nullptr;
3508
3509 /// The first memory accessing instruction in the scheduling region
3510 /// (can be null).
3511 ScheduleData *FirstLoadStoreInRegion = nullptr;
3512
3513 /// The last memory accessing instruction in the scheduling region
3514 /// (can be null).
3515 ScheduleData *LastLoadStoreInRegion = nullptr;
3516
3517 /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling
3518 /// region? Used to optimize the dependence calculation for the
3519 /// common case where there isn't.
3520 bool RegionHasStackSave = false;
3521
3522 /// The current size of the scheduling region.
3523 int ScheduleRegionSize = 0;
3524
3525 /// The maximum size allowed for the scheduling region.
3526 int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3527
3528 /// The ID of the scheduling region. For a new vectorization iteration this
3529 /// is incremented which "removes" all ScheduleData from the region.
3530 /// Make sure that the initial SchedulingRegionID is greater than the
3531 /// initial SchedulingRegionID in ScheduleData (which is 0).
3532 int SchedulingRegionID = 1;
3533 };
3534
3535 /// Attaches the BlockScheduling structures to basic blocks.
3536 MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3537
3538 /// Performs the "real" scheduling. Done before vectorization is actually
3539 /// performed in a basic block.
3540 void scheduleBlock(BlockScheduling *BS);
3541
3542 /// List of users to ignore during scheduling and that don't need extracting.
3543 const SmallDenseSet<Value *> *UserIgnoreList = nullptr;
3544
3545 /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3546 /// sorted SmallVectors of unsigned.
3547 struct OrdersTypeDenseMapInfo {
3548 static OrdersType getEmptyKey() {
3549 OrdersType V;
3550 V.push_back(~1U);
3551 return V;
3552 }
3553
3554 static OrdersType getTombstoneKey() {
3555 OrdersType V;
3556 V.push_back(~2U);
3557 return V;
3558 }
3559
3560 static unsigned getHashValue(const OrdersType &V) {
3561 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3562 }
3563
3564 static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3565 return LHS == RHS;
3566 }
3567 };
3568
3569 // Analysis and block reference.
3570 Function *F;
3571 ScalarEvolution *SE;
3572 TargetTransformInfo *TTI;
3573 TargetLibraryInfo *TLI;
3574 LoopInfo *LI;
3575 DominatorTree *DT;
3576 AssumptionCache *AC;
3577 DemandedBits *DB;
3578 const DataLayout *DL;
3579 OptimizationRemarkEmitter *ORE;
3580
3581 unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3582 unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3583
3584 /// Instruction builder to construct the vectorized tree.
3585 IRBuilder<> Builder;
3586
3587 /// A map of scalar integer values to the smallest bit width with which they
3588 /// can legally be represented. The values map to (width, signed) pairs,
3589 /// where "width" indicates the minimum bit width and "signed" is True if the
3590 /// value must be signed-extended, rather than zero-extended, back to its
3591 /// original width.
3592 MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3593};
3594
3595} // end namespace slpvectorizer
3596
3597template <> struct GraphTraits<BoUpSLP *> {
3598 using TreeEntry = BoUpSLP::TreeEntry;
3599
3600 /// NodeRef has to be a pointer per the GraphWriter.
3601 using NodeRef = TreeEntry *;
3602
3603 using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3604
3605 /// Add the VectorizableTree to the index iterator to be able to return
3606 /// TreeEntry pointers.
3607 struct ChildIteratorType
3608 : public iterator_adaptor_base<
3609 ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3610 ContainerTy &VectorizableTree;
3611
3612 ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3613 ContainerTy &VT)
3614 : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3615
3616 NodeRef operator*() { return I->UserTE; }
3617 };
3618
3619 static NodeRef getEntryNode(BoUpSLP &R) {
3620 return R.VectorizableTree[0].get();
3621 }
3622
3623 static ChildIteratorType child_begin(NodeRef N) {
3624 return {N->UserTreeIndices.begin(), N->Container};
3625 }
3626
3627 static ChildIteratorType child_end(NodeRef N) {
3628 return {N->UserTreeIndices.end(), N->Container};
3629 }
3630
3631 /// For the node iterator we just need to turn the TreeEntry iterator into a
3632 /// TreeEntry* iterator so that it dereferences to NodeRef.
3633 class nodes_iterator {
3634 using ItTy = ContainerTy::iterator;
3635 ItTy It;
3636
3637 public:
3638 nodes_iterator(const ItTy &It2) : It(It2) {}
3639 NodeRef operator*() { return It->get(); }
3640 nodes_iterator operator++() {
3641 ++It;
3642 return *this;
3643 }
3644 bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3645 };
3646
3647 static nodes_iterator nodes_begin(BoUpSLP *R) {
3648 return nodes_iterator(R->VectorizableTree.begin());
3649 }
3650
3651 static nodes_iterator nodes_end(BoUpSLP *R) {
3652 return nodes_iterator(R->VectorizableTree.end());
3653 }
3654
3655 static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3656};
3657
3658template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3659 using TreeEntry = BoUpSLP::TreeEntry;
3660
3661 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3662
3663 std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3664 std::string Str;
3665 raw_string_ostream OS(Str);
3666 OS << Entry->Idx << ".\n";
3667 if (isSplat(Entry->Scalars))
3668 OS << "<splat> ";
3669 for (auto *V : Entry->Scalars) {
3670 OS << *V;
3671 if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3672 return EU.Scalar == V;
3673 }))
3674 OS << " <extract>";
3675 OS << "\n";
3676 }
3677 return Str;
3678 }
3679
3680 static std::string getNodeAttributes(const TreeEntry *Entry,
3681 const BoUpSLP *) {
3682 if (Entry->State == TreeEntry::NeedToGather)
3683 return "color=red";
3684 if (Entry->State == TreeEntry::ScatterVectorize)
3685 return "color=blue";
3686 return "";
3687 }
3688};
3689
3690} // end namespace llvm
3691
3692BoUpSLP::~BoUpSLP() {
3693 SmallVector<WeakTrackingVH> DeadInsts;
3694 for (auto *I : DeletedInstructions) {
3695 for (Use &U : I->operands()) {
3696 auto *Op = dyn_cast<Instruction>(U.get());
3697 if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() &&
3698 wouldInstructionBeTriviallyDead(Op, TLI))
3699 DeadInsts.emplace_back(Op);
3700 }
3701 I->dropAllReferences();
3702 }
3703 for (auto *I : DeletedInstructions) {
3704 assert(I->use_empty() &&(static_cast <bool> (I->use_empty() && "trying to erase instruction with users."
) ? void (0) : __assert_fail ("I->use_empty() && \"trying to erase instruction with users.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3705, __extension__
__PRETTY_FUNCTION__))
3705 "trying to erase instruction with users.")(static_cast <bool> (I->use_empty() && "trying to erase instruction with users."
) ? void (0) : __assert_fail ("I->use_empty() && \"trying to erase instruction with users.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3705, __extension__
__PRETTY_FUNCTION__))
;
3706 I->eraseFromParent();
3707 }
3708
3709 // Cleanup any dead scalar code feeding the vectorized instructions
3710 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI);
3711
3712#ifdef EXPENSIVE_CHECKS
3713 // If we could guarantee that this call is not extremely slow, we could
3714 // remove the ifdef limitation (see PR47712).
3715 assert(!verifyFunction(*F, &dbgs()))(static_cast <bool> (!verifyFunction(*F, &dbgs())) ?
void (0) : __assert_fail ("!verifyFunction(*F, &dbgs())"
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3715, __extension__
__PRETTY_FUNCTION__))
;
3716#endif
3717}
3718
3719/// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3720/// contains original mask for the scalars reused in the node. Procedure
3721/// transform this mask in accordance with the given \p Mask.
3722static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3723 assert(!Mask.empty() && Reuses.size() == Mask.size() &&(static_cast <bool> (!Mask.empty() && Reuses.size
() == Mask.size() && "Expected non-empty mask.") ? void
(0) : __assert_fail ("!Mask.empty() && Reuses.size() == Mask.size() && \"Expected non-empty mask.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3724, __extension__
__PRETTY_FUNCTION__))
3724 "Expected non-empty mask.")(static_cast <bool> (!Mask.empty() && Reuses.size
() == Mask.size() && "Expected non-empty mask.") ? void
(0) : __assert_fail ("!Mask.empty() && Reuses.size() == Mask.size() && \"Expected non-empty mask.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3724, __extension__
__PRETTY_FUNCTION__))
;
3725 SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3726 Prev.swap(Reuses);
3727 for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3728 if (Mask[I] != PoisonMaskElem)
3729 Reuses[Mask[I]] = Prev[I];
3730}
3731
3732/// Reorders the given \p Order according to the given \p Mask. \p Order - is
3733/// the original order of the scalars. Procedure transforms the provided order
3734/// in accordance with the given \p Mask. If the resulting \p Order is just an
3735/// identity order, \p Order is cleared.
3736static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3737 assert(!Mask.empty() && "Expected non-empty mask.")(static_cast <bool> (!Mask.empty() && "Expected non-empty mask."
) ? void (0) : __assert_fail ("!Mask.empty() && \"Expected non-empty mask.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3737, __extension__
__PRETTY_FUNCTION__))
;
3738 SmallVector<int> MaskOrder;
3739 if (Order.empty()) {
3740 MaskOrder.resize(Mask.size());
3741 std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3742 } else {
3743 inversePermutation(Order, MaskOrder);
3744 }
3745 reorderReuses(MaskOrder, Mask);
3746 if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3747 Order.clear();
3748 return;
3749 }
3750 Order.assign(Mask.size(), Mask.size());
3751 for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3752 if (MaskOrder[I] != PoisonMaskElem)
3753 Order[MaskOrder[I]] = I;
3754 fixupOrderingIndices(Order);
3755}
3756
3757std::optional<BoUpSLP::OrdersType>
3758BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3759 assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.")(static_cast <bool> (TE.State == TreeEntry::NeedToGather
&& "Expected gather node only.") ? void (0) : __assert_fail
("TE.State == TreeEntry::NeedToGather && \"Expected gather node only.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3759, __extension__
__PRETTY_FUNCTION__))
;
3760 unsigned NumScalars = TE.Scalars.size();
3761 OrdersType CurrentOrder(NumScalars, NumScalars);
3762 SmallVector<int> Positions;
3763 SmallBitVector UsedPositions(NumScalars);
3764 const TreeEntry *STE = nullptr;
3765 // Try to find all gathered scalars that are gets vectorized in other
3766 // vectorize node. Here we can have only one single tree vector node to
3767 // correctly identify order of the gathered scalars.
3768 for (unsigned I = 0; I < NumScalars; ++I) {
3769 Value *V = TE.Scalars[I];
3770 if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3771 continue;
3772 if (const auto *LocalSTE = getTreeEntry(V)) {
3773 if (!STE)
3774 STE = LocalSTE;
3775 else if (STE != LocalSTE)
3776 // Take the order only from the single vector node.
3777 return std::nullopt;
3778 unsigned Lane =
3779 std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3780 if (Lane >= NumScalars)
3781 return std::nullopt;
3782 if (CurrentOrder[Lane] != NumScalars) {
3783 if (Lane != I)
3784 continue;
3785 UsedPositions.reset(CurrentOrder[Lane]);
3786 }
3787 // The partial identity (where only some elements of the gather node are
3788 // in the identity order) is good.
3789 CurrentOrder[Lane] = I;
3790 UsedPositions.set(I);
3791 }
3792 }
3793 // Need to keep the order if we have a vector entry and at least 2 scalars or
3794 // the vectorized entry has just 2 scalars.
3795 if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3796 auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3797 for (unsigned I = 0; I < NumScalars; ++I)
3798 if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3799 return false;
3800 return true;
3801 };
3802 if (IsIdentityOrder(CurrentOrder))
3803 return OrdersType();
3804 auto *It = CurrentOrder.begin();
3805 for (unsigned I = 0; I < NumScalars;) {
3806 if (UsedPositions.test(I)) {
3807 ++I;
3808 continue;
3809 }
3810 if (*It == NumScalars) {
3811 *It = I;
3812 ++I;
3813 }
3814 ++It;
3815 }
3816 return std::move(CurrentOrder);
3817 }
3818 return std::nullopt;
3819}
3820
3821namespace {
3822/// Tracks the state we can represent the loads in the given sequence.
3823enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3824} // anonymous namespace
3825
3826static bool arePointersCompatible(Value *Ptr1, Value *Ptr2,
3827 const TargetLibraryInfo &TLI,
3828 bool CompareOpcodes = true) {
3829 if (getUnderlyingObject(Ptr1) != getUnderlyingObject(Ptr2))
3830 return false;
3831 auto *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1);
3832 if (!GEP1)
3833 return false;
3834 auto *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2);
3835 if (!GEP2)
3836 return false;
3837 return GEP1->getNumOperands() == 2 && GEP2->getNumOperands() == 2 &&
3838 ((isConstant(GEP1->getOperand(1)) &&
3839 isConstant(GEP2->getOperand(1))) ||
3840 !CompareOpcodes ||
3841 getSameOpcode({GEP1->getOperand(1), GEP2->getOperand(1)}, TLI)
3842 .getOpcode());
3843}
3844
3845/// Checks if the given array of loads can be represented as a vectorized,
3846/// scatter or just simple gather.
3847static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3848 const TargetTransformInfo &TTI,
3849 const DataLayout &DL, ScalarEvolution &SE,
3850 LoopInfo &LI, const TargetLibraryInfo &TLI,
3851 SmallVectorImpl<unsigned> &Order,
3852 SmallVectorImpl<Value *> &PointerOps) {
3853 // Check that a vectorized load would load the same memory as a scalar
3854 // load. For example, we don't want to vectorize loads that are smaller
3855 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3856 // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3857 // from such a struct, we read/write packed bits disagreeing with the
3858 // unvectorized version.
3859 Type *ScalarTy = VL0->getType();
3860
3861 if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3862 return LoadsState::Gather;
3863
3864 // Make sure all loads in the bundle are simple - we can't vectorize
3865 // atomic or volatile loads.
3866 PointerOps.clear();
3867 PointerOps.resize(VL.size());
3868 auto *POIter = PointerOps.begin();
3869 for (Value *V : VL) {
3870 auto *L = cast<LoadInst>(V);
3871 if (!L->isSimple())
3872 return LoadsState::Gather;
3873 *POIter = L->getPointerOperand();
3874 ++POIter;
3875 }
3876
3877 Order.clear();
3878 // Check the order of pointer operands or that all pointers are the same.
3879 bool IsSorted = sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order);
3880 if (IsSorted || all_of(PointerOps, [&](Value *P) {
3881 return arePointersCompatible(P, PointerOps.front(), TLI);
3882 })) {
3883 if (IsSorted) {
3884 Value *Ptr0;
3885 Value *PtrN;
3886 if (Order.empty()) {
3887 Ptr0 = PointerOps.front();
3888 PtrN = PointerOps.back();
3889 } else {
3890 Ptr0 = PointerOps[Order.front()];
3891 PtrN = PointerOps[Order.back()];
3892 }
3893 std::optional<int> Diff =
3894 getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3895 // Check that the sorted loads are consecutive.
3896 if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3897 return LoadsState::Vectorize;
3898 }
3899 // TODO: need to improve analysis of the pointers, if not all of them are
3900 // GEPs or have > 2 operands, we end up with a gather node, which just
3901 // increases the cost.
3902 Loop *L = LI.getLoopFor(cast<LoadInst>(VL0)->getParent());
3903 bool ProfitableGatherPointers =
3904 static_cast<unsigned>(count_if(PointerOps, [L](Value *V) {
3905 return L && L->isLoopInvariant(V);
3906 })) <= VL.size() / 2 && VL.size() > 2;
3907 if (ProfitableGatherPointers || all_of(PointerOps, [IsSorted](Value *P) {
3908 auto *GEP = dyn_cast<GetElementPtrInst>(P);
3909 return (IsSorted && !GEP && doesNotNeedToBeScheduled(P)) ||
3910 (GEP && GEP->getNumOperands() == 2);
3911 })) {
3912 Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3913 for (Value *V : VL)
3914 CommonAlignment =
3915 std::min(CommonAlignment, cast<LoadInst>(V)->getAlign());
3916 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
3917 if (TTI.isLegalMaskedGather(VecTy, CommonAlignment) &&
3918 !TTI.forceScalarizeMaskedGather(VecTy, CommonAlignment))
3919 return LoadsState::ScatterVectorize;
3920 }
3921 }
3922
3923 return LoadsState::Gather;
3924}
3925
3926static bool clusterSortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy,
3927 const DataLayout &DL, ScalarEvolution &SE,
3928 SmallVectorImpl<unsigned> &SortedIndices) {
3929 assert(llvm::all_of((static_cast <bool> (llvm::all_of( VL, [](const Value *
V) { return V->getType()->isPointerTy(); }) && "Expected list of pointer operands."
) ? void (0) : __assert_fail ("llvm::all_of( VL, [](const Value *V) { return V->getType()->isPointerTy(); }) && \"Expected list of pointer operands.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3931, __extension__
__PRETTY_FUNCTION__))
3930 VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&(static_cast <bool> (llvm::all_of( VL, [](const Value *
V) { return V->getType()->isPointerTy(); }) && "Expected list of pointer operands."
) ? void (0) : __assert_fail ("llvm::all_of( VL, [](const Value *V) { return V->getType()->isPointerTy(); }) && \"Expected list of pointer operands.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3931, __extension__
__PRETTY_FUNCTION__))
3931 "Expected list of pointer operands.")(static_cast <bool> (llvm::all_of( VL, [](const Value *
V) { return V->getType()->isPointerTy(); }) && "Expected list of pointer operands."
) ? void (0) : __assert_fail ("llvm::all_of( VL, [](const Value *V) { return V->getType()->isPointerTy(); }) && \"Expected list of pointer operands.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3931, __extension__
__PRETTY_FUNCTION__))
;
3932 // Map from bases to a vector of (Ptr, Offset, OrigIdx), which we insert each
3933 // Ptr into, sort and return the sorted indices with values next to one
3934 // another.
3935 MapVector<Value *, SmallVector<std::tuple<Value *, int, unsigned>>> Bases;
3936 Bases[VL[0]].push_back(std::make_tuple(VL[0], 0U, 0U));
3937
3938 unsigned Cnt = 1;
3939 for (Value *Ptr : VL.drop_front()) {
3940 bool Found = any_of(Bases, [&](auto &Base) {
3941 std::optional<int> Diff =
3942 getPointersDiff(ElemTy, Base.first, ElemTy, Ptr, DL, SE,
3943 /*StrictCheck=*/true);
3944 if (!Diff)
3945 return false;
3946
3947 Base.second.emplace_back(Ptr, *Diff, Cnt++);
3948 return true;
3949 });
3950
3951 if (!Found) {
3952 // If we haven't found enough to usefully cluster, return early.
3953 if (Bases.size() > VL.size() / 2 - 1)
3954 return false;
3955
3956 // Not found already - add a new Base
3957 Bases[Ptr].emplace_back(Ptr, 0, Cnt++);
3958 }
3959 }
3960
3961 // For each of the bases sort the pointers by Offset and check if any of the
3962 // base become consecutively allocated.
3963 bool AnyConsecutive = false;
3964 for (auto &Base : Bases) {
3965 auto &Vec = Base.second;
3966 if (Vec.size() > 1) {
3967 llvm::stable_sort(Vec, [](const std::tuple<Value *, int, unsigned> &X,
3968 const std::tuple<Value *, int, unsigned> &Y) {
3969 return std::get<1>(X) < std::get<1>(Y);
3970 });
3971 int InitialOffset = std::get<1>(Vec[0]);
3972 AnyConsecutive |= all_of(enumerate(Vec), [InitialOffset](const auto &P) {
3973 return std::get<1>(P.value()) == int(P.index()) + InitialOffset;
3974 });
3975 }
3976 }
3977
3978 // Fill SortedIndices array only if it looks worth-while to sort the ptrs.
3979 SortedIndices.clear();
3980 if (!AnyConsecutive)
3981 return false;
3982
3983 for (auto &Base : Bases) {
3984 for (auto &T : Base.second)
3985 SortedIndices.push_back(std::get<2>(T));
3986 }
3987
3988 assert(SortedIndices.size() == VL.size() &&(static_cast <bool> (SortedIndices.size() == VL.size() &&
"Expected SortedIndices to be the size of VL") ? void (0) : __assert_fail
("SortedIndices.size() == VL.size() && \"Expected SortedIndices to be the size of VL\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3989, __extension__
__PRETTY_FUNCTION__))
3989 "Expected SortedIndices to be the size of VL")(static_cast <bool> (SortedIndices.size() == VL.size() &&
"Expected SortedIndices to be the size of VL") ? void (0) : __assert_fail
("SortedIndices.size() == VL.size() && \"Expected SortedIndices to be the size of VL\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3989, __extension__
__PRETTY_FUNCTION__))
;
3990 return true;
3991}
3992
3993std::optional<BoUpSLP::OrdersType>
3994BoUpSLP::findPartiallyOrderedLoads(const BoUpSLP::TreeEntry &TE) {
3995 assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.")(static_cast <bool> (TE.State == TreeEntry::NeedToGather
&& "Expected gather node only.") ? void (0) : __assert_fail
("TE.State == TreeEntry::NeedToGather && \"Expected gather node only.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3995, __extension__
__PRETTY_FUNCTION__))
;
3996 Type *ScalarTy = TE.Scalars[0]->getType();
3997
3998 SmallVector<Value *> Ptrs;
3999 Ptrs.reserve(TE.Scalars.size());
4000 for (Value *V : TE.Scalars) {
4001 auto *L = dyn_cast<LoadInst>(V);
4002 if (!L || !L->isSimple())
4003 return std::nullopt;
4004 Ptrs.push_back(L->getPointerOperand());
4005 }
4006
4007 BoUpSLP::OrdersType Order;
4008 if (clusterSortPtrAccesses(Ptrs, ScalarTy, *DL, *SE, Order))
4009 return std::move(Order);
4010 return std::nullopt;
4011}
4012
4013/// Check if two insertelement instructions are from the same buildvector.
4014static bool areTwoInsertFromSameBuildVector(
4015 InsertElementInst *VU, InsertElementInst *V,
4016 function_ref<Value *(InsertElementInst *)> GetBaseOperand) {
4017 // Instructions must be from the same basic blocks.
4018 if (VU->getParent() != V->getParent())
4019 return false;
4020 // Checks if 2 insertelements are from the same buildvector.
4021 if (VU->getType() != V->getType())
4022 return false;
4023 // Multiple used inserts are separate nodes.
4024 if (!VU->hasOneUse() && !V->hasOneUse())
4025 return false;
4026 auto *IE1 = VU;
4027 auto *IE2 = V;
4028 std::optional<unsigned> Idx1 = getInsertIndex(IE1);
4029 std::optional<unsigned> Idx2 = getInsertIndex(IE2);
4030 if (Idx1 == std::nullopt || Idx2 == std::nullopt)
4031 return false;
4032 // Go through the vector operand of insertelement instructions trying to find
4033 // either VU as the original vector for IE2 or V as the original vector for
4034 // IE1.
4035 SmallSet<int, 8> ReusedIdx;
4036 bool IsReusedIdx = false;
4037 do {
4038 if (IE2 == VU && !IE1)
4039 return VU->hasOneUse();
4040 if (IE1 == V && !IE2)
4041 return V->hasOneUse();
4042 if (IE1 && IE1 != V) {
4043 IsReusedIdx |=
4044 !ReusedIdx.insert(getInsertIndex(IE1).value_or(*Idx2)).second;
4045 if ((IE1 != VU && !IE1->hasOneUse()) || IsReusedIdx)
4046 IE1 = nullptr;
4047 else
4048 IE1 = dyn_cast_or_null<InsertElementInst>(GetBaseOperand(IE1));
4049 }
4050 if (IE2 && IE2 != VU) {
4051 IsReusedIdx |=
4052 !ReusedIdx.insert(getInsertIndex(IE2).value_or(*Idx1)).second;
4053 if ((IE2 != V && !IE2->hasOneUse()) || IsReusedIdx)
4054 IE2 = nullptr;
4055 else
4056 IE2 = dyn_cast_or_null<InsertElementInst>(GetBaseOperand(IE2));
4057 }
4058 } while (!IsReusedIdx && (IE1 || IE2));
4059 return false;
4060}
4061
4062std::optional<BoUpSLP::OrdersType>
4063BoUpSLP::getReorderingData(const TreeEntry &TE, bool TopToBottom) {
4064 // No need to reorder if need to shuffle reuses, still need to shuffle the
4065 // node.
4066 if (!TE.ReuseShuffleIndices.empty()) {
4067 // Check if reuse shuffle indices can be improved by reordering.
4068 // For this, check that reuse mask is "clustered", i.e. each scalar values
4069 // is used once in each submask of size <number_of_scalars>.
4070 // Example: 4 scalar values.
4071 // ReuseShuffleIndices mask: 0, 1, 2, 3, 3, 2, 0, 1 - clustered.
4072 // 0, 1, 2, 3, 3, 3, 1, 0 - not clustered, because
4073 // element 3 is used twice in the second submask.
4074 unsigned Sz = TE.Scalars.size();
4075 if (!ShuffleVectorInst::isOneUseSingleSourceMask(TE.ReuseShuffleIndices,
4076 Sz))
4077 return std::nullopt;
4078 unsigned VF = TE.getVectorFactor();
4079 // Try build correct order for extractelement instructions.
4080 SmallVector<int> ReusedMask(TE.ReuseShuffleIndices.begin(),
4081 TE.ReuseShuffleIndices.end());
4082 if (TE.getOpcode() == Instruction::ExtractElement && !TE.isAltShuffle() &&
4083 all_of(TE.Scalars, [Sz](Value *V) {
4084 std::optional<unsigned> Idx = getExtractIndex(cast<Instruction>(V));
4085 return Idx && *Idx < Sz;
4086 })) {
4087 SmallVector<int> ReorderMask(Sz, PoisonMaskElem);
4088 if (TE.ReorderIndices.empty())
4089 std::iota(ReorderMask.begin(), ReorderMask.end(), 0);
4090 else
4091 inversePermutation(TE.ReorderIndices, ReorderMask);
4092 for (unsigned I = 0; I < VF; ++I) {
4093 int &Idx = ReusedMask[I];
4094 if (Idx == PoisonMaskElem)
4095 continue;
4096 Value *V = TE.Scalars[ReorderMask[Idx]];
4097 std::optional<unsigned> EI = getExtractIndex(cast<Instruction>(V));
4098 Idx = std::distance(ReorderMask.begin(), find(ReorderMask, *EI));
4099 }
4100 }
4101 // Build the order of the VF size, need to reorder reuses shuffles, they are
4102 // always of VF size.
4103 OrdersType ResOrder(VF);
4104 std::iota(ResOrder.begin(), ResOrder.end(), 0);
4105 auto *It = ResOrder.begin();
4106 for (unsigned K = 0; K < VF; K += Sz) {
4107 OrdersType CurrentOrder(TE.ReorderIndices);
4108 SmallVector<int> SubMask{ArrayRef(ReusedMask).slice(K, Sz)};
4109 if (SubMask.front() == PoisonMaskElem)
4110 std::iota(SubMask.begin(), SubMask.end(), 0);
4111 reorderOrder(CurrentOrder, SubMask);
4112 transform(CurrentOrder, It, [K](unsigned Pos) { return Pos + K; });
4113 std::advance(It, Sz);
4114 }
4115 if (all_of(enumerate(ResOrder),
4116 [](const auto &Data) { return Data.index() == Data.value(); }))
4117 return std::nullopt; // No need to reorder.
4118 return std::move(ResOrder);
4119 }
4120 if (TE.State == TreeEntry::Vectorize &&
4121 (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
4122 (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
4123 !TE.isAltShuffle())
4124 return TE.ReorderIndices;
4125 if (TE.State == TreeEntry::Vectorize && TE.getOpcode() == Instruction::PHI) {
4126 auto PHICompare = [](llvm::Value *V1, llvm::Value *V2) {
4127 if (!V1->hasOneUse() || !V2->hasOneUse())
4128 return false;
4129 auto *FirstUserOfPhi1 = cast<Instruction>(*V1->user_begin());
4130 auto *FirstUserOfPhi2 = cast<Instruction>(*V2->user_begin());
4131 if (auto *IE1 = dyn_cast<InsertElementInst>(FirstUserOfPhi1))
4132 if (auto *IE2 = dyn_cast<InsertElementInst>(FirstUserOfPhi2)) {
4133 if (!areTwoInsertFromSameBuildVector(
4134 IE1, IE2,
4135 [](InsertElementInst *II) { return II->getOperand(0); }))
4136 return false;
4137 std::optional<unsigned> Idx1 = getInsertIndex(IE1);
4138 std::optional<unsigned> Idx2 = getInsertIndex(IE2);
4139 if (Idx1 == std::nullopt || Idx2 == std::nullopt)
4140 return false;
4141 return *Idx1 < *Idx2;
4142 }
4143 if (auto *EE1 = dyn_cast<ExtractElementInst>(FirstUserOfPhi1))
4144 if (auto *EE2 = dyn_cast<ExtractElementInst>(FirstUserOfPhi2)) {
4145 if (EE1->getOperand(0) != EE2->getOperand(0))
4146 return false;
4147 std::optional<unsigned> Idx1 = getExtractIndex(EE1);
4148 std::optional<unsigned> Idx2 = getExtractIndex(EE2);
4149 if (Idx1 == std::nullopt || Idx2 == std::nullopt)
4150 return false;
4151 return *Idx1 < *Idx2;
4152 }
4153 return false;
4154 };
4155 auto IsIdentityOrder = [](const OrdersType &Order) {
4156 for (unsigned Idx : seq<unsigned>(0, Order.size()))
4157 if (Idx != Order[Idx])
4158 return false;
4159 return true;
4160 };
4161 if (!TE.ReorderIndices.empty())
4162 return TE.ReorderIndices;
4163 DenseMap<Value *, unsigned> PhiToId;
4164 SmallVector<Value *, 4> Phis;
4165 OrdersType ResOrder(TE.Scalars.size());
4166 for (unsigned Id = 0, Sz = TE.Scalars.size(); Id < Sz; ++Id) {
4167 PhiToId[TE.Scalars[Id]] = Id;
4168 Phis.push_back(TE.Scalars[Id]);
4169 }
4170 llvm::stable_sort(Phis, PHICompare);
4171 for (unsigned Id = 0, Sz = Phis.size(); Id < Sz; ++Id)
4172 ResOrder[Id] = PhiToId[Phis[Id]];
4173 if (IsIdentityOrder(ResOrder))
4174 return std::nullopt; // No need to reorder.
4175 return std::move(ResOrder);
4176 }
4177 if (TE.State == TreeEntry::NeedToGather) {
4178 // TODO: add analysis of other gather nodes with extractelement
4179 // instructions and other values/instructions, not only undefs.
4180 if (((TE.getOpcode() == Instruction::ExtractElement &&
4181 !TE.isAltShuffle()) ||
4182 (all_of(TE.Scalars,
4183 [](Value *V) {
4184 return isa<UndefValue, ExtractElementInst>(V);
4185 }) &&
4186 any_of(TE.Scalars,
4187 [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
4188 all_of(TE.Scalars,
4189 [](Value *V) {
4190 auto *EE = dyn_cast<ExtractElementInst>(V);
4191 return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
4192 }) &&
4193 allSameType(TE.Scalars)) {
4194 // Check that gather of extractelements can be represented as
4195 // just a shuffle of a single vector.
4196 OrdersType CurrentOrder;
4197 bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
4198 if (Reuse || !CurrentOrder.empty()) {
4199 if (!CurrentOrder.empty())
4200 fixupOrderingIndices(CurrentOrder);
4201 return std::move(CurrentOrder);
4202 }
4203 }
4204 // If the gather node is <undef, v, .., poison> and
4205 // insertelement poison, v, 0 [+ permute]
4206 // is cheaper than
4207 // insertelement poison, v, n - try to reorder.
4208 // If rotating the whole graph, exclude the permute cost, the whole graph
4209 // might be transformed.
4210 int Sz = TE.Scalars.size();
4211 if (isSplat(TE.Scalars) && !allConstant(TE.Scalars) &&
4212 count_if(TE.Scalars, UndefValue::classof) == Sz - 1) {
4213 const auto *It =
4214 find_if(TE.Scalars, [](Value *V) { return !isConstant(V); });
4215 if (It == TE.Scalars.begin())
4216 return OrdersType();
4217 auto *Ty = FixedVectorType::get(TE.Scalars.front()->getType(), Sz);
4218 if (It != TE.Scalars.end()) {
4219 OrdersType Order(Sz, Sz);
4220 unsigned Idx = std::distance(TE.Scalars.begin(), It);
4221 Order[Idx] = 0;
4222 fixupOrderingIndices(Order);
4223 SmallVector<int> Mask;
4224 inversePermutation(Order, Mask);
4225 InstructionCost PermuteCost =
4226 TopToBottom
4227 ? 0
4228 : TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, Ty, Mask);
4229 InstructionCost InsertFirstCost = TTI->getVectorInstrCost(
4230 Instruction::InsertElement, Ty, TTI::TCK_RecipThroughput, 0,
4231 PoisonValue::get(Ty), *It);
4232 InstructionCost InsertIdxCost = TTI->getVectorInstrCost(
4233 Instruction::InsertElement, Ty, TTI::TCK_RecipThroughput, Idx,
4234 PoisonValue::get(Ty), *It);
4235 if (InsertFirstCost + PermuteCost < InsertIdxCost)
4236 return std::move(Order);
4237 }
4238 }
4239 if (std::optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
4240 return CurrentOrder;
4241 if (TE.Scalars.size() >= 4)
4242 if (std::optional<OrdersType> Order = findPartiallyOrderedLoads(TE))
4243 return Order;
4244 }
4245 return std::nullopt;
4246}
4247
4248/// Checks if the given mask is a "clustered" mask with the same clusters of
4249/// size \p Sz, which are not identity submasks.
4250static bool isRepeatedNonIdentityClusteredMask(ArrayRef<int> Mask,
4251 unsigned Sz) {
4252 ArrayRef<int> FirstCluster = Mask.slice(0, Sz);
4253 if (ShuffleVectorInst::isIdentityMask(FirstCluster))
4254 return false;
4255 for (unsigned I = Sz, E = Mask.size(); I < E; I += Sz) {
4256 ArrayRef<int> Cluster = Mask.slice(I, Sz);
4257 if (Cluster != FirstCluster)
4258 return false;
4259 }
4260 return true;
4261}
4262
4263void BoUpSLP::reorderNodeWithReuses(TreeEntry &TE, ArrayRef<int> Mask) const {
4264 // Reorder reuses mask.
4265 reorderReuses(TE.ReuseShuffleIndices, Mask);
4266 const unsigned Sz = TE.Scalars.size();
4267 // For vectorized and non-clustered reused no need to do anything else.
4268 if (TE.State != TreeEntry::NeedToGather ||
4269 !ShuffleVectorInst::isOneUseSingleSourceMask(TE.ReuseShuffleIndices,
4270 Sz) ||
4271 !isRepeatedNonIdentityClusteredMask(TE.ReuseShuffleIndices, Sz))
4272 return;
4273 SmallVector<int> NewMask;
4274 inversePermutation(TE.ReorderIndices, NewMask);
4275 addMask(NewMask, TE.ReuseShuffleIndices);
4276 // Clear reorder since it is going to be applied to the new mask.
4277 TE.ReorderIndices.clear();
4278 // Try to improve gathered nodes with clustered reuses, if possible.
4279 ArrayRef<int> Slice = ArrayRef(NewMask).slice(0, Sz);
4280 SmallVector<unsigned> NewOrder(Slice.begin(), Slice.end());
4281 inversePermutation(NewOrder, NewMask);
4282 reorderScalars(TE.Scalars, NewMask);
4283 // Fill the reuses mask with the identity submasks.
4284 for (auto *It = TE.ReuseShuffleIndices.begin(),
4285 *End = TE.ReuseShuffleIndices.end();
4286 It != End; std::advance(It, Sz))
4287 std::iota(It, std::next(It, Sz), 0);
4288}
4289
4290void BoUpSLP::reorderTopToBottom() {
4291 // Maps VF to the graph nodes.
4292 DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
4293 // ExtractElement gather nodes which can be vectorized and need to handle
4294 // their ordering.
4295 DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
4296
4297 // Phi nodes can have preferred ordering based on their result users
4298 DenseMap<const TreeEntry *, OrdersType> PhisToOrders;
4299
4300 // AltShuffles can also have a preferred ordering that leads to fewer
4301 // instructions, e.g., the addsub instruction in x86.
4302 DenseMap<const TreeEntry *, OrdersType> AltShufflesToOrders;
4303
4304 // Maps a TreeEntry to the reorder indices of external users.
4305 DenseMap<const TreeEntry *, SmallVector<OrdersType, 1>>
4306 ExternalUserReorderMap;
4307 // FIXME: Workaround for syntax error reported by MSVC buildbots.
4308 TargetTransformInfo &TTIRef = *TTI;
4309 // Find all reorderable nodes with the given VF.
4310 // Currently the are vectorized stores,loads,extracts + some gathering of
4311 // extracts.
4312 for_each(VectorizableTree, [this, &TTIRef, &VFToOrderedEntries,
4313 &GathersToOrders, &ExternalUserReorderMap,
4314 &AltShufflesToOrders, &PhisToOrders](
4315 const std::unique_ptr<TreeEntry> &TE) {
4316 // Look for external users that will probably be vectorized.
4317 SmallVector<OrdersType, 1> ExternalUserReorderIndices =
4318 findExternalStoreUsersReorderIndices(TE.get());
4319 if (!ExternalUserReorderIndices.empty()) {
4320 VFToOrderedEntries[TE->getVectorFactor()].insert(TE.get());
4321 ExternalUserReorderMap.try_emplace(TE.get(),
4322 std::move(ExternalUserReorderIndices));
4323 }
4324
4325 // Patterns like [fadd,fsub] can be combined into a single instruction in
4326 // x86. Reordering them into [fsub,fadd] blocks this pattern. So we need
4327 // to take into account their order when looking for the most used order.
4328 if (TE->isAltShuffle()) {
4329 VectorType *VecTy =
4330 FixedVectorType::get(TE->Scalars[0]->getType(), TE->Scalars.size());
4331 unsigned Opcode0 = TE->getOpcode();
4332 unsigned Opcode1 = TE->getAltOpcode();
4333 // The opcode mask selects between the two opcodes.
4334 SmallBitVector OpcodeMask(TE->Scalars.size(), false);
4335 for (unsigned Lane : seq<unsigned>(0, TE->Scalars.size()))
4336 if (cast<Instruction>(TE->Scalars[Lane])->getOpcode() == Opcode1)
4337 OpcodeMask.set(Lane);
4338 // If this pattern is supported by the target then we consider the order.
4339 if (TTIRef.isLegalAltInstr(VecTy, Opcode0, Opcode1, OpcodeMask)) {
4340 VFToOrderedEntries[TE->getVectorFactor()].insert(TE.get());
4341 AltShufflesToOrders.try_emplace(TE.get(), OrdersType());
4342 }
4343 // TODO: Check the reverse order too.
4344 }
4345
4346 if (std::optional<OrdersType> CurrentOrder =
4347 getReorderingData(*TE, /*TopToBottom=*/true)) {
4348 // Do not include ordering for nodes used in the alt opcode vectorization,
4349 // better to reorder them during bottom-to-top stage. If follow the order
4350 // here, it causes reordering of the whole graph though actually it is
4351 // profitable just to reorder the subgraph that starts from the alternate
4352 // opcode vectorization node. Such nodes already end-up with the shuffle
4353 // instruction and it is just enough to change this shuffle rather than
4354 // rotate the scalars for the whole graph.
4355 unsigned Cnt = 0;
4356 const TreeEntry *UserTE = TE.get();
4357 while (UserTE && Cnt < RecursionMaxDepth) {
4358 if (UserTE->UserTreeIndices.size() != 1)
4359 break;
4360 if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
4361 return EI.UserTE->State == TreeEntry::Vectorize &&
4362 EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
4363 }))
4364 return;
4365 UserTE = UserTE->UserTreeIndices.back().UserTE;
4366 ++Cnt;
4367 }
4368 VFToOrderedEntries[TE->getVectorFactor()].insert(TE.get());
4369 if (TE->State != TreeEntry::Vectorize || !TE->ReuseShuffleIndices.empty())
4370 GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
4371 if (TE->State == TreeEntry::Vectorize &&
4372 TE->getOpcode() == Instruction::PHI)
4373 PhisToOrders.try_emplace(TE.get(), *CurrentOrder);
4374 }
4375 });
4376
4377 // Reorder the graph nodes according to their vectorization factor.
4378 for (unsigned VF = VectorizableTree.front()->getVectorFactor(); VF > 1;
4379 VF /= 2) {
4380 auto It = VFToOrderedEntries.find(VF);
4381 if (It == VFToOrderedEntries.end())
4382 continue;
4383 // Try to find the most profitable order. We just are looking for the most
4384 // used order and reorder scalar elements in the nodes according to this
4385 // mostly used order.
4386 ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
4387 // All operands are reordered and used only in this node - propagate the
4388 // most used order to the user node.
4389 MapVector<OrdersType, unsigned,
4390 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
4391 OrdersUses;
4392 SmallPtrSet<const TreeEntry *, 4> VisitedOps;
4393 for (const TreeEntry *OpTE : OrderedEntries) {
4394 // No need to reorder this nodes, still need to extend and to use shuffle,
4395 // just need to merge reordering shuffle and the reuse shuffle.
4396 if (!OpTE->ReuseShuffleIndices.empty() && !GathersToOrders.count(OpTE))
4397 continue;
4398 // Count number of orders uses.
4399 const auto &Order = [OpTE, &GathersToOrders, &AltShufflesToOrders,
4400 &PhisToOrders]() -> const OrdersType & {
4401 if (OpTE->State == TreeEntry::NeedToGather ||
4402 !OpTE->ReuseShuffleIndices.empty()) {
4403 auto It = GathersToOrders.find(OpTE);
4404 if (It != GathersToOrders.end())
4405 return It->second;
4406 }
4407 if (OpTE->isAltShuffle()) {
4408 auto It = AltShufflesToOrders.find(OpTE);
4409 if (It != AltShufflesToOrders.end())
4410 return It->second;
4411 }
4412 if (OpTE->State == TreeEntry::Vectorize &&
4413 OpTE->getOpcode() == Instruction::PHI) {
4414 auto It = PhisToOrders.find(OpTE);
4415 if (It != PhisToOrders.end())
4416 return It->second;
4417 }
4418 return OpTE->ReorderIndices;
4419 }();
4420 // First consider the order of the external scalar users.
4421 auto It = ExternalUserReorderMap.find(OpTE);
4422 if (It != ExternalUserReorderMap.end()) {
4423 const auto &ExternalUserReorderIndices = It->second;
4424 // If the OpTE vector factor != number of scalars - use natural order,
4425 // it is an attempt to reorder node with reused scalars but with
4426 // external uses.
4427 if (OpTE->getVectorFactor() != OpTE->Scalars.size()) {
4428 OrdersUses.insert(std::make_pair(OrdersType(), 0)).first->second +=
4429 ExternalUserReorderIndices.size();
4430 } else {
4431 for (const OrdersType &ExtOrder : ExternalUserReorderIndices)
4432 ++OrdersUses.insert(std::make_pair(ExtOrder, 0)).first->second;
4433 }
4434 // No other useful reorder data in this entry.
4435 if (Order.empty())
4436 continue;
4437 }
4438 // Stores actually store the mask, not the order, need to invert.
4439 if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
4440 OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
4441 SmallVector<int> Mask;
4442 inversePermutation(Order, Mask);
4443 unsigned E = Order.size();
4444 OrdersType CurrentOrder(E, E);
4445 transform(Mask, CurrentOrder.begin(), [E](int Idx) {
4446 return Idx == PoisonMaskElem ? E : static_cast<unsigned>(Idx);
4447 });
4448 fixupOrderingIndices(CurrentOrder);
4449 ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
4450 } else {
4451 ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
4452 }
4453 }
4454 // Set order of the user node.
4455 if (OrdersUses.empty())
4456 continue;
4457 // Choose the most used order.
4458 ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
4459 unsigned Cnt = OrdersUses.front().second;
4460 for (const auto &Pair : drop_begin(OrdersUses)) {
4461 if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
4462 BestOrder = Pair.first;
4463 Cnt = Pair.second;
4464 }
4465 }
4466 // Set order of the user node.
4467 if (BestOrder.empty())
4468 continue;
4469 SmallVector<int> Mask;
4470 inversePermutation(BestOrder, Mask);
4471 SmallVector<int> MaskOrder(BestOrder.size(), PoisonMaskElem);
4472 unsigned E = BestOrder.size();
4473 transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
4474 return I < E ? static_cast<int>(I) : PoisonMaskElem;
4475 });
4476 // Do an actual reordering, if profitable.
4477 for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
4478 // Just do the reordering for the nodes with the given VF.
4479 if (TE->Scalars.size() != VF) {
4480 if (TE->ReuseShuffleIndices.size() == VF) {
4481 // Need to reorder the reuses masks of the operands with smaller VF to
4482 // be able to find the match between the graph nodes and scalar
4483 // operands of the given node during vectorization/cost estimation.
4484 assert(all_of(TE->UserTreeIndices,(static_cast <bool> (all_of(TE->UserTreeIndices, [VF
, &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars
.size() == VF || EI.UserTE->Scalars.size() == TE->Scalars
.size(); }) && "All users must be of VF size.") ? void
(0) : __assert_fail ("all_of(TE->UserTreeIndices, [VF, &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars.size() == VF || EI.UserTE->Scalars.size() == TE->Scalars.size(); }) && \"All users must be of VF size.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4490, __extension__
__PRETTY_FUNCTION__))
4485 [VF, &TE](const EdgeInfo &EI) {(static_cast <bool> (all_of(TE->UserTreeIndices, [VF
, &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars
.size() == VF || EI.UserTE->Scalars.size() == TE->Scalars
.size(); }) && "All users must be of VF size.") ? void
(0) : __assert_fail ("all_of(TE->UserTreeIndices, [VF, &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars.size() == VF || EI.UserTE->Scalars.size() == TE->Scalars.size(); }) && \"All users must be of VF size.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4490, __extension__
__PRETTY_FUNCTION__))
4486 return EI.UserTE->Scalars.size() == VF ||(static_cast <bool> (all_of(TE->UserTreeIndices, [VF
, &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars
.size() == VF || EI.UserTE->Scalars.size() == TE->Scalars
.size(); }) && "All users must be of VF size.") ? void
(0) : __assert_fail ("all_of(TE->UserTreeIndices, [VF, &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars.size() == VF || EI.UserTE->Scalars.size() == TE->Scalars.size(); }) && \"All users must be of VF size.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4490, __extension__
__PRETTY_FUNCTION__))
4487 EI.UserTE->Scalars.size() ==(static_cast <bool> (all_of(TE->UserTreeIndices, [VF
, &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars
.size() == VF || EI.UserTE->Scalars.size() == TE->Scalars
.size(); }) && "All users must be of VF size.") ? void
(0) : __assert_fail ("all_of(TE->UserTreeIndices, [VF, &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars.size() == VF || EI.UserTE->Scalars.size() == TE->Scalars.size(); }) && \"All users must be of VF size.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4490, __extension__
__PRETTY_FUNCTION__))
4488 TE->Scalars.size();(static_cast <bool> (all_of(TE->UserTreeIndices, [VF
, &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars
.size() == VF || EI.UserTE->Scalars.size() == TE->Scalars
.size(); }) && "All users must be of VF size.") ? void
(0) : __assert_fail ("all_of(TE->UserTreeIndices, [VF, &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars.size() == VF || EI.UserTE->Scalars.size() == TE->Scalars.size(); }) && \"All users must be of VF size.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4490, __extension__
__PRETTY_FUNCTION__))
4489 }) &&(static_cast <bool> (all_of(TE->UserTreeIndices, [VF
, &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars
.size() == VF || EI.UserTE->Scalars.size() == TE->Scalars
.size(); }) && "All users must be of VF size.") ? void
(0) : __assert_fail ("all_of(TE->UserTreeIndices, [VF, &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars.size() == VF || EI.UserTE->Scalars.size() == TE->Scalars.size(); }) && \"All users must be of VF size.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4490, __extension__
__PRETTY_FUNCTION__))
4490 "All users must be of VF size.")(static_cast <bool> (all_of(TE->UserTreeIndices, [VF
, &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars
.size() == VF || EI.UserTE->Scalars.size() == TE->Scalars
.size(); }) && "All users must be of VF size.") ? void
(0) : __assert_fail ("all_of(TE->UserTreeIndices, [VF, &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars.size() == VF || EI.UserTE->Scalars.size() == TE->Scalars.size(); }) && \"All users must be of VF size.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4490, __extension__
__PRETTY_FUNCTION__))
;
4491 // Update ordering of the operands with the smaller VF than the given
4492 // one.
4493 reorderNodeWithReuses(*TE, Mask);
4494 }
4495 continue;
4496 }
4497 if (TE->State == TreeEntry::Vectorize &&
4498 isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
4499 InsertElementInst>(TE->getMainOp()) &&
4500 !TE->isAltShuffle()) {
4501 // Build correct orders for extract{element,value}, loads and
4502 // stores.
4503 reorderOrder(TE->ReorderIndices, Mask);
4504 if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
4505 TE->reorderOperands(Mask);
4506 } else {
4507 // Reorder the node and its operands.
4508 TE->reorderOperands(Mask);
4509 assert(TE->ReorderIndices.empty() &&(static_cast <bool> (TE->ReorderIndices.empty() &&
"Expected empty reorder sequence.") ? void (0) : __assert_fail
("TE->ReorderIndices.empty() && \"Expected empty reorder sequence.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4510, __extension__
__PRETTY_FUNCTION__))
4510 "Expected empty reorder sequence.")(static_cast <bool> (TE->ReorderIndices.empty() &&
"Expected empty reorder sequence.") ? void (0) : __assert_fail
("TE->ReorderIndices.empty() && \"Expected empty reorder sequence.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4510, __extension__
__PRETTY_FUNCTION__))
;
4511 reorderScalars(TE->Scalars, Mask);
4512 }
4513 if (!TE->ReuseShuffleIndices.empty()) {
4514 // Apply reversed order to keep the original ordering of the reused
4515 // elements to avoid extra reorder indices shuffling.
4516 OrdersType CurrentOrder;
4517 reorderOrder(CurrentOrder, MaskOrder);
4518 SmallVector<int> NewReuses;
4519 inversePermutation(CurrentOrder, NewReuses);
4520 addMask(NewReuses, TE->ReuseShuffleIndices);
4521 TE->ReuseShuffleIndices.swap(NewReuses);
4522 }
4523 }
4524 }
4525}
4526
4527bool BoUpSLP::canReorderOperands(
4528 TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
4529 ArrayRef<TreeEntry *> ReorderableGathers,
4530 SmallVectorImpl<TreeEntry *> &GatherOps) {
4531 for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
4532 if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
4533 return OpData.first == I &&
4534 OpData.second->State == TreeEntry::Vectorize;
4535 }))
4536 continue;
4537 if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
4538 // Do not reorder if operand node is used by many user nodes.
4539 if (any_of(TE->UserTreeIndices,
4540 [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
4541 return false;
4542 // Add the node to the list of the ordered nodes with the identity
4543 // order.
4544 Edges.emplace_back(I, TE);
4545 // Add ScatterVectorize nodes to the list of operands, where just
4546 // reordering of the scalars is required. Similar to the gathers, so
4547 // simply add to the list of gathered ops.
4548 // If there are reused scalars, process this node as a regular vectorize
4549 // node, just reorder reuses mask.
4550 if (TE->State != TreeEntry::Vectorize && TE->ReuseShuffleIndices.empty())
4551 GatherOps.push_back(TE);
4552 continue;
4553 }
4554 TreeEntry *Gather = nullptr;
4555 if (count_if(ReorderableGathers,
4556 [&Gather, UserTE, I](TreeEntry *TE) {
4557 assert(TE->State != TreeEntry::Vectorize &&(static_cast <bool> (TE->State != TreeEntry::Vectorize
&& "Only non-vectorized nodes are expected.") ? void
(0) : __assert_fail ("TE->State != TreeEntry::Vectorize && \"Only non-vectorized nodes are expected.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4558, __extension__
__PRETTY_FUNCTION__))
4558 "Only non-vectorized nodes are expected.")(static_cast <bool> (TE->State != TreeEntry::Vectorize
&& "Only non-vectorized nodes are expected.") ? void
(0) : __assert_fail ("TE->State != TreeEntry::Vectorize && \"Only non-vectorized nodes are expected.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4558, __extension__
__PRETTY_FUNCTION__))
;
4559 if (any_of(TE->UserTreeIndices,
4560 [UserTE, I](const EdgeInfo &EI) {
4561 return EI.UserTE == UserTE && EI.EdgeIdx == I;
4562 })) {
4563 assert(TE->isSame(UserTE->getOperand(I)) &&(static_cast <bool> (TE->isSame(UserTE->getOperand
(I)) && "Operand entry does not match operands.") ? void
(0) : __assert_fail ("TE->isSame(UserTE->getOperand(I)) && \"Operand entry does not match operands.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4564, __extension__
__PRETTY_FUNCTION__))
4564 "Operand entry does not match operands.")(static_cast <bool> (TE->isSame(UserTE->getOperand
(I)) && "Operand entry does not match operands.") ? void
(0) : __assert_fail ("TE->isSame(UserTE->getOperand(I)) && \"Operand entry does not match operands.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4564, __extension__
__PRETTY_FUNCTION__))
;
4565 Gather = TE;
4566 return true;
4567 }
4568 return false;
4569 }) > 1 &&
4570 !allConstant(UserTE->getOperand(I)))
4571 return false;
4572 if (Gather)
4573 GatherOps.push_back(Gather);
4574 }
4575 return true;
4576}
4577
4578void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
4579 SetVector<TreeEntry *> OrderedEntries;
4580 DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
4581 // Find all reorderable leaf nodes with the given VF.
4582 // Currently the are vectorized loads,extracts without alternate operands +
4583 // some gathering of extracts.
4584 SmallVector<TreeEntry *> NonVectorized;
4585 for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
4586 &NonVectorized](
4587 const std::unique_ptr<TreeEntry> &TE) {
4588 if (TE->State != TreeEntry::Vectorize)
4589 NonVectorized.push_back(TE.get());
4590 if (std::optional<OrdersType> CurrentOrder =
4591 getReorderingData(*TE, /*TopToBottom=*/false)) {
4592 OrderedEntries.insert(TE.get());
4593 if (TE->State != TreeEntry::Vectorize || !TE->ReuseShuffleIndices.empty())
4594 GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
4595 }
4596 });
4597
4598 // 1. Propagate order to the graph nodes, which use only reordered nodes.
4599 // I.e., if the node has operands, that are reordered, try to make at least
4600 // one operand order in the natural order and reorder others + reorder the
4601 // user node itself.
4602 SmallPtrSet<const TreeEntry *, 4> Visited;
4603 while (!OrderedEntries.empty()) {
4604 // 1. Filter out only reordered nodes.
4605 // 2. If the entry has multiple uses - skip it and jump to the next node.
4606 DenseMap<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
4607 SmallVector<TreeEntry *> Filtered;
4608 for (TreeEntry *TE : OrderedEntries) {
4609 if (!(TE->State == TreeEntry::Vectorize ||
4610 (TE->State == TreeEntry::NeedToGather &&
4611 GathersToOrders.count(TE))) ||
4612 TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
4613 !all_of(drop_begin(TE->UserTreeIndices),
4614 [TE](const EdgeInfo &EI) {
4615 return EI.UserTE == TE->UserTreeIndices.front().UserTE;
4616 }) ||
4617 !Visited.insert(TE).second) {
4618 Filtered.push_back(TE);
4619 continue;
4620 }
4621 // Build a map between user nodes and their operands order to speedup
4622 // search. The graph currently does not provide this dependency directly.
4623 for (EdgeInfo &EI : TE->UserTreeIndices) {
4624 TreeEntry *UserTE = EI.UserTE;
4625 auto It = Users.find(UserTE);
4626 if (It == Users.end())
4627 It = Users.insert({UserTE, {}}).first;
4628 It->second.emplace_back(EI.EdgeIdx, TE);
4629 }
4630 }
4631 // Erase filtered entries.
4632 for_each(Filtered,
4633 [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
4634 SmallVector<
4635 std::pair<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>>>
4636 UsersVec(Users.begin(), Users.end());
4637 sort(UsersVec, [](const auto &Data1, const auto &Data2) {
4638 return Data1.first->Idx > Data2.first->Idx;
4639 });
4640 for (auto &Data : UsersVec) {
4641 // Check that operands are used only in the User node.
4642 SmallVector<TreeEntry *> GatherOps;
4643 if (!canReorderOperands(Data.first, Data.second, NonVectorized,
4644 GatherOps)) {
4645 for_each(Data.second,
4646 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
4647 OrderedEntries.remove(Op.second);
4648 });
4649 continue;
4650 }
4651 // All operands are reordered and used only in this node - propagate the
4652 // most used order to the user node.
4653 MapVector<OrdersType, unsigned,
4654 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
4655 OrdersUses;
4656 // Do the analysis for each tree entry only once, otherwise the order of
4657 // the same node my be considered several times, though might be not
4658 // profitable.
4659 SmallPtrSet<const TreeEntry *, 4> VisitedOps;
4660 SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
4661 for (const auto &Op : Data.second) {
4662 TreeEntry *OpTE = Op.second;
4663 if (!VisitedOps.insert(OpTE).second)
4664 continue;
4665 if (!OpTE->ReuseShuffleIndices.empty() && !GathersToOrders.count(OpTE))
4666 continue;
4667 const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
4668 if (OpTE->State == TreeEntry::NeedToGather ||
4669 !OpTE->ReuseShuffleIndices.empty())
4670 return GathersToOrders.find(OpTE)->second;
4671 return OpTE->ReorderIndices;
4672 }();
4673 unsigned NumOps = count_if(
4674 Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
4675 return P.second == OpTE;
4676 });
4677 // Stores actually store the mask, not the order, need to invert.
4678 if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
4679 OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
4680 SmallVector<int> Mask;
4681 inversePermutation(Order, Mask);
4682 unsigned E = Order.size();
4683 OrdersType CurrentOrder(E, E);
4684 transform(Mask, CurrentOrder.begin(), [E](int Idx) {
4685 return Idx == PoisonMaskElem ? E : static_cast<unsigned>(Idx);
4686 });
4687 fixupOrderingIndices(CurrentOrder);
4688 OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
4689 NumOps;
4690 } else {
4691 OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
4692 }
4693 auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
4694 const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
4695 const TreeEntry *TE) {
4696 if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
4697 (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
4698 (IgnoreReorder && TE->Idx == 0))
4699 return true;
4700 if (TE->State == TreeEntry::NeedToGather) {
4701 auto It = GathersToOrders.find(TE);
4702 if (It != GathersToOrders.end())
4703 return !It->second.empty();
4704 return true;
4705 }
4706 return false;
4707 };
4708 for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
4709 TreeEntry *UserTE = EI.UserTE;
4710 if (!VisitedUsers.insert(UserTE).second)
4711 continue;
4712 // May reorder user node if it requires reordering, has reused
4713 // scalars, is an alternate op vectorize node or its op nodes require
4714 // reordering.
4715 if (AllowsReordering(UserTE))
4716 continue;
4717 // Check if users allow reordering.
4718 // Currently look up just 1 level of operands to avoid increase of
4719 // the compile time.
4720 // Profitable to reorder if definitely more operands allow
4721 // reordering rather than those with natural order.
4722 ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
4723 if (static_cast<unsigned>(count_if(
4724 Ops, [UserTE, &AllowsReordering](
4725 const std::pair<unsigned, TreeEntry *> &Op) {
4726 return AllowsReordering(Op.second) &&
4727 all_of(Op.second->UserTreeIndices,
4728 [UserTE](const EdgeInfo &EI) {
4729 return EI.UserTE == UserTE;
4730 });
4731 })) <= Ops.size() / 2)
4732 ++Res.first->second;
4733 }
4734 }
4735 // If no orders - skip current nodes and jump to the next one, if any.
4736 if (OrdersUses.empty()) {
4737 for_each(Data.second,
4738 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
4739 OrderedEntries.remove(Op.second);
4740 });
4741 continue;
4742 }
4743 // Choose the best order.
4744 ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
4745 unsigned Cnt = OrdersUses.front().second;
4746 for (const auto &Pair : drop_begin(OrdersUses)) {
4747 if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
4748 BestOrder = Pair.first;
4749 Cnt = Pair.second;
4750 }
4751 }
4752 // Set order of the user node (reordering of operands and user nodes).
4753 if (BestOrder.empty()) {
4754 for_each(Data.second,
4755 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
4756 OrderedEntries.remove(Op.second);
4757 });
4758 continue;
4759 }
4760 // Erase operands from OrderedEntries list and adjust their orders.
4761 VisitedOps.clear();
4762 SmallVector<int> Mask;
4763 inversePermutation(BestOrder, Mask);
4764 SmallVector<int> MaskOrder(BestOrder.size(), PoisonMaskElem);
4765 unsigned E = BestOrder.size();
4766 transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
4767 return I < E ? static_cast<int>(I) : PoisonMaskElem;
4768 });
4769 for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
4770 TreeEntry *TE = Op.second;
4771 OrderedEntries.remove(TE);
4772 if (!VisitedOps.insert(TE).second)
4773 continue;
4774 if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
4775 reorderNodeWithReuses(*TE, Mask);
4776 continue;
4777 }
4778 // Gathers are processed separately.
4779 if (TE->State != TreeEntry::Vectorize)
4780 continue;
4781 assert((BestOrder.size() == TE->ReorderIndices.size() ||(static_cast <bool> ((BestOrder.size() == TE->ReorderIndices
.size() || TE->ReorderIndices.empty()) && "Non-matching sizes of user/operand entries."
) ? void (0) : __assert_fail ("(BestOrder.size() == TE->ReorderIndices.size() || TE->ReorderIndices.empty()) && \"Non-matching sizes of user/operand entries.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4783, __extension__
__PRETTY_FUNCTION__))
4782 TE->ReorderIndices.empty()) &&(static_cast <bool> ((BestOrder.size() == TE->ReorderIndices
.size() || TE->ReorderIndices.empty()) && "Non-matching sizes of user/operand entries."
) ? void (0) : __assert_fail ("(BestOrder.size() == TE->ReorderIndices.size() || TE->ReorderIndices.empty()) && \"Non-matching sizes of user/operand entries.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4783, __extension__
__PRETTY_FUNCTION__))
4783 "Non-matching sizes of user/operand entries.")(static_cast <bool> ((BestOrder.size() == TE->ReorderIndices
.size() || TE->ReorderIndices.empty()) && "Non-matching sizes of user/operand entries."
) ? void (0) : __assert_fail ("(BestOrder.size() == TE->ReorderIndices.size() || TE->ReorderIndices.empty()) && \"Non-matching sizes of user/operand entries.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4783, __extension__
__PRETTY_FUNCTION__))
;
4784 reorderOrder(TE->ReorderIndices, Mask);
4785 if (IgnoreReorder && TE == VectorizableTree.front().get())
4786 IgnoreReorder = false;
4787 }
4788 // For gathers just need to reorder its scalars.
4789 for (TreeEntry *Gather : GatherOps) {
4790 assert(Gather->ReorderIndices.empty() &&(static_cast <bool> (Gather->ReorderIndices.empty() &&
"Unexpected reordering of gathers.") ? void (0) : __assert_fail
("Gather->ReorderIndices.empty() && \"Unexpected reordering of gathers.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4791, __extension__
__PRETTY_FUNCTION__))
4791 "Unexpected reordering of gathers.")(static_cast <bool> (Gather->ReorderIndices.empty() &&
"Unexpected reordering of gathers.") ? void (0) : __assert_fail
("Gather->ReorderIndices.empty() && \"Unexpected reordering of gathers.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4791, __extension__
__PRETTY_FUNCTION__))
;
4792 if (!Gather->ReuseShuffleIndices.empty()) {
4793 // Just reorder reuses indices.
4794 reorderReuses(Gather->ReuseShuffleIndices, Mask);
4795 continue;
4796 }
4797 reorderScalars(Gather->Scalars, Mask);
4798 OrderedEntries.remove(Gather);
4799 }
4800 // Reorder operands of the user node and set the ordering for the user
4801 // node itself.
4802 if (Data.first->State != TreeEntry::Vectorize ||
4803 !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
4804 Data.first->getMainOp()) ||
4805 Data.first->isAltShuffle())
4806 Data.first->reorderOperands(Mask);
4807 if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
4808 Data.first->isAltShuffle()) {
4809 reorderScalars(Data.first->Scalars, Mask);
4810 reorderOrder(Data.first->ReorderIndices, MaskOrder);
4811 if (Data.first->ReuseShuffleIndices.empty() &&
4812 !Data.first->ReorderIndices.empty() &&
4813 !Data.first->isAltShuffle()) {
4814 // Insert user node to the list to try to sink reordering deeper in
4815 // the graph.
4816 OrderedEntries.insert(Data.first);
4817 }
4818 } else {
4819 reorderOrder(Data.first->ReorderIndices, Mask);
4820 }
4821 }
4822 }
4823 // If the reordering is unnecessary, just remove the reorder.
4824 if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
4825 VectorizableTree.front()->ReuseShuffleIndices.empty())
4826 VectorizableTree.front()->ReorderIndices.clear();
4827}
4828
4829void BoUpSLP::buildExternalUses(
4830 const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
4831 // Collect the values that we need to extract from the tree.
4832 for (auto &TEPtr : VectorizableTree) {
4833 TreeEntry *Entry = TEPtr.get();
4834
4835 // No need to handle users of gathered values.
4836 if (Entry->State == TreeEntry::NeedToGather)
4837 continue;
4838
4839 // For each lane:
4840 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
4841 Value *Scalar = Entry->Scalars[Lane];
4842 int FoundLane = Entry->findLaneForValue(Scalar);
4843
4844 // Check if the scalar is externally used as an extra arg.
4845 auto ExtI = ExternallyUsedValues.find(Scalar);
4846 if (ExtI != ExternallyUsedValues.end()) {
4847 LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Need to extract: Extra arg from lane "
<< Lane << " from " << *Scalar << ".\n"
; } } while (false)
4848 << Lane << " from " << *Scalar << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Need to extract: Extra arg from lane "
<< Lane << " from " << *Scalar << ".\n"
; } } while (false)
;
4849 ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
4850 }
4851 for (User *U : Scalar->users()) {
4852 LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Checking user:" << *U <<
".\n"; } } while (false)
;
4853
4854 Instruction *UserInst = dyn_cast<Instruction>(U);
4855 if (!UserInst)
4856 continue;
4857
4858 if (isDeleted(UserInst))
4859 continue;
4860
4861 // Skip in-tree scalars that become vectors
4862 if (TreeEntry *UseEntry = getTreeEntry(U)) {
4863 Value *UseScalar = UseEntry->Scalars[0];
4864 // Some in-tree scalars will remain as scalar in vectorized
4865 // instructions. If that is the case, the one in Lane 0 will
4866 // be used.
4867 if (UseScalar != U ||
4868 UseEntry->State == TreeEntry::ScatterVectorize ||
4869 !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
4870 LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *Udo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: \tInternal user will be removed:"
<< *U << ".\n"; } } while (false)
4871 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: \tInternal user will be removed:"
<< *U << ".\n"; } } while (false)
;
4872 assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state")(static_cast <bool> (UseEntry->State != TreeEntry::NeedToGather
&& "Bad state") ? void (0) : __assert_fail ("UseEntry->State != TreeEntry::NeedToGather && \"Bad state\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4872, __extension__
__PRETTY_FUNCTION__))
;
4873 continue;
4874 }
4875 }
4876
4877 // Ignore users in the user ignore list.
4878 if (UserIgnoreList && UserIgnoreList->contains(UserInst))
4879 continue;
4880
4881 LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Need to extract:" << *
U << " from lane " << Lane << " from " <<
*Scalar << ".\n"; } } while (false)
4882 << Lane << " from " << *Scalar << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Need to extract:" << *
U << " from lane " << Lane << " from " <<
*Scalar << ".\n"; } } while (false)
;
4883 ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
4884 }
4885 }
4886 }
4887}
4888
4889DenseMap<Value *, SmallVector<StoreInst *, 4>>
4890BoUpSLP::collectUserStores(const BoUpSLP::TreeEntry *TE) const {
4891 DenseMap<Value *, SmallVector<StoreInst *, 4>> PtrToStoresMap;
4892 for (unsigned Lane : seq<unsigned>(0, TE->Scalars.size())) {
4893 Value *V = TE->Scalars[Lane];
4894 // To save compilation time we don't visit if we have too many users.
4895 static constexpr unsigned UsersLimit = 4;
4896 if (V->hasNUsesOrMore(UsersLimit))
4897 break;
4898
4899 // Collect stores per pointer object.
4900 for (User *U : V->users()) {
4901 auto *SI = dyn_cast<StoreInst>(U);
4902 if (SI == nullptr || !SI->isSimple() ||
4903 !isValidElementType(SI->getValueOperand()->getType()))
4904 continue;
4905 // Skip entry if already
4906 if (getTreeEntry(U))
4907 continue;
4908
4909 Value *Ptr = getUnderlyingObject(SI->getPointerOperand());
4910 auto &StoresVec = PtrToStoresMap[Ptr];
4911 // For now just keep one store per pointer object per lane.
4912 // TODO: Extend this to support multiple stores per pointer per lane
4913 if (StoresVec.size() > Lane)
4914 continue;
4915 // Skip if in different BBs.
4916 if (!StoresVec.empty() &&
4917 SI->getParent() != StoresVec.back()->getParent())
4918 continue;
4919 // Make sure that the stores are of the same type.
4920 if (!StoresVec.empty() &&
4921 SI->getValueOperand()->getType() !=
4922 StoresVec.back()->getValueOperand()->getType())
4923 continue;
4924 StoresVec.push_back(SI);
4925 }
4926 }
4927 return PtrToStoresMap;
4928}
4929
4930bool BoUpSLP::canFormVector(const SmallVector<StoreInst *, 4> &StoresVec,
4931 OrdersType &ReorderIndices) const {
4932 // We check whether the stores in StoreVec can form a vector by sorting them
4933 // and checking whether they are consecutive.
4934
4935 // To avoid calling getPointersDiff() while sorting we create a vector of
4936 // pairs {store, offset from first} and sort this instead.
4937 SmallVector<std::pair<StoreInst *, int>, 4> StoreOffsetVec(StoresVec.size());
4938 StoreInst *S0 = StoresVec[0];
4939 StoreOffsetVec[0] = {S0, 0};
4940 Type *S0Ty = S0->getValueOperand()->getType();
4941 Value *S0Ptr = S0->getPointerOperand();
4942 for (unsigned Idx : seq<unsigned>(1, StoresVec.size())) {
4943 StoreInst *SI = StoresVec[Idx];
4944 std::optional<int> Diff =
4945 getPointersDiff(S0Ty, S0Ptr, SI->getValueOperand()->getType(),
4946 SI->getPointerOperand(), *DL, *SE,
4947 /*StrictCheck=*/true);
4948 // We failed to compare the pointers so just abandon this StoresVec.
4949 if (!Diff)
4950 return false;
4951 StoreOffsetVec[Idx] = {StoresVec[Idx], *Diff};
4952 }
4953
4954 // Sort the vector based on the pointers. We create a copy because we may
4955 // need the original later for calculating the reorder (shuffle) indices.
4956 stable_sort(StoreOffsetVec, [](const std::pair<StoreInst *, int> &Pair1,
4957 const std::pair<StoreInst *, int> &Pair2) {
4958 int Offset1 = Pair1.second;
4959 int Offset2 = Pair2.second;
4960 return Offset1 < Offset2;
4961 });
4962
4963 // Check if the stores are consecutive by checking if their difference is 1.
4964 for (unsigned Idx : seq<unsigned>(1, StoreOffsetVec.size()))
4965 if (StoreOffsetVec[Idx].second != StoreOffsetVec[Idx-1].second + 1)
4966 return false;
4967
4968 // Calculate the shuffle indices according to their offset against the sorted
4969 // StoreOffsetVec.
4970 ReorderIndices.reserve(StoresVec.size());
4971 for (StoreInst *SI : StoresVec) {
4972 unsigned Idx = find_if(StoreOffsetVec,
4973 [SI](const std::pair<StoreInst *, int> &Pair) {
4974 return Pair.first == SI;
4975 }) -
4976 StoreOffsetVec.begin();
4977 ReorderIndices.push_back(Idx);
4978 }
4979 // Identity order (e.g., {0,1,2,3}) is modeled as an empty OrdersType in
4980 // reorderTopToBottom() and reorderBottomToTop(), so we are following the
4981 // same convention here.
4982 auto IsIdentityOrder = [](const OrdersType &Order) {
4983 for (unsigned Idx : seq<unsigned>(0, Order.size()))
4984 if (Idx != Order[Idx])
4985 return false;
4986 return true;
4987 };
4988 if (IsIdentityOrder(ReorderIndices))
4989 ReorderIndices.clear();
4990
4991 return true;
4992}
4993
4994#ifndef NDEBUG
4995LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) static void dumpOrder(const BoUpSLP::OrdersType &Order) {
4996 for (unsigned Idx : Order)
4997 dbgs() << Idx << ", ";
4998 dbgs() << "\n";
4999}
5000#endif
5001
5002SmallVector<BoUpSLP::OrdersType, 1>
5003BoUpSLP::findExternalStoreUsersReorderIndices(TreeEntry *TE) const {
5004 unsigned NumLanes = TE->Scalars.size();
5005
5006 DenseMap<Value *, SmallVector<StoreInst *, 4>> PtrToStoresMap =
5007 collectUserStores(TE);
5008
5009 // Holds the reorder indices for each candidate store vector that is a user of
5010 // the current TreeEntry.
5011 SmallVector<OrdersType, 1> ExternalReorderIndices;
5012
5013 // Now inspect the stores collected per pointer and look for vectorization
5014 // candidates. For each candidate calculate the reorder index vector and push
5015 // it into `ExternalReorderIndices`
5016 for (const auto &Pair : PtrToStoresMap) {
5017 auto &StoresVec = Pair.second;
5018 // If we have fewer than NumLanes stores, then we can't form a vector.
5019 if (StoresVec.size() != NumLanes)
5020 continue;
5021
5022 // If the stores are not consecutive then abandon this StoresVec.
5023 OrdersType ReorderIndices;
5024 if (!canFormVector(StoresVec, ReorderIndices))
5025 continue;
5026
5027 // We now know that the scalars in StoresVec can form a vector instruction,
5028 // so set the reorder indices.
5029 ExternalReorderIndices.push_back(ReorderIndices);
5030 }
5031 return ExternalReorderIndices;
5032}
5033
5034void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
5035 const SmallDenseSet<Value *> &UserIgnoreLst) {
5036 deleteTree();
5037 UserIgnoreList = &UserIgnoreLst;
5038 if (!allSameType(Roots))
5039 return;
5040 buildTree_rec(Roots, 0, EdgeInfo());
5041}
5042
5043void BoUpSLP::buildTree(ArrayRef<Value *> Roots) {
5044 deleteTree();
5045 if (!allSameType(Roots))
5046 return;
5047 buildTree_rec(Roots, 0, EdgeInfo());
5048}
5049
5050/// \return true if the specified list of values has only one instruction that
5051/// requires scheduling, false otherwise.
5052#ifndef NDEBUG
5053static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
5054 Value *NeedsScheduling = nullptr;
5055 for (Value *V : VL) {
5056 if (doesNotNeedToBeScheduled(V))
5057 continue;
5058 if (!NeedsScheduling) {
5059 NeedsScheduling = V;
5060 continue;
5061 }
5062 return false;
5063 }
5064 return NeedsScheduling;
5065}
5066#endif
5067
5068/// Generates key/subkey pair for the given value to provide effective sorting
5069/// of the values and better detection of the vectorizable values sequences. The
5070/// keys/subkeys can be used for better sorting of the values themselves (keys)
5071/// and in values subgroups (subkeys).
5072static std::pair<size_t, size_t> generateKeySubkey(
5073 Value *V, const TargetLibraryInfo *TLI,
5074 function_ref<hash_code(size_t, LoadInst *)> LoadsSubkeyGenerator,
5075 bool AllowAlternate) {
5076 hash_code Key = hash_value(V->getValueID() + 2);
5077 hash_code SubKey = hash_value(0);
5078 // Sort the loads by the distance between the pointers.
5079 if (auto *LI = dyn_cast<LoadInst>(V)) {
5080 Key = hash_combine(LI->getType(), hash_value(Instruction::Load), Key);
5081 if (LI->isSimple())
5082 SubKey = hash_value(LoadsSubkeyGenerator(Key, LI));
5083 else
5084 Key = SubKey = hash_value(LI);
5085 } else if (isVectorLikeInstWithConstOps(V)) {
5086 // Sort extracts by the vector operands.
5087 if (isa<ExtractElementInst, UndefValue>(V))
5088 Key = hash_value(Value::UndefValueVal + 1);
5089 if (auto *EI = dyn_cast<ExtractElementInst>(V)) {
5090 if (!isUndefVector(EI->getVectorOperand()).all() &&
5091 !isa<UndefValue>(EI->getIndexOperand()))
5092 SubKey = hash_value(EI->getVectorOperand());
5093 }
5094 } else if (auto *I = dyn_cast<Instruction>(V)) {
5095 // Sort other instructions just by the opcodes except for CMPInst.
5096 // For CMP also sort by the predicate kind.
5097 if ((isa<BinaryOperator, CastInst>(I)) &&
5098 isValidForAlternation(I->getOpcode())) {
5099 if (AllowAlternate)
5100 Key = hash_value(isa<BinaryOperator>(I) ? 1 : 0);
5101 else
5102 Key = hash_combine(hash_value(I->getOpcode()), Key);
5103 SubKey = hash_combine(
5104 hash_value(I->getOpcode()), hash_value(I->getType()),
5105 hash_value(isa<BinaryOperator>(I)
5106 ? I->getType()
5107 : cast<CastInst>(I)->getOperand(0)->getType()));
5108 // For casts, look through the only operand to improve compile time.
5109 if (isa<CastInst>(I)) {
5110 std::pair<size_t, size_t> OpVals =
5111 generateKeySubkey(I->getOperand(0), TLI, LoadsSubkeyGenerator,
5112 /*AllowAlternate=*/true);
5113 Key = hash_combine(OpVals.first, Key);
5114 SubKey = hash_combine(OpVals.first, SubKey);
5115 }
5116 } else if (auto *CI = dyn_cast<CmpInst>(I)) {
5117 CmpInst::Predicate Pred = CI->getPredicate();
5118 if (CI->isCommutative())
5119 Pred = std::min(Pred, CmpInst::getInversePredicate(Pred));
5120 CmpInst::Predicate SwapPred = CmpInst::getSwappedPredicate(Pred);
5121 SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Pred),
5122 hash_value(SwapPred),
5123 hash_value(CI->getOperand(0)->getType()));
5124 } else if (auto *Call = dyn_cast<CallInst>(I)) {
5125 Intrinsic::ID ID = getVectorIntrinsicIDForCall(Call, TLI);
5126 if (isTriviallyVectorizable(ID)) {
5127 SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(ID));
5128 } else if (!VFDatabase(*Call).getMappings(*Call).empty()) {
5129 SubKey = hash_combine(hash_value(I->getOpcode()),
5130 hash_value(Call->getCalledFunction()));
5131 } else {
5132 Key = hash_combine(hash_value(Call), Key);
5133 SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Call));
5134 }
5135 for (const CallBase::BundleOpInfo &Op : Call->bundle_op_infos())
5136 SubKey = hash_combine(hash_value(Op.Begin), hash_value(Op.End),
5137 hash_value(Op.Tag), SubKey);
5138 } else if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) {
5139 if (Gep->getNumOperands() == 2 && isa<ConstantInt>(Gep->getOperand(1)))
5140 SubKey = hash_value(Gep->getPointerOperand());
5141 else
5142 SubKey = hash_value(Gep);
5143 } else if (BinaryOperator::isIntDivRem(I->getOpcode()) &&
5144 !isa<ConstantInt>(I->getOperand(1))) {
5145 // Do not try to vectorize instructions with potentially high cost.
5146 SubKey = hash_value(I);
5147 } else {
5148 SubKey = hash_value(I->getOpcode());
5149 }
5150 Key = hash_combine(hash_value(I->getParent()), Key);
5151 }
5152 return std::make_pair(Key, SubKey);
5153}
5154
5155/// Checks if the specified instruction \p I is an alternate operation for
5156/// the given \p MainOp and \p AltOp instructions.
5157static bool isAlternateInstruction(const Instruction *I,
5158 const Instruction *MainOp,
5159 const Instruction *AltOp,
5160 const TargetLibraryInfo &TLI);
5161
5162void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
5163 const EdgeInfo &UserTreeIdx) {
5164 assert((allConstant(VL) || allSameType(VL)) && "Invalid types!")(static_cast <bool> ((allConstant(VL) || allSameType(VL
)) && "Invalid types!") ? void (0) : __assert_fail ("(allConstant(VL) || allSameType(VL)) && \"Invalid types!\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5164, __extension__
__PRETTY_FUNCTION__))
;
5165
5166 SmallVector<int> ReuseShuffleIndicies;
5167 SmallVector<Value *> UniqueValues;
5168 auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
5169 &UserTreeIdx,
5170 this](const InstructionsState &S) {
5171 // Check that every instruction appears once in this bundle.
5172 DenseMap<Value *, unsigned> UniquePositions(VL.size());
5173 for (Value *V : VL) {
5174 if (isConstant(V)) {
5175 ReuseShuffleIndicies.emplace_back(
5176 isa<UndefValue>(V) ? PoisonMaskElem : UniqueValues.size());
5177 UniqueValues.emplace_back(V);
5178 continue;
5179 }
5180 auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
5181 ReuseShuffleIndicies.emplace_back(Res.first->second);
5182 if (Res.second)
5183 UniqueValues.emplace_back(V);
5184 }
5185 size_t NumUniqueScalarValues = UniqueValues.size();
5186 if (NumUniqueScalarValues == VL.size()) {
5187 ReuseShuffleIndicies.clear();
5188 } else {
5189 LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Shuffle for reused scalars.\n"
; } } while (false)
;
5190 if (NumUniqueScalarValues <= 1 ||
5191 (UniquePositions.size() == 1 && all_of(UniqueValues,
5192 [](Value *V) {
5193 return isa<UndefValue>(V) ||
5194 !isConstant(V);
5195 })) ||
5196 !llvm::has_single_bit<uint32_t>(NumUniqueScalarValues)) {
5197 LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Scalar used twice in bundle.\n"
; } } while (false)
;
5198 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx);
5199 return false;
5200 }
5201 VL = UniqueValues;
5202 }
5203 return true;
5204 };
5205
5206 InstructionsState S = getSameOpcode(VL, *TLI);
5207
5208 // Gather if we hit the RecursionMaxDepth, unless this is a load (or z/sext of
5209 // a load), in which case peek through to include it in the tree, without
5210 // ballooning over-budget.
5211 if (Depth >= RecursionMaxDepth &&
5212 !(S.MainOp && isa<Instruction>(S.MainOp) && S.MainOp == S.AltOp &&
5213 VL.size() >= 4 &&
5214 (match(S.MainOp, m_Load(m_Value())) || all_of(VL, [&S](const Value *I) {
5215 return match(I,
5216 m_OneUse(m_ZExtOrSExt(m_OneUse(m_Load(m_Value()))))) &&
5217 cast<Instruction>(I)->getOpcode() ==
5218 cast<Instruction>(S.MainOp)->getOpcode();
5219 })))) {
5220 LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering due to max recursion depth.\n"
; } } while (false)
;
5221 if (TryToFindDuplicates(S))
5222 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
5223 ReuseShuffleIndicies);
5224 return;
5225 }
5226
5227 // Don't handle scalable vectors
5228 if (S.getOpcode() == Instruction::ExtractElement &&
5229 isa<ScalableVectorType>(
5230 cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
5231 LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering due to scalable vector type.\n"
; } } while (false)
;
5232 if (TryToFindDuplicates(S))
5233 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
5234 ReuseShuffleIndicies);
5235 return;
5236 }
5237
5238 // Don't handle vectors.
5239 if (S.OpValue->getType()->isVectorTy() &&
5240 !isa<InsertElementInst>(S.OpValue)) {
5241 LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering due to vector type.\n"
; } } while (false)
;
5242 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx);
5243 return;
5244 }
5245
5246 if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
5247 if (SI->getValueOperand()->getType()->isVectorTy()) {
5248 LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering due to store vector type.\n"
; } } while (false)
;
5249 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx);
5250 return;
5251 }
5252
5253 // If all of the operands are identical or constant we have a simple solution.
5254 // If we deal with insert/extract instructions, they all must have constant
5255 // indices, otherwise we should gather them, not try to vectorize.
5256 // If alternate op node with 2 elements with gathered operands - do not
5257 // vectorize.
5258 auto &&NotProfitableForVectorization = [&S, this,
5259 Depth](ArrayRef<Value *> VL) {
5260 if (!S.getOpcode() || !S.isAltShuffle() || VL.size() > 2)
5261 return false;
5262 if (VectorizableTree.size() < MinTreeSize)
5263 return false;
5264 if (Depth >= RecursionMaxDepth - 1)
5265 return true;
5266 // Check if all operands are extracts, part of vector node or can build a
5267 // regular vectorize node.
5268 SmallVector<unsigned, 2> InstsCount(VL.size(), 0);
5269 for (Value *V : VL) {
5270 auto *I = cast<Instruction>(V);
5271 InstsCount.push_back(count_if(I->operand_values(), [](Value *Op) {
5272 return isa<Instruction>(Op) || isVectorLikeInstWithConstOps(Op);
5273 }));
5274 }
5275 bool IsCommutative = isCommutative(S.MainOp) || isCommutative(S.AltOp);
5276 if ((IsCommutative &&
5277 std::accumulate(InstsCount.begin(), InstsCount.end(), 0) < 2) ||
5278 (!IsCommutative &&
5279 all_of(InstsCount, [](unsigned ICnt) { return ICnt < 2; })))
5280 return true;
5281 assert(VL.size() == 2 && "Expected only 2 alternate op instructions.")(static_cast <bool> (VL.size() == 2 && "Expected only 2 alternate op instructions."
) ? void (0) : __assert_fail ("VL.size() == 2 && \"Expected only 2 alternate op instructions.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5281, __extension__
__PRETTY_FUNCTION__))
;
5282 SmallVector<SmallVector<std::pair<Value *, Value *>>> Candidates;
5283 auto *I1 = cast<Instruction>(VL.front());
5284 auto *I2 = cast<Instruction>(VL.back());
5285 for (int Op = 0, E = S.MainOp->getNumOperands(); Op < E; ++Op)
5286 Candidates.emplace_back().emplace_back(I1->getOperand(Op),
5287 I2->getOperand(Op));
5288 if (static_cast<unsigned>(count_if(
5289 Candidates, [this](ArrayRef<std::pair<Value *, Value *>> Cand) {
5290 return findBestRootPair(Cand, LookAheadHeuristics::ScoreSplat);
5291 })) >= S.MainOp->getNumOperands() / 2)
5292 return false;
5293 if (S.MainOp->getNumOperands() > 2)
5294 return true;
5295 if (IsCommutative) {
5296 // Check permuted operands.
5297 Candidates.clear();
5298 for (int Op = 0, E = S.MainOp->getNumOperands(); Op < E; ++Op)
5299 Candidates.emplace_back().emplace_back(I1->getOperand(Op),
5300 I2->getOperand((Op + 1) % E));
5301 if (any_of(
5302 Candidates, [this](ArrayRef<std::pair<Value *, Value *>> Cand) {
5303 return findBestRootPair(Cand, LookAheadHeuristics::ScoreSplat);
5304 }))
5305 return false;
5306 }
5307 return true;
5308 };
5309 SmallVector<unsigned> SortedIndices;
5310 BasicBlock *BB = nullptr;
5311 bool IsScatterVectorizeUserTE =
5312 UserTreeIdx.UserTE &&
5313 UserTreeIdx.UserTE->State == TreeEntry::ScatterVectorize;
5314 bool AreAllSameInsts =
5315 (S.getOpcode() && allSameBlock(VL)) ||
5316 (S.OpValue->getType()->isPointerTy() && IsScatterVectorizeUserTE &&
5317 VL.size() > 2 &&
5318 all_of(VL,
5319 [&BB](Value *V) {
5320 auto *I = dyn_cast<GetElementPtrInst>(V);
5321 if (!I)
5322 return doesNotNeedToBeScheduled(V);
5323 if (!BB)
5324 BB = I->getParent();
5325 return BB == I->getParent() && I->getNumOperands() == 2;
5326 }) &&
5327 BB &&
5328 sortPtrAccesses(VL, UserTreeIdx.UserTE->getMainOp()->getType(), *DL, *SE,
5329 SortedIndices));
5330 if (!AreAllSameInsts || allConstant(VL) || isSplat(VL) ||
5331 (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(
5332 S.OpValue) &&
5333 !all_of(VL, isVectorLikeInstWithConstOps)) ||
5334 NotProfitableForVectorization(VL)) {
5335 LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O, small shuffle. \n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering due to C,S,B,O, small shuffle. \n"
; } } while (false)
;
5336 if (TryToFindDuplicates(S))
5337 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
5338 ReuseShuffleIndicies);
5339 return;
5340 }
5341
5342 // We now know that this is a vector of instructions of the same type from
5343 // the same block.
5344
5345 // Don't vectorize ephemeral values.
5346 if (!EphValues.empty()) {
5347 for (Value *V : VL) {
5348 if (EphValues.count(V)) {
5349 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *Vdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: The instruction (" << *
V << ") is ephemeral.\n"; } } while (false)
5350 << ") is ephemeral.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: The instruction (" << *
V << ") is ephemeral.\n"; } } while (false)
;
5351 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx);
5352 return;
5353 }
5354 }
5355 }
5356
5357 // Check if this is a duplicate of another entry.
5358 if (TreeEntry *E = getTreeEntry(S.OpValue)) {
5359 LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: \tChecking bundle: " <<
*S.OpValue << ".\n"; } } while (false)
;
5360 if (!E->isSame(VL)) {
5361 LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering due to partial overlap.\n"
; } } while (false)
;
5362 if (TryToFindDuplicates(S))
5363 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
5364 ReuseShuffleIndicies);
5365 return;
5366 }
5367 // Record the reuse of the tree node. FIXME, currently this is only used to
5368 // properly draw the graph rather than for the actual vectorization.
5369 E->UserTreeIndices.push_back(UserTreeIdx);
5370 LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValuedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Perfect diamond merge at " <<
*S.OpValue << ".\n"; } } while (false)
5371 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Perfect diamond merge at " <<
*S.OpValue << ".\n"; } } while (false)
;
5372 return;
5373 }
5374
5375 // Check that none of the instructions in the bundle are already in the tree.
5376 for (Value *V : VL) {
5377 if (!IsScatterVectorizeUserTE && !isa<Instruction>(V))
5378 continue;
5379 if (getTreeEntry(V)) {
5380 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *Vdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: The instruction (" << *
V << ") is already in tree.\n"; } } while (false)
5381 << ") is already in tree.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: The instruction (" << *
V << ") is already in tree.\n"; } } while (false)
;
5382 if (TryToFindDuplicates(S))
5383 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
5384 ReuseShuffleIndicies);
5385 return;
5386 }
5387 }
5388
5389 // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
5390 if (UserIgnoreList && !UserIgnoreList->empty()) {
5391 for (Value *V : VL) {
5392 if (UserIgnoreList && UserIgnoreList->contains(V)) {
5393 LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering due to gathered scalar.\n"
; } } while (false)
;
5394 if (TryToFindDuplicates(S))
5395 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
5396 ReuseShuffleIndicies);
5397 return;
5398 }
5399 }
5400 }
5401
5402 // Special processing for sorted pointers for ScatterVectorize node with
5403 // constant indeces only.
5404 if (AreAllSameInsts && UserTreeIdx.UserTE &&
5405 UserTreeIdx.UserTE->State == TreeEntry::ScatterVectorize &&
5406 !(S.getOpcode() && allSameBlock(VL))) {
5407 assert(S.OpValue->getType()->isPointerTy() &&(static_cast <bool> (S.OpValue->getType()->isPointerTy
() && count_if(VL, [](Value *V) { return isa<GetElementPtrInst
>(V); }) >= 2 && "Expected pointers only.") ? void
(0) : __assert_fail ("S.OpValue->getType()->isPointerTy() && count_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); }) >= 2 && \"Expected pointers only.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5410, __extension__
__PRETTY_FUNCTION__))
5408 count_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); }) >=(static_cast <bool> (S.OpValue->getType()->isPointerTy
() && count_if(VL, [](Value *V) { return isa<GetElementPtrInst
>(V); }) >= 2 && "Expected pointers only.") ? void
(0) : __assert_fail ("S.OpValue->getType()->isPointerTy() && count_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); }) >= 2 && \"Expected pointers only.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5410, __extension__
__PRETTY_FUNCTION__))
5409 2 &&(static_cast <bool> (S.OpValue->getType()->isPointerTy
() && count_if(VL, [](Value *V) { return isa<GetElementPtrInst
>(V); }) >= 2 && "Expected pointers only.") ? void
(0) : __assert_fail ("S.OpValue->getType()->isPointerTy() && count_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); }) >= 2 && \"Expected pointers only.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5410, __extension__
__PRETTY_FUNCTION__))
5410 "Expected pointers only.")(static_cast <bool> (S.OpValue->getType()->isPointerTy
() && count_if(VL, [](Value *V) { return isa<GetElementPtrInst
>(V); }) >= 2 && "Expected pointers only.") ? void
(0) : __assert_fail ("S.OpValue->getType()->isPointerTy() && count_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); }) >= 2 && \"Expected pointers only.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5410, __extension__
__PRETTY_FUNCTION__))
;
5411 // Reset S to make it GetElementPtr kind of node.
5412 const auto *It = find_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); });
5413 assert(It != VL.end() && "Expected at least one GEP.")(static_cast <bool> (It != VL.end() && "Expected at least one GEP."
) ? void (0) : __assert_fail ("It != VL.end() && \"Expected at least one GEP.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5413, __extension__
__PRETTY_FUNCTION__))
;
5414 S = getSameOpcode(*It, *TLI);
5415 }
5416
5417 // Check that all of the users of the scalars that we want to vectorize are
5418 // schedulable.
5419 auto *VL0 = cast<Instruction>(S.OpValue);
5420 BB = VL0->getParent();
5421
5422 if (!DT->isReachableFromEntry(BB)) {
5423 // Don't go into unreachable blocks. They may contain instructions with
5424 // dependency cycles which confuse the final scheduling.
5425 LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: bundle in unreachable block.\n"
; } } while (false)
;
5426 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx);
5427 return;
5428 }
5429
5430 // Don't go into catchswitch blocks, which can happen with PHIs.
5431 // Such blocks can only have PHIs and the catchswitch. There is no
5432 // place to insert a shuffle if we need to, so just avoid that issue.
5433 if (isa<CatchSwitchInst>(BB->getTerminator())) {
5434 LLVM_DEBUG(dbgs() << "SLP: bundle in catchswitch block.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: bundle in catchswitch block.\n"
; } } while (false)
;
5435 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx);
5436 return;
5437 }
5438
5439 // Check that every instruction appears once in this bundle.
5440 if (!TryToFindDuplicates(S))
5441 return;
5442
5443 auto &BSRef = BlocksSchedules[BB];
5444 if (!BSRef)
5445 BSRef = std::make_unique<BlockScheduling>(BB);
5446
5447 BlockScheduling &BS = *BSRef;
5448
5449 std::optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
5450#ifdef EXPENSIVE_CHECKS
5451 // Make sure we didn't break any internal invariants
5452 BS.verify();
5453#endif
5454 if (!Bundle) {
5455 LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: We are not able to schedule this bundle!\n"
; } } while (false)
;
5456 assert((!BS.getScheduleData(VL0) ||(static_cast <bool> ((!BS.getScheduleData(VL0) || !BS.getScheduleData
(VL0)->isPartOfBundle()) && "tryScheduleBundle should cancelScheduling on failure"
) ? void (0) : __assert_fail ("(!BS.getScheduleData(VL0) || !BS.getScheduleData(VL0)->isPartOfBundle()) && \"tryScheduleBundle should cancelScheduling on failure\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5458, __extension__
__PRETTY_FUNCTION__))
5457 !BS.getScheduleData(VL0)->isPartOfBundle()) &&(static_cast <bool> ((!BS.getScheduleData(VL0) || !BS.getScheduleData
(VL0)->isPartOfBundle()) && "tryScheduleBundle should cancelScheduling on failure"
) ? void (0) : __assert_fail ("(!BS.getScheduleData(VL0) || !BS.getScheduleData(VL0)->isPartOfBundle()) && \"tryScheduleBundle should cancelScheduling on failure\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5458, __extension__
__PRETTY_FUNCTION__))
5458 "tryScheduleBundle should cancelScheduling on failure")(static_cast <bool> ((!BS.getScheduleData(VL0) || !BS.getScheduleData
(VL0)->isPartOfBundle()) && "tryScheduleBundle should cancelScheduling on failure"
) ? void (0) : __assert_fail ("(!BS.getScheduleData(VL0) || !BS.getScheduleData(VL0)->isPartOfBundle()) && \"tryScheduleBundle should cancelScheduling on failure\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5458, __extension__
__PRETTY_FUNCTION__))
;
5459 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
5460 ReuseShuffleIndicies);
5461 return;
5462 }
5463 LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: We are able to schedule this bundle.\n"
; } } while (false)
;
5464
5465 unsigned ShuffleOrOp = S.isAltShuffle() ?
5466 (unsigned) Instruction::ShuffleVector : S.getOpcode();
5467 switch (ShuffleOrOp) {
5468 case Instruction::PHI: {
5469 auto *PH = cast<PHINode>(VL0);
5470
5471 // Check for terminator values (e.g. invoke).
5472 for (Value *V : VL)
5473 for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
5474 Instruction *Term = dyn_cast<Instruction>(Incoming);
5475 if (Term && Term->isTerminator()) {
5476 LLVM_DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Need to swizzle PHINodes (terminator use).\n"
; } } while (false)
5477 << "SLP: Need to swizzle PHINodes (terminator use).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Need to swizzle PHINodes (terminator use).\n"
; } } while (false)
;
5478 BS.cancelScheduling(VL, VL0);
5479 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
5480 ReuseShuffleIndicies);
5481 return;
5482 }
5483 }
5484
5485 TreeEntry *TE =
5486 newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
5487 LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: added a vector of PHINodes.\n"
; } } while (false)
;
5488
5489 // Keeps the reordered operands to avoid code duplication.
5490 SmallVector<ValueList, 2> OperandsVec;
5491 for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
5492 if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
5493 ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
5494 TE->setOperand(I, Operands);
5495 OperandsVec.push_back(Operands);
5496 continue;
5497 }
5498 ValueList Operands;
5499 // Prepare the operand vector.
5500 for (Value *V : VL)
5501 Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
5502 PH->getIncomingBlock(I)));
5503 TE->setOperand(I, Operands);
5504 OperandsVec.push_back(Operands);
5505 }
5506 for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
5507 buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
5508 return;
5509 }
5510 case Instruction::ExtractValue:
5511 case Instruction::ExtractElement: {
5512 OrdersType CurrentOrder;
5513 bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
5514 if (Reuse) {
5515 LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Reusing or shuffling extract sequence.\n"
; } } while (false)
;
5516 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5517 ReuseShuffleIndicies);
5518 // This is a special case, as it does not gather, but at the same time
5519 // we are not extending buildTree_rec() towards the operands.
5520 ValueList Op0;
5521 Op0.assign(VL.size(), VL0->getOperand(0));
5522 VectorizableTree.back()->setOperand(0, Op0);
5523 return;
5524 }
5525 if (!CurrentOrder.empty()) {
5526 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { { dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
"with order"; for (unsigned Idx : CurrentOrder) dbgs() <<
" " << Idx; dbgs() << "\n"; }; } } while (false)
5527 dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { { dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
"with order"; for (unsigned Idx : CurrentOrder) dbgs() <<
" " << Idx; dbgs() << "\n"; }; } } while (false)
5528 "with order";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { { dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
"with order"; for (unsigned Idx : CurrentOrder) dbgs() <<
" " << Idx; dbgs() << "\n"; }; } } while (false)
5529 for (unsigned Idx : CurrentOrder)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { { dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
"with order"; for (unsigned Idx : CurrentOrder) dbgs() <<
" " << Idx; dbgs() << "\n"; }; } } while (false)
5530 dbgs() << " " << Idx;do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { { dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
"with order"; for (unsigned Idx : CurrentOrder) dbgs() <<
" " << Idx; dbgs() << "\n"; }; } } while (false)
5531 dbgs() << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { { dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
"with order"; for (unsigned Idx : CurrentOrder) dbgs() <<
" " << Idx; dbgs() << "\n"; }; } } while (false)
5532 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { { dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
"with order"; for (unsigned Idx : CurrentOrder) dbgs() <<
" " << Idx; dbgs() << "\n"; }; } } while (false)
;
5533 fixupOrderingIndices(CurrentOrder);
5534 // Insert new order with initial value 0, if it does not exist,
5535 // otherwise return the iterator to the existing one.
5536 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5537 ReuseShuffleIndicies, CurrentOrder);
5538 // This is a special case, as it does not gather, but at the same time
5539 // we are not extending buildTree_rec() towards the operands.
5540 ValueList Op0;
5541 Op0.assign(VL.size(), VL0->getOperand(0));
5542 VectorizableTree.back()->setOperand(0, Op0);
5543 return;
5544 }
5545 LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gather extract sequence.\n";
} } while (false)
;
5546 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
5547 ReuseShuffleIndicies);
5548 BS.cancelScheduling(VL, VL0);
5549 return;
5550 }
5551 case Instruction::InsertElement: {
5552 assert(ReuseShuffleIndicies.empty() && "All inserts should be unique")(static_cast <bool> (ReuseShuffleIndicies.empty() &&
"All inserts should be unique") ? void (0) : __assert_fail (
"ReuseShuffleIndicies.empty() && \"All inserts should be unique\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5552, __extension__
__PRETTY_FUNCTION__))
;
5553
5554 // Check that we have a buildvector and not a shuffle of 2 or more
5555 // different vectors.
5556 ValueSet SourceVectors;
5557 for (Value *V : VL) {
5558 SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
5559 assert(getInsertIndex(V) != std::nullopt &&(static_cast <bool> (getInsertIndex(V) != std::nullopt &&
"Non-constant or undef index?") ? void (0) : __assert_fail (
"getInsertIndex(V) != std::nullopt && \"Non-constant or undef index?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5560, __extension__
__PRETTY_FUNCTION__))
5560 "Non-constant or undef index?")(static_cast <bool> (getInsertIndex(V) != std::nullopt &&
"Non-constant or undef index?") ? void (0) : __assert_fail (
"getInsertIndex(V) != std::nullopt && \"Non-constant or undef index?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5560, __extension__
__PRETTY_FUNCTION__))
;
5561 }
5562
5563 if (count_if(VL, [&SourceVectors](Value *V) {
5564 return !SourceVectors.contains(V);
5565 }) >= 2) {
5566 // Found 2nd source vector - cancel.
5567 LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gather of insertelement vectors with "
"different source vectors.\n"; } } while (false)
5568 "different source vectors.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gather of insertelement vectors with "
"different source vectors.\n"; } } while (false)
;
5569 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx);
5570 BS.cancelScheduling(VL, VL0);
5571 return;
5572 }
5573
5574 auto OrdCompare = [](const std::pair<int, int> &P1,
5575 const std::pair<int, int> &P2) {
5576 return P1.first > P2.first;
5577 };
5578 PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
5579 decltype(OrdCompare)>
5580 Indices(OrdCompare);
5581 for (int I = 0, E = VL.size(); I < E; ++I) {
5582 unsigned Idx = *getInsertIndex(VL[I]);
5583 Indices.emplace(Idx, I);
5584 }
5585 OrdersType CurrentOrder(VL.size(), VL.size());
5586 bool IsIdentity = true;
5587 for (int I = 0, E = VL.size(); I < E; ++I) {
5588 CurrentOrder[Indices.top().second] = I;
5589 IsIdentity &= Indices.top().second == I;
5590 Indices.pop();
5591 }
5592 if (IsIdentity)
5593 CurrentOrder.clear();
5594 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5595 std::nullopt, CurrentOrder);
5596 LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: added inserts bundle.\n"; } }
while (false)
;
5597
5598 constexpr int NumOps = 2;
5599 ValueList VectorOperands[NumOps];
5600 for (int I = 0; I < NumOps; ++I) {
5601 for (Value *V : VL)
5602 VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
5603
5604 TE->setOperand(I, VectorOperands[I]);
5605 }
5606 buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
5607 return;
5608 }
5609 case Instruction::Load: {
5610 // Check that a vectorized load would load the same memory as a scalar
5611 // load. For example, we don't want to vectorize loads that are smaller
5612 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
5613 // treats loading/storing it as an i8 struct. If we vectorize loads/stores
5614 // from such a struct, we read/write packed bits disagreeing with the
5615 // unvectorized version.
5616 SmallVector<Value *> PointerOps;
5617 OrdersType CurrentOrder;
5618 TreeEntry *TE = nullptr;
5619 switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, *LI, *TLI,
5620 CurrentOrder, PointerOps)) {
5621 case LoadsState::Vectorize:
5622 if (CurrentOrder.empty()) {
5623 // Original loads are consecutive and does not require reordering.
5624 TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5625 ReuseShuffleIndicies);
5626 LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: added a vector of loads.\n";
} } while (false)
;
5627 } else {
5628 fixupOrderingIndices(CurrentOrder);
5629 // Need to reorder.
5630 TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5631 ReuseShuffleIndicies, CurrentOrder);
5632 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: added a vector of jumbled loads.\n"
; } } while (false)
;
5633 }
5634 TE->setOperandsInOrder();
5635 break;
5636 case LoadsState::ScatterVectorize:
5637 // Vectorizing non-consecutive loads with `llvm.masked.gather`.
5638 TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
5639 UserTreeIdx, ReuseShuffleIndicies);
5640 TE->setOperandsInOrder();
5641 buildTree_rec(PointerOps, Depth + 1, {TE, 0});
5642 LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: added a vector of non-consecutive loads.\n"
; } } while (false)
;
5643 break;
5644 case LoadsState::Gather:
5645 BS.cancelScheduling(VL, VL0);
5646 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
5647 ReuseShuffleIndicies);
5648#ifndef NDEBUG
5649 Type *ScalarTy = VL0->getType();
5650 if (DL->getTypeSizeInBits(ScalarTy) !=
5651 DL->getTypeAllocSizeInBits(ScalarTy))
5652 LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering loads of non-packed type.\n"
; } } while (false)
;
5653 else if (any_of(VL, [](Value *V) {
5654 return !cast<LoadInst>(V)->isSimple();
5655 }))
5656 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering non-simple loads.\n"
; } } while (false)
;
5657 else
5658 LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering non-consecutive loads.\n"
; } } while (false)
;
5659#endif // NDEBUG
5660 break;
5661 }
5662 return;
5663 }
5664 case Instruction::ZExt:
5665 case Instruction::SExt:
5666 case Instruction::FPToUI:
5667 case Instruction::FPToSI:
5668 case Instruction::FPExt:
5669 case Instruction::PtrToInt:
5670 case Instruction::IntToPtr:
5671 case Instruction::SIToFP:
5672 case Instruction::UIToFP:
5673 case Instruction::Trunc:
5674 case Instruction::FPTrunc:
5675 case Instruction::BitCast: {
5676 Type *SrcTy = VL0->getOperand(0)->getType();
5677 for (Value *V : VL) {
5678 Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
5679 if (Ty != SrcTy || !isValidElementType(Ty)) {
5680 BS.cancelScheduling(VL, VL0);
5681 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
5682 ReuseShuffleIndicies);
5683 LLVM_DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering casts with different src types.\n"
; } } while (false)
5684 << "SLP: Gathering casts with different src types.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering casts with different src types.\n"
; } } while (false)
;
5685 return;
5686 }
5687 }
5688 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5689 ReuseShuffleIndicies);
5690 LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: added a vector of casts.\n";
} } while (false)
;
5691
5692 TE->setOperandsInOrder();
5693 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
5694 ValueList Operands;
5695 // Prepare the operand vector.
5696 for (Value *V : VL)
5697 Operands.push_back(cast<Instruction>(V)->getOperand(i));
5698
5699 buildTree_rec(Operands, Depth + 1, {TE, i});
5700 }
5701 return;
5702 }
5703 case Instruction::ICmp:
5704 case Instruction::FCmp: {
5705 // Check that all of the compares have the same predicate.
5706 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
5707 CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
5708 Type *ComparedTy = VL0->getOperand(0)->getType();
5709 for (Value *V : VL) {
5710 CmpInst *Cmp = cast<CmpInst>(V);
5711 if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
5712 Cmp->getOperand(0)->getType() != ComparedTy) {
5713 BS.cancelScheduling(VL, VL0);
5714 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
5715 ReuseShuffleIndicies);
5716 LLVM_DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering cmp with different predicate.\n"
; } } while (false)
5717 << "SLP: Gathering cmp with different predicate.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering cmp with different predicate.\n"
; } } while (false)
;
5718 return;
5719 }
5720 }
5721
5722 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5723 ReuseShuffleIndicies);
5724 LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: added a vector of compares.\n"
; } } while (false)
;
5725
5726 ValueList Left, Right;
5727 if (cast<CmpInst>(VL0)->isCommutative()) {
5728 // Commutative predicate - collect + sort operands of the instructions
5729 // so that each side is more likely to have the same opcode.
5730 assert(P0 == SwapP0 && "Commutative Predicate mismatch")(static_cast <bool> (P0 == SwapP0 && "Commutative Predicate mismatch"
) ? void (0) : __assert_fail ("P0 == SwapP0 && \"Commutative Predicate mismatch\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5730, __extension__
__PRETTY_FUNCTION__))
;
5731 reorderInputsAccordingToOpcode(VL, Left, Right, *TLI, *DL, *SE, *this);
5732 } else {
5733 // Collect operands - commute if it uses the swapped predicate.
5734 for (Value *V : VL) {
5735 auto *Cmp = cast<CmpInst>(V);
5736 Value *LHS = Cmp->getOperand(0);
5737 Value *RHS = Cmp->getOperand(1);
5738 if (Cmp->getPredicate() != P0)
5739 std::swap(LHS, RHS);
5740 Left.push_back(LHS);
5741 Right.push_back(RHS);
5742 }
5743 }
5744 TE->setOperand(0, Left);
5745 TE->setOperand(1, Right);
5746 buildTree_rec(Left, Depth + 1, {TE, 0});
5747 buildTree_rec(Right, Depth + 1, {TE, 1});
5748 return;
5749 }
5750 case Instruction::Select:
5751 case Instruction::FNeg:
5752 case Instruction::Add:
5753 case Instruction::FAdd:
5754 case Instruction::Sub:
5755 case Instruction::FSub:
5756 case Instruction::Mul:
5757 case Instruction::FMul:
5758 case Instruction::UDiv:
5759 case Instruction::SDiv:
5760 case Instruction::FDiv:
5761 case Instruction::URem:
5762 case Instruction::SRem:
5763 case Instruction::FRem:
5764 case Instruction::Shl:
5765 case Instruction::LShr:
5766 case Instruction::AShr:
5767 case Instruction::And:
5768 case Instruction::Or:
5769 case Instruction::Xor: {
5770 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5771 ReuseShuffleIndicies);
5772 LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: added a vector of un/bin op.\n"
; } } while (false)
;
5773
5774 // Sort operands of the instructions so that each side is more likely to
5775 // have the same opcode.
5776 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
5777 ValueList Left, Right;
5778 reorderInputsAccordingToOpcode(VL, Left, Right, *TLI, *DL, *SE, *this);
5779 TE->setOperand(0, Left);
5780 TE->setOperand(1, Right);
5781 buildTree_rec(Left, Depth + 1, {TE, 0});
5782 buildTree_rec(Right, Depth + 1, {TE, 1});
5783 return;
5784 }
5785
5786 TE->setOperandsInOrder();
5787 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
5788 ValueList Operands;
5789 // Prepare the operand vector.
5790 for (Value *V : VL)
5791 Operands.push_back(cast<Instruction>(V)->getOperand(i));
5792
5793 buildTree_rec(Operands, Depth + 1, {TE, i});
5794 }
5795 return;
5796 }
5797 case Instruction::GetElementPtr: {
5798 // We don't combine GEPs with complicated (nested) indexing.
5799 for (Value *V : VL) {
5800 auto *I = dyn_cast<GetElementPtrInst>(V);
5801 if (!I)
5802 continue;
5803 if (I->getNumOperands() != 2) {
5804 LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n"
; } } while (false)
;
5805 BS.cancelScheduling(VL, VL0);
5806 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
5807 ReuseShuffleIndicies);
5808 return;
5809 }
5810 }
5811
5812 // We can't combine several GEPs into one vector if they operate on
5813 // different types.
5814 Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
5815 for (Value *V : VL) {
5816 auto *GEP = dyn_cast<GEPOperator>(V);
5817 if (!GEP)
5818 continue;
5819 Type *CurTy = GEP->getSourceElementType();
5820 if (Ty0 != CurTy) {
5821 LLVM_DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: not-vectorizable GEP (different types).\n"
; } } while (false)
5822 << "SLP: not-vectorizable GEP (different types).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: not-vectorizable GEP (different types).\n"
; } } while (false)
;
5823 BS.cancelScheduling(VL, VL0);
5824 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
5825 ReuseShuffleIndicies);
5826 return;
5827 }
5828 }
5829
5830 // We don't combine GEPs with non-constant indexes.
5831 Type *Ty1 = VL0->getOperand(1)->getType();
5832 for (Value *V : VL) {
5833 auto *I = dyn_cast<GetElementPtrInst>(V);
5834 if (!I)
5835 continue;
5836 auto *Op = I->getOperand(1);
5837 if ((!IsScatterVectorizeUserTE && !isa<ConstantInt>(Op)) ||
5838 (Op->getType() != Ty1 &&
5839 ((IsScatterVectorizeUserTE && !isa<ConstantInt>(Op)) ||
5840 Op->getType()->getScalarSizeInBits() >
5841 DL->getIndexSizeInBits(
5842 V->getType()->getPointerAddressSpace())))) {
5843 LLVM_DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n"
; } } while (false)
5844 << "SLP: not-vectorizable GEP (non-constant indexes).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n"
; } } while (false)
;
5845 BS.cancelScheduling(VL, VL0);
5846 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
5847 ReuseShuffleIndicies);
5848 return;
5849 }
5850 }
5851
5852 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5853 ReuseShuffleIndicies);
5854 LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: added a vector of GEPs.\n"; }
} while (false)
;
5855 SmallVector<ValueList, 2> Operands(2);
5856 // Prepare the operand vector for pointer operands.
5857 for (Value *V : VL) {
5858 auto *GEP = dyn_cast<GetElementPtrInst>(V);
5859 if (!GEP) {
5860 Operands.front().push_back(V);
5861 continue;
5862 }
5863 Operands.front().push_back(GEP->getPointerOperand());
5864 }
5865 TE->setOperand(0, Operands.front());
5866 // Need to cast all indices to the same type before vectorization to
5867 // avoid crash.
5868 // Required to be able to find correct matches between different gather
5869 // nodes and reuse the vectorized values rather than trying to gather them
5870 // again.
5871 int IndexIdx = 1;
5872 Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
5873 Type *Ty = all_of(VL,
5874 [VL0Ty, IndexIdx](Value *V) {
5875 auto *GEP = dyn_cast<GetElementPtrInst>(V);
5876 if (!GEP)
5877 return true;
5878 return VL0Ty == GEP->getOperand(IndexIdx)->getType();
5879 })
5880 ? VL0Ty
5881 : DL->getIndexType(cast<GetElementPtrInst>(VL0)
5882 ->getPointerOperandType()
5883 ->getScalarType());
5884 // Prepare the operand vector.
5885 for (Value *V : VL) {
5886 auto *I = dyn_cast<GetElementPtrInst>(V);
5887 if (!I) {
5888 Operands.back().push_back(
5889 ConstantInt::get(Ty, 0, /*isSigned=*/false));
5890 continue;
5891 }
5892 auto *Op = I->getOperand(IndexIdx);
5893 auto *CI = dyn_cast<ConstantInt>(Op);
5894 if (!CI)
5895 Operands.back().push_back(Op);
5896 else
5897 Operands.back().push_back(ConstantExpr::getIntegerCast(
5898 CI, Ty, CI->getValue().isSignBitSet()));
5899 }
5900 TE->setOperand(IndexIdx, Operands.back());
5901
5902 for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
5903 buildTree_rec(Operands[I], Depth + 1, {TE, I});
5904 return;
5905 }
5906 case Instruction::Store: {
5907 // Check if the stores are consecutive or if we need to swizzle them.
5908 llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
5909 // Avoid types that are padded when being allocated as scalars, while
5910 // being packed together in a vector (such as i1).
5911 if (DL->getTypeSizeInBits(ScalarTy) !=
5912 DL->getTypeAllocSizeInBits(ScalarTy)) {
5913 BS.cancelScheduling(VL, VL0);
5914 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
5915 ReuseShuffleIndicies);
5916 LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering stores of non-packed type.\n"
; } } while (false)
;
5917 return;
5918 }
5919 // Make sure all stores in the bundle are simple - we can't vectorize
5920 // atomic or volatile stores.
5921 SmallVector<Value *, 4> PointerOps(VL.size());
5922 ValueList Operands(VL.size());
5923 auto POIter = PointerOps.begin();
5924 auto OIter = Operands.begin();
5925 for (Value *V : VL) {
5926 auto *SI = cast<StoreInst>(V);
5927 if (!SI->isSimple()) {
5928 BS.cancelScheduling(VL, VL0);
5929 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
5930 ReuseShuffleIndicies);
5931 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering non-simple stores.\n"
; } } while (false)
;
5932 return;
5933 }
5934 *POIter = SI->getPointerOperand();
5935 *OIter = SI->getValueOperand();
5936 ++POIter;
5937 ++OIter;
5938 }
5939
5940 OrdersType CurrentOrder;
5941 // Check the order of pointer operands.
5942 if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
5943 Value *Ptr0;
5944 Value *PtrN;
5945 if (CurrentOrder.empty()) {
5946 Ptr0 = PointerOps.front();
5947 PtrN = PointerOps.back();
5948 } else {
5949 Ptr0 = PointerOps[CurrentOrder.front()];
5950 PtrN = PointerOps[CurrentOrder.back()];
5951 }
5952 std::optional<int> Dist =
5953 getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
5954 // Check that the sorted pointer operands are consecutive.
5955 if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
5956 if (CurrentOrder.empty()) {
5957 // Original stores are consecutive and does not require reordering.
5958 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
5959 UserTreeIdx, ReuseShuffleIndicies);
5960 TE->setOperandsInOrder();
5961 buildTree_rec(Operands, Depth + 1, {TE, 0});
5962 LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: added a vector of stores.\n"
; } } while (false)
;
5963 } else {
5964 fixupOrderingIndices(CurrentOrder);
5965 TreeEntry *TE =
5966 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5967 ReuseShuffleIndicies, CurrentOrder);
5968 TE->setOperandsInOrder();
5969 buildTree_rec(Operands, Depth + 1, {TE, 0});
5970 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: added a vector of jumbled stores.\n"
; } } while (false)
;
5971 }
5972 return;
5973 }
5974 }
5975
5976 BS.cancelScheduling(VL, VL0);
5977 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
5978 ReuseShuffleIndicies);
5979 LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Non-consecutive store.\n"; }
} while (false)
;
5980 return;
5981 }
5982 case Instruction::Call: {
5983 // Check if the calls are all to the same vectorizable intrinsic or
5984 // library function.
5985 CallInst *CI = cast<CallInst>(VL0);
5986 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5987
5988 VFShape Shape = VFShape::get(
5989 *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
5990 false /*HasGlobalPred*/);
5991 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
5992
5993 if (!VecFunc && !isTriviallyVectorizable(ID)) {
5994 BS.cancelScheduling(VL, VL0);
5995 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
5996 ReuseShuffleIndicies);
5997 LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Non-vectorizable call.\n"; }
} while (false)
;
5998 return;
5999 }
6000 Function *F = CI->getCalledFunction();
6001 unsigned NumArgs = CI->arg_size();
6002 SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
6003 for (unsigned j = 0; j != NumArgs; ++j)
6004 if (isVectorIntrinsicWithScalarOpAtArg(ID, j))
6005 ScalarArgs[j] = CI->getArgOperand(j);
6006 for (Value *V : VL) {
6007 CallInst *CI2 = dyn_cast<CallInst>(V);
6008 if (!CI2 || CI2->getCalledFunction() != F ||
6009 getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
6010 (VecFunc &&
6011 VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
6012 !CI->hasIdenticalOperandBundleSchema(*CI2)) {
6013 BS.cancelScheduling(VL, VL0);
6014 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
6015 ReuseShuffleIndicies);
6016 LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *Vdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: mismatched calls:" << *
CI << "!=" << *V << "\n"; } } while (false)
6017 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: mismatched calls:" << *
CI << "!=" << *V << "\n"; } } while (false)
;
6018 return;
6019 }
6020 // Some intrinsics have scalar arguments and should be same in order for
6021 // them to be vectorized.
6022 for (unsigned j = 0; j != NumArgs; ++j) {
6023 if (isVectorIntrinsicWithScalarOpAtArg(ID, j)) {
6024 Value *A1J = CI2->getArgOperand(j);
6025 if (ScalarArgs[j] != A1J) {
6026 BS.cancelScheduling(VL, VL0);
6027 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
6028 ReuseShuffleIndicies);
6029 LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CIdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: mismatched arguments in call:"
<< *CI << " argument " << ScalarArgs[j] <<
"!=" << A1J << "\n"; } } while (false)
6030 << " argument " << ScalarArgs[j] << "!=" << A1Jdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: mismatched arguments in call:"
<< *CI << " argument " << ScalarArgs[j] <<
"!=" << A1J << "\n"; } } while (false)
6031 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: mismatched arguments in call:"
<< *CI << " argument " << ScalarArgs[j] <<
"!=" << A1J << "\n"; } } while (false)
;
6032 return;
6033 }
6034 }
6035 }
6036 // Verify that the bundle operands are identical between the two calls.
6037 if (CI->hasOperandBundles() &&
6038 !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
6039 CI->op_begin() + CI->getBundleOperandsEndIndex(),
6040 CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
6041 BS.cancelScheduling(VL, VL0);
6042 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
6043 ReuseShuffleIndicies);
6044 LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: mismatched bundle operands in calls:"
<< *CI << "!=" << *V << '\n'; } } while
(false)
6045 << *CI << "!=" << *V << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: mismatched bundle operands in calls:"
<< *CI << "!=" << *V << '\n'; } } while
(false)
;
6046 return;
6047 }
6048 }
6049
6050 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
6051 ReuseShuffleIndicies);
6052 TE->setOperandsInOrder();
6053 for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
6054 // For scalar operands no need to to create an entry since no need to
6055 // vectorize it.
6056 if (isVectorIntrinsicWithScalarOpAtArg(ID, i))
6057 continue;
6058 ValueList Operands;
6059 // Prepare the operand vector.
6060 for (Value *V : VL) {
6061 auto *CI2 = cast<CallInst>(V);
6062 Operands.push_back(CI2->getArgOperand(i));
6063 }
6064 buildTree_rec(Operands, Depth + 1, {TE, i});
6065 }
6066 return;
6067 }
6068 case Instruction::ShuffleVector: {
6069 // If this is not an alternate sequence of opcode like add-sub
6070 // then do not vectorize this instruction.
6071 if (!S.isAltShuffle()) {
6072 BS.cancelScheduling(VL, VL0);
6073 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
6074 ReuseShuffleIndicies);
6075 LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: ShuffleVector are not vectorized.\n"
; } } while (false)
;
6076 return;
6077 }
6078 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
6079 ReuseShuffleIndicies);
6080 LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: added a ShuffleVector op.\n"
; } } while (false)
;
6081
6082 // Reorder operands if reordering would enable vectorization.
6083 auto *CI = dyn_cast<CmpInst>(VL0);
6084 if (isa<BinaryOperator>(VL0) || CI) {
6085 ValueList Left, Right;
6086 if (!CI || all_of(VL, [](Value *V) {
6087 return cast<CmpInst>(V)->isCommutative();
6088 })) {
6089 reorderInputsAccordingToOpcode(VL, Left, Right, *TLI, *DL, *SE,
6090 *this);
6091 } else {
6092 auto *MainCI = cast<CmpInst>(S.MainOp);
6093 auto *AltCI = cast<CmpInst>(S.AltOp);
6094 CmpInst::Predicate MainP = MainCI->getPredicate();
6095 CmpInst::Predicate AltP = AltCI->getPredicate();
6096 assert(MainP != AltP &&(static_cast <bool> (MainP != AltP && "Expected different main/alternate predicates."
) ? void (0) : __assert_fail ("MainP != AltP && \"Expected different main/alternate predicates.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6097, __extension__
__PRETTY_FUNCTION__))
6097 "Expected different main/alternate predicates.")(static_cast <bool> (MainP != AltP && "Expected different main/alternate predicates."
) ? void (0) : __assert_fail ("MainP != AltP && \"Expected different main/alternate predicates.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6097, __extension__
__PRETTY_FUNCTION__))
;
6098 // Collect operands - commute if it uses the swapped predicate or
6099 // alternate operation.
6100 for (Value *V : VL) {
6101 auto *Cmp = cast<CmpInst>(V);
6102 Value *LHS = Cmp->getOperand(0);
6103 Value *RHS = Cmp->getOperand(1);
6104
6105 if (isAlternateInstruction(Cmp, MainCI, AltCI, *TLI)) {
6106 if (AltP == CmpInst::getSwappedPredicate(Cmp->getPredicate()))
6107 std::swap(LHS, RHS);
6108 } else {
6109 if (MainP == CmpInst::getSwappedPredicate(Cmp->getPredicate()))
6110 std::swap(LHS, RHS);
6111 }
6112 Left.push_back(LHS);
6113 Right.push_back(RHS);
6114 }
6115 }
6116 TE->setOperand(0, Left);
6117 TE->setOperand(1, Right);
6118 buildTree_rec(Left, Depth + 1, {TE, 0});
6119 buildTree_rec(Right, Depth + 1, {TE, 1});
6120 return;
6121 }
6122
6123 TE->setOperandsInOrder();
6124 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
6125 ValueList Operands;
6126 // Prepare the operand vector.
6127 for (Value *V : VL)
6128 Operands.push_back(cast<Instruction>(V)->getOperand(i));
6129
6130 buildTree_rec(Operands, Depth + 1, {TE, i});
6131 }
6132 return;
6133 }
6134 default:
6135 BS.cancelScheduling(VL, VL0);
6136 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
6137 ReuseShuffleIndicies);
6138 LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Gathering unknown instruction.\n"
; } } while (false)
;
6139 return;
6140 }
6141}
6142
6143unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
6144 unsigned N = 1;
6145 Type *EltTy = T;
6146
6147 while (isa<StructType, ArrayType, VectorType>(EltTy)) {
6148 if (auto *ST = dyn_cast<StructType>(EltTy)) {
6149 // Check that struct is homogeneous.
6150 for (const auto *Ty : ST->elements())
6151 if (Ty != *ST->element_begin())
6152 return 0;
6153 N *= ST->getNumElements();
6154 EltTy = *ST->element_begin();
6155 } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
6156 N *= AT->getNumElements();
6157 EltTy = AT->getElementType();
6158 } else {
6159 auto *VT = cast<FixedVectorType>(EltTy);
6160 N *= VT->getNumElements();
6161 EltTy = VT->getElementType();
6162 }
6163 }
6164
6165 if (!isValidElementType(EltTy))
6166 return 0;
6167 uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
6168 if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
6169 return 0;
6170 return N;
6171}
6172
6173bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
6174 SmallVectorImpl<unsigned> &CurrentOrder) const {
6175 const auto *It = find_if(VL, [](Value *V) {
6176 return isa<ExtractElementInst, ExtractValueInst>(V);
6177 });
6178 assert(It != VL.end() && "Expected at least one extract instruction.")(static_cast <bool> (It != VL.end() && "Expected at least one extract instruction."
) ? void (0) : __assert_fail ("It != VL.end() && \"Expected at least one extract instruction.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6178, __extension__
__PRETTY_FUNCTION__))
;
6179 auto *E0 = cast<Instruction>(*It);
6180 assert(all_of(VL,(static_cast <bool> (all_of(VL, [](Value *V) { return isa
<UndefValue, ExtractElementInst, ExtractValueInst>( V);
}) && "Invalid opcode") ? void (0) : __assert_fail (
"all_of(VL, [](Value *V) { return isa<UndefValue, ExtractElementInst, ExtractValueInst>( V); }) && \"Invalid opcode\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6185, __extension__
__PRETTY_FUNCTION__))
6181 [](Value *V) {(static_cast <bool> (all_of(VL, [](Value *V) { return isa
<UndefValue, ExtractElementInst, ExtractValueInst>( V);
}) && "Invalid opcode") ? void (0) : __assert_fail (
"all_of(VL, [](Value *V) { return isa<UndefValue, ExtractElementInst, ExtractValueInst>( V); }) && \"Invalid opcode\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6185, __extension__
__PRETTY_FUNCTION__))
6182 return isa<UndefValue, ExtractElementInst, ExtractValueInst>((static_cast <bool> (all_of(VL, [](Value *V) { return isa
<UndefValue, ExtractElementInst, ExtractValueInst>( V);
}) && "Invalid opcode") ? void (0) : __assert_fail (
"all_of(VL, [](Value *V) { return isa<UndefValue, ExtractElementInst, ExtractValueInst>( V); }) && \"Invalid opcode\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6185, __extension__
__PRETTY_FUNCTION__))
6183 V);(static_cast <bool> (all_of(VL, [](Value *V) { return isa
<UndefValue, ExtractElementInst, ExtractValueInst>( V);
}) && "Invalid opcode") ? void (0) : __assert_fail (
"all_of(VL, [](Value *V) { return isa<UndefValue, ExtractElementInst, ExtractValueInst>( V); }) && \"Invalid opcode\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6185, __extension__
__PRETTY_FUNCTION__))
6184 }) &&(static_cast <bool> (all_of(VL, [](Value *V) { return isa
<UndefValue, ExtractElementInst, ExtractValueInst>( V);
}) && "Invalid opcode") ? void (0) : __assert_fail (
"all_of(VL, [](Value *V) { return isa<UndefValue, ExtractElementInst, ExtractValueInst>( V); }) && \"Invalid opcode\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6185, __extension__
__PRETTY_FUNCTION__))
6185 "Invalid opcode")(static_cast <bool> (all_of(VL, [](Value *V) { return isa
<UndefValue, ExtractElementInst, ExtractValueInst>( V);
}) && "Invalid opcode") ? void (0) : __assert_fail (
"all_of(VL, [](Value *V) { return isa<UndefValue, ExtractElementInst, ExtractValueInst>( V); }) && \"Invalid opcode\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6185, __extension__
__PRETTY_FUNCTION__))
;
6186 // Check if all of the extracts come from the same vector and from the
6187 // correct offset.
6188 Value *Vec = E0->getOperand(0);
6189
6190 CurrentOrder.clear();
6191
6192 // We have to extract from a vector/aggregate with the same number of elements.
6193 unsigned NElts;
6194 if (E0->getOpcode() == Instruction::ExtractValue) {
6195 const DataLayout &DL = E0->getModule()->getDataLayout();
6196 NElts = canMapToVector(Vec->getType(), DL);
6197 if (!NElts)
6198 return false;
6199 // Check if load can be rewritten as load of vector.
6200 LoadInst *LI = dyn_cast<LoadInst>(Vec);
6201 if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
6202 return false;
6203 } else {
6204 NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
6205 }
6206
6207 if (NElts != VL.size())
6208 return false;
6209
6210 // Check that all of the indices extract from the correct offset.
6211 bool ShouldKeepOrder = true;
6212 unsigned E = VL.size();
6213 // Assign to all items the initial value E + 1 so we can check if the extract
6214 // instruction index was used already.
6215 // Also, later we can check that all the indices are used and we have a
6216 // consecutive access in the extract instructions, by checking that no
6217 // element of CurrentOrder still has value E + 1.
6218 CurrentOrder.assign(E, E);
6219 unsigned I = 0;
6220 for (; I < E; ++I) {
6221 auto *Inst = dyn_cast<Instruction>(VL[I]);
6222 if (!Inst)
6223 continue;
6224 if (Inst->getOperand(0) != Vec)
6225 break;
6226 if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
6227 if (isa<UndefValue>(EE->getIndexOperand()))
6228 continue;
6229 std::optional<unsigned> Idx = getExtractIndex(Inst);
6230 if (!Idx)
6231 break;
6232 const unsigned ExtIdx = *Idx;
6233 if (ExtIdx != I) {
6234 if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
6235 break;
6236 ShouldKeepOrder = false;
6237 CurrentOrder[ExtIdx] = I;
6238 } else {
6239 if (CurrentOrder[I] != E)
6240 break;
6241 CurrentOrder[I] = I;
6242 }
6243 }
6244 if (I < E) {
6245 CurrentOrder.clear();
6246 return false;
6247 }
6248 if (ShouldKeepOrder)
6249 CurrentOrder.clear();
6250
6251 return ShouldKeepOrder;
6252}
6253
6254bool BoUpSLP::areAllUsersVectorized(Instruction *I,
6255 ArrayRef<Value *> VectorizedVals) const {
6256 return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
6257 all_of(I->users(), [this](User *U) {
6258 return ScalarToTreeEntry.count(U) > 0 ||
6259 isVectorLikeInstWithConstOps(U) ||
6260 (isa<ExtractElementInst>(U) && MustGather.contains(U));
6261 });
6262}
6263
6264static std::pair<InstructionCost, InstructionCost>
6265getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
6266 TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
6267 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
6268
6269 // Calculate the cost of the scalar and vector calls.
6270 SmallVector<Type *, 4> VecTys;
6271 for (Use &Arg : CI->args())
6272 VecTys.push_back(
6273 FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
6274 FastMathFlags FMF;
6275 if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
6276 FMF = FPCI->getFastMathFlags();
6277 SmallVector<const Value *> Arguments(CI->args());
6278 IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
6279 dyn_cast<IntrinsicInst>(CI));
6280 auto IntrinsicCost =
6281 TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
6282
6283 auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
6284 VecTy->getNumElements())),
6285 false /*HasGlobalPred*/);
6286 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
6287 auto LibCost = IntrinsicCost;
6288 if (!CI->isNoBuiltin() && VecFunc) {
6289 // Calculate the cost of the vector library call.
6290 // If the corresponding vector call is cheaper, return its cost.
6291 LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
6292 TTI::TCK_RecipThroughput);
6293 }
6294 return {IntrinsicCost, LibCost};
6295}
6296
6297/// Build shuffle mask for shuffle graph entries and lists of main and alternate
6298/// operations operands.
6299static void
6300buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
6301 ArrayRef<int> ReusesIndices,
6302 const function_ref<bool(Instruction *)> IsAltOp,
6303 SmallVectorImpl<int> &Mask,
6304 SmallVectorImpl<Value *> *OpScalars = nullptr,
6305 SmallVectorImpl<Value *> *AltScalars = nullptr) {
6306 unsigned Sz = VL.size();
6307 Mask.assign(Sz, PoisonMaskElem);
6308 SmallVector<int> OrderMask;
6309 if (!ReorderIndices.empty())
6310 inversePermutation(ReorderIndices, OrderMask);
6311 for (unsigned I = 0; I < Sz; ++I) {
6312 unsigned Idx = I;
6313 if (!ReorderIndices.empty())
6314 Idx = OrderMask[I];
6315 auto *OpInst = cast<Instruction>(VL[Idx]);
6316 if (IsAltOp(OpInst)) {
6317 Mask[I] = Sz + Idx;
6318 if (AltScalars)
6319 AltScalars->push_back(OpInst);
6320 } else {
6321 Mask[I] = Idx;
6322 if (OpScalars)
6323 OpScalars->push_back(OpInst);
6324 }
6325 }
6326 if (!ReusesIndices.empty()) {
6327 SmallVector<int> NewMask(ReusesIndices.size(), PoisonMaskElem);
6328 transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
6329 return Idx != PoisonMaskElem ? Mask[Idx] : PoisonMaskElem;
6330 });
6331 Mask.swap(NewMask);
6332 }
6333}
6334
6335static bool isAlternateInstruction(const Instruction *I,
6336 const Instruction *MainOp,
6337 const Instruction *AltOp,
6338 const TargetLibraryInfo &TLI) {
6339 if (auto *MainCI = dyn_cast<CmpInst>(MainOp)) {
6340 auto *AltCI = cast<CmpInst>(AltOp);
6341 CmpInst::Predicate MainP = MainCI->getPredicate();
6342 CmpInst::Predicate AltP = AltCI->getPredicate();
6343 assert(MainP != AltP && "Expected different main/alternate predicates.")(static_cast <bool> (MainP != AltP && "Expected different main/alternate predicates."
) ? void (0) : __assert_fail ("MainP != AltP && \"Expected different main/alternate predicates.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6343, __extension__
__PRETTY_FUNCTION__))
;
6344 auto *CI = cast<CmpInst>(I);
6345 if (isCmpSameOrSwapped(MainCI, CI, TLI))
6346 return false;
6347 if (isCmpSameOrSwapped(AltCI, CI, TLI))
6348 return true;
6349 CmpInst::Predicate P = CI->getPredicate();
6350 CmpInst::Predicate SwappedP = CmpInst::getSwappedPredicate(P);
6351
6352 assert((MainP == P || AltP == P || MainP == SwappedP || AltP == SwappedP) &&(static_cast <bool> ((MainP == P || AltP == P || MainP ==
SwappedP || AltP == SwappedP) && "CmpInst expected to match either main or alternate predicate or "
"their swap.") ? void (0) : __assert_fail ("(MainP == P || AltP == P || MainP == SwappedP || AltP == SwappedP) && \"CmpInst expected to match either main or alternate predicate or \" \"their swap.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6354, __extension__
__PRETTY_FUNCTION__))
6353 "CmpInst expected to match either main or alternate predicate or "(static_cast <bool> ((MainP == P || AltP == P || MainP ==
SwappedP || AltP == SwappedP) && "CmpInst expected to match either main or alternate predicate or "
"their swap.") ? void (0) : __assert_fail ("(MainP == P || AltP == P || MainP == SwappedP || AltP == SwappedP) && \"CmpInst expected to match either main or alternate predicate or \" \"their swap.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6354, __extension__
__PRETTY_FUNCTION__))
6354 "their swap.")(static_cast <bool> ((MainP == P || AltP == P || MainP ==
SwappedP || AltP == SwappedP) && "CmpInst expected to match either main or alternate predicate or "
"their swap.") ? void (0) : __assert_fail ("(MainP == P || AltP == P || MainP == SwappedP || AltP == SwappedP) && \"CmpInst expected to match either main or alternate predicate or \" \"their swap.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6354, __extension__
__PRETTY_FUNCTION__))
;
6355 (void)AltP;
6356 return MainP != P && MainP != SwappedP;
6357 }
6358 return I->getOpcode() == AltOp->getOpcode();
6359}
6360
6361TTI::OperandValueInfo BoUpSLP::getOperandInfo(ArrayRef<Value *> VL,
6362 unsigned OpIdx) {
6363 assert(!VL.empty())(static_cast <bool> (!VL.empty()) ? void (0) : __assert_fail
("!VL.empty()", "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 6363, __extension__ __PRETTY_FUNCTION__))
;
6364 const auto *I0 = cast<Instruction>(*find_if(VL, Instruction::classof));
6365 const auto *Op0 = I0->getOperand(OpIdx);
6366
6367 const bool IsConstant = all_of(VL, [&](Value *V) {
6368 // TODO: We should allow undef elements here
6369 const auto *I = dyn_cast<Instruction>(V);
6370 if (!I)
6371 return true;
6372 auto *Op = I->getOperand(OpIdx);
6373 return isConstant(Op) && !isa<UndefValue>(Op);
6374 });
6375 const bool IsUniform = all_of(VL, [&](Value *V) {
6376 // TODO: We should allow undef elements here
6377 const auto *I = dyn_cast<Instruction>(V);
6378 if (!I)
6379 return false;
6380 return I->getOperand(OpIdx) == Op0;
6381 });
6382 const bool IsPowerOfTwo = all_of(VL, [&](Value *V) {
6383 // TODO: We should allow undef elements here
6384 const auto *I = dyn_cast<Instruction>(V);
6385 if (!I) {
6386 assert((isa<UndefValue>(V) ||(static_cast <bool> ((isa<UndefValue>(V) || I0->
getOpcode() == Instruction::GetElementPtr) && "Expected undef or GEP."
) ? void (0) : __assert_fail ("(isa<UndefValue>(V) || I0->getOpcode() == Instruction::GetElementPtr) && \"Expected undef or GEP.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6388, __extension__
__PRETTY_FUNCTION__))
6387 I0->getOpcode() == Instruction::GetElementPtr) &&(static_cast <bool> ((isa<UndefValue>(V) || I0->
getOpcode() == Instruction::GetElementPtr) && "Expected undef or GEP."
) ? void (0) : __assert_fail ("(isa<UndefValue>(V) || I0->getOpcode() == Instruction::GetElementPtr) && \"Expected undef or GEP.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6388, __extension__
__PRETTY_FUNCTION__))
6388 "Expected undef or GEP.")(static_cast <bool> ((isa<UndefValue>(V) || I0->
getOpcode() == Instruction::GetElementPtr) && "Expected undef or GEP."
) ? void (0) : __assert_fail ("(isa<UndefValue>(V) || I0->getOpcode() == Instruction::GetElementPtr) && \"Expected undef or GEP.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6388, __extension__
__PRETTY_FUNCTION__))
;
6389 return true;
6390 }
6391 auto *Op = I->getOperand(OpIdx);
6392 if (auto *CI = dyn_cast<ConstantInt>(Op))
6393 return CI->getValue().isPowerOf2();
6394 return false;
6395 });
6396 const bool IsNegatedPowerOfTwo = all_of(VL, [&](Value *V) {
6397 // TODO: We should allow undef elements here
6398 const auto *I = dyn_cast<Instruction>(V);
6399 if (!I) {
6400 assert((isa<UndefValue>(V) ||(static_cast <bool> ((isa<UndefValue>(V) || I0->
getOpcode() == Instruction::GetElementPtr) && "Expected undef or GEP."
) ? void (0) : __assert_fail ("(isa<UndefValue>(V) || I0->getOpcode() == Instruction::GetElementPtr) && \"Expected undef or GEP.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6402, __extension__
__PRETTY_FUNCTION__))
6401 I0->getOpcode() == Instruction::GetElementPtr) &&(static_cast <bool> ((isa<UndefValue>(V) || I0->
getOpcode() == Instruction::GetElementPtr) && "Expected undef or GEP."
) ? void (0) : __assert_fail ("(isa<UndefValue>(V) || I0->getOpcode() == Instruction::GetElementPtr) && \"Expected undef or GEP.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6402, __extension__
__PRETTY_FUNCTION__))
6402 "Expected undef or GEP.")(static_cast <bool> ((isa<UndefValue>(V) || I0->
getOpcode() == Instruction::GetElementPtr) && "Expected undef or GEP."
) ? void (0) : __assert_fail ("(isa<UndefValue>(V) || I0->getOpcode() == Instruction::GetElementPtr) && \"Expected undef or GEP.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6402, __extension__
__PRETTY_FUNCTION__))
;
6403 return true;
6404 }
6405 const auto *Op = I->getOperand(OpIdx);
6406 if (auto *CI = dyn_cast<ConstantInt>(Op))
6407 return CI->getValue().isNegatedPowerOf2();
6408 return false;
6409 });
6410
6411 TTI::OperandValueKind VK = TTI::OK_AnyValue;
6412 if (IsConstant && IsUniform)
6413 VK = TTI::OK_UniformConstantValue;
6414 else if (IsConstant)
6415 VK = TTI::OK_NonUniformConstantValue;
6416 else if (IsUniform)
6417 VK = TTI::OK_UniformValue;
6418
6419 TTI::OperandValueProperties VP = TTI::OP_None;
6420 VP = IsPowerOfTwo ? TTI::OP_PowerOf2 : VP;
6421 VP = IsNegatedPowerOfTwo ? TTI::OP_NegatedPowerOf2 : VP;
6422
6423 return {VK, VP};
6424}
6425
6426namespace {
6427/// The base class for shuffle instruction emission and shuffle cost estimation.
6428class BaseShuffleAnalysis {
6429protected:
6430 /// Checks if the mask is an identity mask.
6431 /// \param IsStrict if is true the function returns false if mask size does
6432 /// not match vector size.
6433 static bool isIdentityMask(ArrayRef<int> Mask, const FixedVectorType *VecTy,
6434 bool IsStrict) {
6435 int Limit = Mask.size();
6436 int VF = VecTy->getNumElements();
6437 return (VF == Limit || !IsStrict) &&
6438 all_of(Mask, [Limit](int Idx) { return Idx < Limit; }) &&
6439 ShuffleVectorInst::isIdentityMask(Mask);
6440 }
6441
6442 /// Tries to combine 2 different masks into single one.
6443 /// \param LocalVF Vector length of the permuted input vector. \p Mask may
6444 /// change the size of the vector, \p LocalVF is the original size of the
6445 /// shuffled vector.
6446 static void combineMasks(unsigned LocalVF, SmallVectorImpl<int> &Mask,
6447 ArrayRef<int> ExtMask) {
6448 unsigned VF = Mask.size();
6449 SmallVector<int> NewMask(ExtMask.size(), PoisonMaskElem);
6450 for (int I = 0, Sz = ExtMask.size(); I < Sz; ++I) {
6451 if (ExtMask[I] == PoisonMaskElem)
6452 continue;
6453 int MaskedIdx = Mask[ExtMask[I] % VF];
6454 NewMask[I] =
6455 MaskedIdx == PoisonMaskElem ? PoisonMaskElem : MaskedIdx % LocalVF;
6456 }
6457 Mask.swap(NewMask);
6458 }
6459
6460 /// Looks through shuffles trying to reduce final number of shuffles in the
6461 /// code. The function looks through the previously emitted shuffle
6462 /// instructions and properly mark indices in mask as undef.
6463 /// For example, given the code
6464 /// \code
6465 /// %s1 = shufflevector <2 x ty> %0, poison, <1, 0>
6466 /// %s2 = shufflevector <2 x ty> %1, poison, <1, 0>
6467 /// \endcode
6468 /// and if need to emit shuffle of %s1 and %s2 with mask <1, 0, 3, 2>, it will
6469 /// look through %s1 and %s2 and select vectors %0 and %1 with mask
6470 /// <0, 1, 2, 3> for the shuffle.
6471 /// If 2 operands are of different size, the smallest one will be resized and
6472 /// the mask recalculated properly.
6473 /// For example, given the code
6474 /// \code
6475 /// %s1 = shufflevector <2 x ty> %0, poison, <1, 0, 1, 0>
6476 /// %s2 = shufflevector <2 x ty> %1, poison, <1, 0, 1, 0>
6477 /// \endcode
6478 /// and if need to emit shuffle of %s1 and %s2 with mask <1, 0, 5, 4>, it will
6479 /// look through %s1 and %s2 and select vectors %0 and %1 with mask
6480 /// <0, 1, 2, 3> for the shuffle.
6481 /// So, it tries to transform permutations to simple vector merge, if
6482 /// possible.
6483 /// \param V The input vector which must be shuffled using the given \p Mask.
6484 /// If the better candidate is found, \p V is set to this best candidate
6485 /// vector.
6486 /// \param Mask The input mask for the shuffle. If the best candidate is found
6487 /// during looking-through-shuffles attempt, it is updated accordingly.
6488 /// \param SinglePermute true if the shuffle operation is originally a
6489 /// single-value-permutation. In this case the look-through-shuffles procedure
6490 /// may look for resizing shuffles as the best candidates.
6491 /// \return true if the shuffle results in the non-resizing identity shuffle
6492 /// (and thus can be ignored), false - otherwise.
6493 static bool peekThroughShuffles(Value *&V, SmallVectorImpl<int> &Mask,
6494 bool SinglePermute) {
6495 Value *Op = V;
6496 ShuffleVectorInst *IdentityOp = nullptr;
6497 SmallVector<int> IdentityMask;
6498 while (auto *SV = dyn_cast<ShuffleVectorInst>(Op)) {
6499 // Exit if not a fixed vector type or changing size shuffle.
6500 auto *SVTy = dyn_cast<FixedVectorType>(SV->getType());
6501 if (!SVTy)
6502 break;
6503 // Remember the identity or broadcast mask, if it is not a resizing
6504 // shuffle. If no better candidates are found, this Op and Mask will be
6505 // used in the final shuffle.
6506 if (isIdentityMask(Mask, SVTy, /*IsStrict=*/false)) {
6507 if (!IdentityOp || !SinglePermute ||
6508 (isIdentityMask(Mask, SVTy, /*IsStrict=*/true) &&
6509 !ShuffleVectorInst::isZeroEltSplatMask(IdentityMask))) {
6510 IdentityOp = SV;
6511 // Store current mask in the IdentityMask so later we did not lost
6512 // this info if IdentityOp is selected as the best candidate for the
6513 // permutation.
6514 IdentityMask.assign(Mask);
6515 }
6516 }
6517 // Remember the broadcast mask. If no better candidates are found, this Op
6518 // and Mask will be used in the final shuffle.
6519 // Zero splat can be used as identity too, since it might be used with
6520 // mask <0, 1, 2, ...>, i.e. identity mask without extra reshuffling.
6521 // E.g. if need to shuffle the vector with the mask <3, 1, 2, 0>, which is
6522 // expensive, the analysis founds out, that the source vector is just a
6523 // broadcast, this original mask can be transformed to identity mask <0,
6524 // 1, 2, 3>.
6525 // \code
6526 // %0 = shuffle %v, poison, zeroinitalizer
6527 // %res = shuffle %0, poison, <3, 1, 2, 0>
6528 // \endcode
6529 // may be transformed to
6530 // \code
6531 // %0 = shuffle %v, poison, zeroinitalizer
6532 // %res = shuffle %0, poison, <0, 1, 2, 3>
6533 // \endcode
6534 if (SV->isZeroEltSplat()) {
6535 IdentityOp = SV;
6536 IdentityMask.assign(Mask);
6537 }
6538 int LocalVF = Mask.size();
6539 if (auto *SVOpTy =
6540 dyn_cast<FixedVectorType>(SV->getOperand(0)->getType()))
6541 LocalVF = SVOpTy->getNumElements();
6542 SmallVector<int> ExtMask(Mask.size(), PoisonMaskElem);
6543 for (auto [Idx, I] : enumerate(Mask)) {
6544 if (I == PoisonMaskElem ||
6545 static_cast<unsigned>(I) >= SV->getShuffleMask().size())
6546 continue;
6547 ExtMask[Idx] = SV->getMaskValue(I);
6548 }
6549 bool IsOp1Undef =
6550 isUndefVector(SV->getOperand(0),
6551 buildUseMask(LocalVF, ExtMask, UseMask::FirstArg))
6552 .all();
6553 bool IsOp2Undef =
6554 isUndefVector(SV->getOperand(1),
6555 buildUseMask(LocalVF, ExtMask, UseMask::SecondArg))
6556 .all();
6557 if (!IsOp1Undef && !IsOp2Undef) {
6558 // Update mask and mark undef elems.
6559 for (int &I : Mask) {
6560 if (I == PoisonMaskElem)
6561 continue;
6562 if (SV->getMaskValue(I % SV->getShuffleMask().size()) ==
6563 PoisonMaskElem)
6564 I = PoisonMaskElem;
6565 }
6566 break;
6567 }
6568 SmallVector<int> ShuffleMask(SV->getShuffleMask().begin(),
6569 SV->getShuffleMask().end());
6570 combineMasks(LocalVF, ShuffleMask, Mask);
6571 Mask.swap(ShuffleMask);
6572 if (IsOp2Undef)
6573 Op = SV->getOperand(0);
6574 else
6575 Op = SV->getOperand(1);
6576 }
6577 if (auto *OpTy = dyn_cast<FixedVectorType>(Op->getType());
6578 !OpTy || !isIdentityMask(Mask, OpTy, SinglePermute) ||
6579 ShuffleVectorInst::isZeroEltSplatMask(Mask)) {
6580 if (IdentityOp) {
6581 V = IdentityOp;
6582 assert(Mask.size() == IdentityMask.size() &&(static_cast <bool> (Mask.size() == IdentityMask.size()
&& "Expected masks of same sizes.") ? void (0) : __assert_fail
("Mask.size() == IdentityMask.size() && \"Expected masks of same sizes.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6583, __extension__
__PRETTY_FUNCTION__))
6583 "Expected masks of same sizes.")(static_cast <bool> (Mask.size() == IdentityMask.size()
&& "Expected masks of same sizes.") ? void (0) : __assert_fail
("Mask.size() == IdentityMask.size() && \"Expected masks of same sizes.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6583, __extension__
__PRETTY_FUNCTION__))
;
6584 // Clear known poison elements.
6585 for (auto [I, Idx] : enumerate(Mask))
6586 if (Idx == PoisonMaskElem)
6587 IdentityMask[I] = PoisonMaskElem;
6588 Mask.swap(IdentityMask);
6589 auto *Shuffle = dyn_cast<ShuffleVectorInst>(V);
6590 return SinglePermute &&
6591 (isIdentityMask(Mask, cast<FixedVectorType>(V->getType()),
6592 /*IsStrict=*/true) ||
6593 (Shuffle && Mask.size() == Shuffle->getShuffleMask().size() &&
6594 Shuffle->isZeroEltSplat() &&
6595 ShuffleVectorInst::isZeroEltSplatMask(Mask)));
6596 }
6597 V = Op;
6598 return false;
6599 }
6600 V = Op;
6601 return true;
6602 }
6603
6604 /// Smart shuffle instruction emission, walks through shuffles trees and
6605 /// tries to find the best matching vector for the actual shuffle
6606 /// instruction.
6607 template <typename T, typename ShuffleBuilderTy>
6608 static T createShuffle(Value *V1, Value *V2, ArrayRef<int> Mask,
6609 ShuffleBuilderTy &Builder) {
6610 assert(V1 && "Expected at least one vector value.")(static_cast <bool> (V1 && "Expected at least one vector value."
) ? void (0) : __assert_fail ("V1 && \"Expected at least one vector value.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6610, __extension__
__PRETTY_FUNCTION__))
;
6611 if (V2)
6612 Builder.resizeToMatch(V1, V2);
6613 int VF = Mask.size();
6614 if (auto *FTy = dyn_cast<FixedVectorType>(V1->getType()))
6615 VF = FTy->getNumElements();
6616 if (V2 &&
6617 !isUndefVector(V2, buildUseMask(VF, Mask, UseMask::SecondArg)).all()) {
6618 // Peek through shuffles.
6619 Value *Op1 = V1;
6620 Value *Op2 = V2;
6621 int VF =
6622 cast<VectorType>(V1->getType())->getElementCount().getKnownMinValue();
6623 SmallVector<int> CombinedMask1(Mask.size(), PoisonMaskElem);
6624 SmallVector<int> CombinedMask2(Mask.size(), PoisonMaskElem);
6625 for (int I = 0, E = Mask.size(); I < E; ++I) {
6626 if (Mask[I] < VF)
6627 CombinedMask1[I] = Mask[I];
6628 else
6629 CombinedMask2[I] = Mask[I] - VF;
6630 }
6631 Value *PrevOp1;
6632 Value *PrevOp2;
6633 do {
6634 PrevOp1 = Op1;
6635 PrevOp2 = Op2;
6636 (void)peekThroughShuffles(Op1, CombinedMask1, /*SinglePermute=*/false);
6637 (void)peekThroughShuffles(Op2, CombinedMask2, /*SinglePermute=*/false);
6638 // Check if we have 2 resizing shuffles - need to peek through operands
6639 // again.
6640 if (auto *SV1 = dyn_cast<ShuffleVectorInst>(Op1))
6641 if (auto *SV2 = dyn_cast<ShuffleVectorInst>(Op2)) {
6642 SmallVector<int> ExtMask1(Mask.size(), PoisonMaskElem);
6643 for (auto [Idx, I] : enumerate(CombinedMask1)) {
6644 if (I == PoisonMaskElem)
6645 continue;
6646 ExtMask1[Idx] = SV1->getMaskValue(I);
6647 }
6648 SmallBitVector UseMask1 = buildUseMask(
6649 cast<FixedVectorType>(SV1->getOperand(1)->getType())
6650 ->getNumElements(),
6651 ExtMask1, UseMask::SecondArg);
6652 SmallVector<int> ExtMask2(CombinedMask2.size(), PoisonMaskElem);
6653 for (auto [Idx, I] : enumerate(CombinedMask2)) {
6654 if (I == PoisonMaskElem)
6655 continue;
6656 ExtMask2[Idx] = SV2->getMaskValue(I);
6657 }
6658 SmallBitVector UseMask2 = buildUseMask(
6659 cast<FixedVectorType>(SV2->getOperand(1)->getType())
6660 ->getNumElements(),
6661 ExtMask2, UseMask::SecondArg);
6662 if (SV1->getOperand(0)->getType() ==
6663 SV2->getOperand(0)->getType() &&
6664 SV1->getOperand(0)->getType() != SV1->getType() &&
6665 isUndefVector(SV1->getOperand(1), UseMask1).all() &&
6666 isUndefVector(SV2->getOperand(1), UseMask2).all()) {
6667 Op1 = SV1->getOperand(0);
6668 Op2 = SV2->getOperand(0);
6669 SmallVector<int> ShuffleMask1(SV1->getShuffleMask().begin(),
6670 SV1->getShuffleMask().end());
6671 int LocalVF = ShuffleMask1.size();
6672 if (auto *FTy = dyn_cast<FixedVectorType>(Op1->getType()))
6673 LocalVF = FTy->getNumElements();
6674 combineMasks(LocalVF, ShuffleMask1, CombinedMask1);
6675 CombinedMask1.swap(ShuffleMask1);
6676 SmallVector<int> ShuffleMask2(SV2->getShuffleMask().begin(),
6677 SV2->getShuffleMask().end());
6678 LocalVF = ShuffleMask2.size();
6679 if (auto *FTy = dyn_cast<FixedVectorType>(Op2->getType()))
6680 LocalVF = FTy->getNumElements();
6681 combineMasks(LocalVF, ShuffleMask2, CombinedMask2);
6682 CombinedMask2.swap(ShuffleMask2);
6683 }
6684 }
6685 } while (PrevOp1 != Op1 || PrevOp2 != Op2);
6686 Builder.resizeToMatch(Op1, Op2);
6687 VF = std::max(cast<VectorType>(Op1->getType())
6688 ->getElementCount()
6689 .getKnownMinValue(),
6690 cast<VectorType>(Op2->getType())
6691 ->getElementCount()
6692 .getKnownMinValue());
6693 for (int I = 0, E = Mask.size(); I < E; ++I) {
6694 if (CombinedMask2[I] != PoisonMaskElem) {
6695 assert(CombinedMask1[I] == PoisonMaskElem &&(static_cast <bool> (CombinedMask1[I] == PoisonMaskElem
&& "Expected undefined mask element") ? void (0) : __assert_fail
("CombinedMask1[I] == PoisonMaskElem && \"Expected undefined mask element\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6696, __extension__
__PRETTY_FUNCTION__))
6696 "Expected undefined mask element")(static_cast <bool> (CombinedMask1[I] == PoisonMaskElem
&& "Expected undefined mask element") ? void (0) : __assert_fail
("CombinedMask1[I] == PoisonMaskElem && \"Expected undefined mask element\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6696, __extension__
__PRETTY_FUNCTION__))
;
6697 CombinedMask1[I] = CombinedMask2[I] + (Op1 == Op2 ? 0 : VF);
6698 }
6699 }
6700 const int Limit = CombinedMask1.size() * 2;
6701 if (Op1 == Op2 && Limit == 2 * VF &&
6702 all_of(CombinedMask1, [=](int Idx) { return Idx < Limit; }) &&
6703 (ShuffleVectorInst::isIdentityMask(CombinedMask1) ||
6704 (ShuffleVectorInst::isZeroEltSplatMask(CombinedMask1) &&
6705 isa<ShuffleVectorInst>(Op1) &&
6706 cast<ShuffleVectorInst>(Op1)->getShuffleMask() ==
6707 ArrayRef(CombinedMask1))))
6708 return Builder.createIdentity(Op1);
6709 return Builder.createShuffleVector(
6710 Op1, Op1 == Op2 ? PoisonValue::get(Op1->getType()) : Op2,
6711 CombinedMask1);
6712 }
6713 if (isa<PoisonValue>(V1))
6714 return Builder.createPoison(
6715 cast<VectorType>(V1->getType())->getElementType(), Mask.size());
6716 SmallVector<int> NewMask(Mask.begin(), Mask.end());
6717 bool IsIdentity = peekThroughShuffles(V1, NewMask, /*SinglePermute=*/true);
6718 assert(V1 && "Expected non-null value after looking through shuffles.")(static_cast <bool> (V1 && "Expected non-null value after looking through shuffles."
) ? void (0) : __assert_fail ("V1 && \"Expected non-null value after looking through shuffles.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6718, __extension__
__PRETTY_FUNCTION__))
;
6719
6720 if (!IsIdentity)
6721 return Builder.createShuffleVector(V1, NewMask);
6722 return Builder.createIdentity(V1);
6723 }
6724};
6725} // namespace
6726
6727/// Merges shuffle masks and emits final shuffle instruction, if required. It
6728/// supports shuffling of 2 input vectors. It implements lazy shuffles emission,
6729/// when the actual shuffle instruction is generated only if this is actually
6730/// required. Otherwise, the shuffle instruction emission is delayed till the
6731/// end of the process, to reduce the number of emitted instructions and further
6732/// analysis/transformations.
6733class BoUpSLP::ShuffleCostEstimator : public BaseShuffleAnalysis {
6734 bool IsFinalized = false;
6735 SmallVector<int> CommonMask;
6736 SmallVector<PointerUnion<Value *, const TreeEntry *> , 2> InVectors;
6737 const TargetTransformInfo &TTI;
6738 InstructionCost Cost = 0;
6739 ArrayRef<Value *> VectorizedVals;
6740 BoUpSLP &R;
6741 SmallPtrSetImpl<Value *> &CheckedExtracts;
6742 constexpr static TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6743
6744 InstructionCost getBuildVectorCost(ArrayRef<Value *> VL, Value *Root) {
6745 if ((!Root && allConstant(VL)) || all_of(VL, UndefValue::classof))
6746 return TTI::TCC_Free;
6747 auto *VecTy = FixedVectorType::get(VL.front()->getType(), VL.size());
6748 InstructionCost GatherCost = 0;
6749 SmallVector<Value *> Gathers(VL.begin(), VL.end());
6750 // Improve gather cost for gather of loads, if we can group some of the
6751 // loads into vector loads.
6752 InstructionsState S = getSameOpcode(VL, *R.TLI);
6753 if (VL.size() > 2 && S.getOpcode() == Instruction::Load &&
6754 !S.isAltShuffle() &&
6755 !all_of(Gathers, [&](Value *V) { return R.getTreeEntry(V); }) &&
6756 !isSplat(Gathers)) {
6757 BoUpSLP::ValueSet VectorizedLoads;
6758 unsigned StartIdx = 0;
6759 unsigned VF = VL.size() / 2;
6760 unsigned VectorizedCnt = 0;
6761 unsigned ScatterVectorizeCnt = 0;
6762 const unsigned Sz = R.DL->getTypeSizeInBits(S.MainOp->getType());
6763 for (unsigned MinVF = R.getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
6764 for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
6765 Cnt += VF) {
6766 ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
6767 if (!VectorizedLoads.count(Slice.front()) &&
6768 !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
6769 SmallVector<Value *> PointerOps;
6770 OrdersType CurrentOrder;
6771 LoadsState LS =
6772 canVectorizeLoads(Slice, Slice.front(), TTI, *R.DL, *R.SE,
6773 *R.LI, *R.TLI, CurrentOrder, PointerOps);
6774 switch (LS) {
6775 case LoadsState::Vectorize:
6776 case LoadsState::ScatterVectorize:
6777 // Mark the vectorized loads so that we don't vectorize them
6778 // again.
6779 if (LS == LoadsState::Vectorize)
6780 ++VectorizedCnt;
6781 else
6782 ++ScatterVectorizeCnt;
6783 VectorizedLoads.insert(Slice.begin(), Slice.end());
6784 // If we vectorized initial block, no need to try to vectorize
6785 // it again.
6786 if (Cnt == StartIdx)
6787 StartIdx += VF;
6788 break;
6789 case LoadsState::Gather:
6790 break;
6791 }
6792 }
6793 }
6794 // Check if the whole array was vectorized already - exit.
6795 if (StartIdx >= VL.size())
6796 break;
6797 // Found vectorizable parts - exit.
6798 if (!VectorizedLoads.empty())
6799 break;
6800 }
6801 if (!VectorizedLoads.empty()) {
6802 unsigned NumParts = TTI.getNumberOfParts(VecTy);
6803 bool NeedInsertSubvectorAnalysis =
6804 !NumParts || (VL.size() / VF) > NumParts;
6805 // Get the cost for gathered loads.
6806 for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
6807 if (VectorizedLoads.contains(VL[I]))
6808 continue;
6809 GatherCost += getBuildVectorCost(VL.slice(I, VF), Root);
6810 }
6811 // Exclude potentially vectorized loads from list of gathered
6812 // scalars.
6813 auto *LI = cast<LoadInst>(S.MainOp);
6814 Gathers.assign(Gathers.size(), PoisonValue::get(LI->getType()));
6815 // The cost for vectorized loads.
6816 InstructionCost ScalarsCost = 0;
6817 for (Value *V : VectorizedLoads) {
6818 auto *LI = cast<LoadInst>(V);
6819 ScalarsCost +=
6820 TTI.getMemoryOpCost(Instruction::Load, LI->getType(),
6821 LI->getAlign(), LI->getPointerAddressSpace(),
6822 CostKind, TTI::OperandValueInfo(), LI);
6823 }
6824 auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
6825 Align Alignment = LI->getAlign();
6826 GatherCost +=
6827 VectorizedCnt *
6828 TTI.getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
6829 LI->getPointerAddressSpace(), CostKind,
6830 TTI::OperandValueInfo(), LI);
6831 GatherCost += ScatterVectorizeCnt *
6832 TTI.getGatherScatterOpCost(
6833 Instruction::Load, LoadTy, LI->getPointerOperand(),
6834 /*VariableMask=*/false, Alignment, CostKind, LI);
6835 if (NeedInsertSubvectorAnalysis) {
6836 // Add the cost for the subvectors insert.
6837 for (int I = VF, E = VL.size(); I < E; I += VF)
6838 GatherCost += TTI.getShuffleCost(TTI::SK_InsertSubvector, VecTy,
6839 std::nullopt, CostKind, I, LoadTy);
6840 }
6841 GatherCost -= ScalarsCost;
6842 }
6843 } else if (!Root && isSplat(VL)) {
6844 // Found the broadcasting of the single scalar, calculate the cost as
6845 // the broadcast.
6846 const auto *It =
6847 find_if(VL, [](Value *V) { return !isa<UndefValue>(V); });
6848 assert(It != VL.end() && "Expected at least one non-undef value.")(static_cast <bool> (It != VL.end() && "Expected at least one non-undef value."
) ? void (0) : __assert_fail ("It != VL.end() && \"Expected at least one non-undef value.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6848, __extension__
__PRETTY_FUNCTION__))
;
6849 // Add broadcast for non-identity shuffle only.
6850 bool NeedShuffle =
6851 count(VL, *It) > 1 &&
6852 (VL.front() != *It || !all_of(VL.drop_front(), UndefValue::classof));
6853 InstructionCost InsertCost = TTI.getVectorInstrCost(
6854 Instruction::InsertElement, VecTy, CostKind,
6855 NeedShuffle ? 0 : std::distance(VL.begin(), It),
6856 PoisonValue::get(VecTy), *It);
6857 return InsertCost +
6858 (NeedShuffle ? TTI.getShuffleCost(
6859 TargetTransformInfo::SK_Broadcast, VecTy,
6860 /*Mask=*/std::nullopt, CostKind, /*Index=*/0,
6861 /*SubTp=*/nullptr, /*Args=*/*It)
6862 : TTI::TCC_Free);
6863 }
6864 return GatherCost +
6865 (all_of(Gathers, UndefValue::classof)
6866 ? TTI::TCC_Free
6867 : R.getGatherCost(Gathers, !Root && VL.equals(Gathers)));
6868 };
6869
6870 /// Compute the cost of creating a vector of type \p VecTy containing the
6871 /// extracted values from \p VL.
6872 InstructionCost computeExtractCost(ArrayRef<Value *> VL, ArrayRef<int> Mask,
6873 TTI::ShuffleKind ShuffleKind) {
6874 auto *VecTy = FixedVectorType::get(VL.front()->getType(), VL.size());
6875 unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
6876
6877 if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc ||
6878 !NumOfParts || VecTy->getNumElements() < NumOfParts)
6879 return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
6880
6881 bool AllConsecutive = true;
6882 unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
6883 unsigned Idx = -1;
6884 InstructionCost Cost = 0;
6885
6886 // Process extracts in blocks of EltsPerVector to check if the source vector
6887 // operand can be re-used directly. If not, add the cost of creating a
6888 // shuffle to extract the values into a vector register.
6889 SmallVector<int> RegMask(EltsPerVector, PoisonMaskElem);
6890 for (auto *V : VL) {
6891 ++Idx;
6892
6893 // Reached the start of a new vector registers.
6894 if (Idx % EltsPerVector == 0) {
6895 RegMask.assign(EltsPerVector, PoisonMaskElem);
6896 AllConsecutive = true;
6897 continue;
6898 }
6899
6900 // Need to exclude undefs from analysis.
6901 if (isa<UndefValue>(V) || Mask[Idx] == PoisonMaskElem)
6902 continue;
6903
6904 // Check all extracts for a vector register on the target directly
6905 // extract values in order.
6906 unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
6907 if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != PoisonMaskElem) {
6908 unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
6909 AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
6910 CurrentIdx % EltsPerVector == Idx % EltsPerVector;
6911 RegMask[Idx % EltsPerVector] = CurrentIdx % EltsPerVector;
6912 }
6913
6914 if (AllConsecutive)
6915 continue;
6916
6917 // Skip all indices, except for the last index per vector block.
6918 if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
6919 continue;
6920
6921 // If we have a series of extracts which are not consecutive and hence
6922 // cannot re-use the source vector register directly, compute the shuffle
6923 // cost to extract the vector with EltsPerVector elements.
6924 Cost += TTI.getShuffleCost(
6925 TargetTransformInfo::SK_PermuteSingleSrc,
6926 FixedVectorType::get(VecTy->getElementType(), EltsPerVector),
6927 RegMask);
6928 }
6929 return Cost;
6930 }
6931
6932 class ShuffleCostBuilder {
6933 const TargetTransformInfo &TTI;
6934
6935 static bool isEmptyOrIdentity(ArrayRef<int> Mask, unsigned VF) {
6936 int Limit = 2 * VF;
6937 return Mask.empty() ||
6938 (VF == Mask.size() &&
6939 all_of(Mask, [Limit](int Idx) { return Idx < Limit; }) &&
6940 ShuffleVectorInst::isIdentityMask(Mask));
6941 }
6942
6943 public:
6944 ShuffleCostBuilder(const TargetTransformInfo &TTI) : TTI(TTI) {}
6945 ~ShuffleCostBuilder() = default;
6946 InstructionCost createShuffleVector(Value *V1, Value *,
6947 ArrayRef<int> Mask) const {
6948 // Empty mask or identity mask are free.
6949 unsigned VF =
6950 cast<VectorType>(V1->getType())->getElementCount().getKnownMinValue();
6951 if (isEmptyOrIdentity(Mask, VF))
6952 return TTI::TCC_Free;
6953 return TTI.getShuffleCost(
6954 TTI::SK_PermuteTwoSrc,
6955 FixedVectorType::get(
6956 cast<VectorType>(V1->getType())->getElementType(), Mask.size()),
6957 Mask);
6958 }
6959 InstructionCost createShuffleVector(Value *V1, ArrayRef<int> Mask) const {
6960 // Empty mask or identity mask are free.
6961 if (isEmptyOrIdentity(Mask, Mask.size()))
6962 return TTI::TCC_Free;
6963 return TTI.getShuffleCost(
6964 TTI::SK_PermuteSingleSrc,
6965 FixedVectorType::get(
6966 cast<VectorType>(V1->getType())->getElementType(), Mask.size()),
6967 Mask);
6968 }
6969 InstructionCost createIdentity(Value *) const { return TTI::TCC_Free; }
6970 InstructionCost createPoison(Type *Ty, unsigned VF) const {
6971 return TTI::TCC_Free;
6972 }
6973 void resizeToMatch(Value *&, Value *&) const {}
6974 };
6975
6976 /// Smart shuffle instruction emission, walks through shuffles trees and
6977 /// tries to find the best matching vector for the actual shuffle
6978 /// instruction.
6979 InstructionCost
6980 createShuffle(const PointerUnion<Value *, const TreeEntry *> &P1,
6981 const PointerUnion<Value *, const TreeEntry *> &P2,
6982 ArrayRef<int> Mask) {
6983 ShuffleCostBuilder Builder(TTI);
6984 Value *V1 = P1.dyn_cast<Value *>(), *V2 = P2.dyn_cast<Value *>();
6985 unsigned CommonVF = 0;
6986 if (!V1) {
6987 const TreeEntry *E = P1.get<const TreeEntry *>();
6988 unsigned VF = E->getVectorFactor();
6989 if (V2) {
6990 unsigned V2VF = cast<FixedVectorType>(V2->getType())->getNumElements();
6991 if (V2VF != VF && V2VF == E->Scalars.size())
6992 VF = E->Scalars.size();
6993 } else if (!P2.isNull()) {
6994 const TreeEntry *E2 = P2.get<const TreeEntry *>();
6995 if (E->Scalars.size() == E2->Scalars.size())
6996 CommonVF = VF = E->Scalars.size();
6997 }
6998 V1 = Constant::getNullValue(
6999 FixedVectorType::get(E->Scalars.front()->getType(), VF));
7000 }
7001 if (!V2 && !P2.isNull()) {
7002 const TreeEntry *E = P2.get<const TreeEntry *>();
7003 unsigned VF = E->getVectorFactor();
7004 unsigned V1VF = cast<FixedVectorType>(V1->getType())->getNumElements();
7005 if (!CommonVF && V1VF == E->Scalars.size())
7006 CommonVF = E->Scalars.size();
7007 if (CommonVF)
7008 VF = CommonVF;
7009 V2 = Constant::getNullValue(
7010 FixedVectorType::get(E->Scalars.front()->getType(), VF));
7011 }
7012 return BaseShuffleAnalysis::createShuffle<InstructionCost>(V1, V2, Mask,
7013 Builder);
7014 }
7015
7016public:
7017 ShuffleCostEstimator(TargetTransformInfo &TTI,
7018 ArrayRef<Value *> VectorizedVals, BoUpSLP &R,
7019 SmallPtrSetImpl<Value *> &CheckedExtracts)
7020 : TTI(TTI), VectorizedVals(VectorizedVals), R(R),
7021 CheckedExtracts(CheckedExtracts) {}
7022 Value *adjustExtracts(const TreeEntry *E, ArrayRef<int> Mask,
7023 TTI::ShuffleKind ShuffleKind) {
7024 if (Mask.empty())
7025 return nullptr;
7026 Value *VecBase = nullptr;
7027 ArrayRef<Value *> VL = E->Scalars;
7028 auto *VecTy = FixedVectorType::get(VL.front()->getType(), VL.size());
7029 // If the resulting type is scalarized, do not adjust the cost.
7030 unsigned VecNumParts = TTI.getNumberOfParts(VecTy);
7031 if (VecNumParts == VecTy->getNumElements()) {
7032 InVectors.assign(1, E);
7033 return nullptr;
7034 }
7035 DenseMap<Value *, int> ExtractVectorsTys;
7036 for (auto [I, V] : enumerate(VL)) {
7037 // Ignore non-extractelement scalars.
7038 if (isa<UndefValue>(V) || (!Mask.empty() && Mask[I] == PoisonMaskElem))
7039 continue;
7040 // If all users of instruction are going to be vectorized and this
7041 // instruction itself is not going to be vectorized, consider this
7042 // instruction as dead and remove its cost from the final cost of the
7043 // vectorized tree.
7044 // Also, avoid adjusting the cost for extractelements with multiple uses
7045 // in different graph entries.
7046 const TreeEntry *VE = R.getTreeEntry(V);
7047 if (!CheckedExtracts.insert(V).second ||
7048 !R.areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
7049 (VE && VE != E))
7050 continue;
7051 auto *EE = cast<ExtractElementInst>(V);
7052 VecBase = EE->getVectorOperand();
7053 std::optional<unsigned> EEIdx = getExtractIndex(EE);
7054 if (!EEIdx)
7055 continue;
7056 unsigned Idx = *EEIdx;
7057 if (VecNumParts != TTI.getNumberOfParts(EE->getVectorOperandType())) {
7058 auto It =
7059 ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
7060 It->getSecond() = std::min<int>(It->second, Idx);
7061 }
7062 // Take credit for instruction that will become dead.
7063 if (EE->hasOneUse()) {
7064 Instruction *Ext = EE->user_back();
7065 if (isa<SExtInst, ZExtInst>(Ext) && all_of(Ext->users(), [](User *U) {
7066 return isa<GetElementPtrInst>(U);
7067 })) {
7068 // Use getExtractWithExtendCost() to calculate the cost of
7069 // extractelement/ext pair.
7070 Cost -= TTI.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
7071 EE->getVectorOperandType(), Idx);
7072 // Add back the cost of s|zext which is subtracted separately.
7073 Cost += TTI.getCastInstrCost(
7074 Ext->getOpcode(), Ext->getType(), EE->getType(),
7075 TTI::getCastContextHint(Ext), CostKind, Ext);
7076 continue;
7077 }
7078 }
7079 Cost -= TTI.getVectorInstrCost(*EE, EE->getVectorOperandType(), CostKind,
7080 Idx);
7081 }
7082 // Add a cost for subvector extracts/inserts if required.
7083 for (const auto &Data : ExtractVectorsTys) {
7084 auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
7085 unsigned NumElts = VecTy->getNumElements();
7086 if (Data.second % NumElts == 0)
7087 continue;
7088 if (TTI.getNumberOfParts(EEVTy) > VecNumParts) {
7089 unsigned Idx = (Data.second / NumElts) * NumElts;
7090 unsigned EENumElts = EEVTy->getNumElements();
7091 if (Idx % NumElts == 0)
7092 continue;
7093 if (Idx + NumElts <= EENumElts) {
7094 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
7095 EEVTy, std::nullopt, CostKind, Idx, VecTy);
7096 } else {
7097 // Need to round up the subvector type vectorization factor to avoid a
7098 // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
7099 // <= EENumElts.
7100 auto *SubVT =
7101 FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
7102 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
7103 EEVTy, std::nullopt, CostKind, Idx, SubVT);
7104 }
7105 } else {
7106 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
7107 VecTy, std::nullopt, CostKind, 0, EEVTy);
7108 }
7109 }
7110 // Check that gather of extractelements can be represented as just a
7111 // shuffle of a single/two vectors the scalars are extracted from.
7112 // Found the bunch of extractelement instructions that must be gathered
7113 // into a vector and can be represented as a permutation elements in a
7114 // single input vector or of 2 input vectors.
7115 Cost += computeExtractCost(VL, Mask, ShuffleKind);
7116 InVectors.assign(1, E);
7117 return VecBase;
7118 }
7119 void add(const TreeEntry *E1, const TreeEntry *E2, ArrayRef<int> Mask) {
7120 CommonMask.assign(Mask.begin(), Mask.end());
7121 InVectors.assign({E1, E2});
7122 }
7123 void add(const TreeEntry *E1, ArrayRef<int> Mask) {
7124 CommonMask.assign(Mask.begin(), Mask.end());
7125 InVectors.assign(1, E1);
7126 }
7127 void gather(ArrayRef<Value *> VL, Value *Root = nullptr) {
7128 Cost += getBuildVectorCost(VL, Root);
7129 if (!Root) {
7130 assert(InVectors.empty() && "Unexpected input vectors for buildvector.")(static_cast <bool> (InVectors.empty() && "Unexpected input vectors for buildvector."
) ? void (0) : __assert_fail ("InVectors.empty() && \"Unexpected input vectors for buildvector.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7130, __extension__
__PRETTY_FUNCTION__))
;
7131 // FIXME: Need to find a way to avoid use of getNullValue here.
7132 InVectors.assign(1, Constant::getNullValue(FixedVectorType::get(
7133 VL.front()->getType(), VL.size())));
7134 }
7135 }
7136 /// Finalize emission of the shuffles.
7137 InstructionCost finalize(ArrayRef<int> ExtMask) {
7138 IsFinalized = true;
7139 ::addMask(CommonMask, ExtMask, /*ExtendingManyInputs=*/true);
7140 if (CommonMask.empty())
7141 return Cost;
7142 int Limit = CommonMask.size() * 2;
7143 if (all_of(CommonMask, [=](int Idx) { return Idx < Limit; }) &&
7144 ShuffleVectorInst::isIdentityMask(CommonMask))
7145 return Cost;
7146 return Cost +
7147 createShuffle(InVectors.front(),
7148 InVectors.size() == 2 ? InVectors.back() : nullptr,
7149 CommonMask);
7150 }
7151
7152 ~ShuffleCostEstimator() {
7153 assert((IsFinalized || CommonMask.empty()) &&(static_cast <bool> ((IsFinalized || CommonMask.empty()
) && "Shuffle construction must be finalized.") ? void
(0) : __assert_fail ("(IsFinalized || CommonMask.empty()) && \"Shuffle construction must be finalized.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7154, __extension__
__PRETTY_FUNCTION__))
7154 "Shuffle construction must be finalized.")(static_cast <bool> ((IsFinalized || CommonMask.empty()
) && "Shuffle construction must be finalized.") ? void
(0) : __assert_fail ("(IsFinalized || CommonMask.empty()) && \"Shuffle construction must be finalized.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7154, __extension__
__PRETTY_FUNCTION__))
;
7155 }
7156};
7157
7158InstructionCost
7159BoUpSLP::getEntryCost(const TreeEntry *E, ArrayRef<Value *> VectorizedVals,
7160 SmallPtrSetImpl<Value *> &CheckedExtracts) {
7161 ArrayRef<Value *> VL = E->Scalars;
7162
7163 Type *ScalarTy = VL[0]->getType();
7164 if (auto *SI = dyn_cast<StoreInst>(VL[0]))
7165 ScalarTy = SI->getValueOperand()->getType();
7166 else if (auto *CI = dyn_cast<CmpInst>(VL[0]))
7167 ScalarTy = CI->getOperand(0)->getType();
7168 else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
7169 ScalarTy = IE->getOperand(1)->getType();
7170 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
7171 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
7172
7173 // If we have computed a smaller type for the expression, update VecTy so
7174 // that the costs will be accurate.
7175 if (MinBWs.count(VL[0]))
7176 VecTy = FixedVectorType::get(
7177 IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
7178 unsigned EntryVF = E->getVectorFactor();
7179 auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
7180
7181 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
7182 if (E->State == TreeEntry::NeedToGather) {
7183 if (allConstant(VL))
7184 return 0;
7185 if (isa<InsertElementInst>(VL[0]))
7186 return InstructionCost::getInvalid();
7187 ShuffleCostEstimator Estimator(*TTI, VectorizedVals, *this,
7188 CheckedExtracts);
7189 unsigned VF = E->getVectorFactor();
7190 SmallVector<int> ReuseShuffleIndicies(E->ReuseShuffleIndices.begin(),
7191 E->ReuseShuffleIndices.end());
7192 SmallVector<Value *> GatheredScalars(E->Scalars.begin(), E->Scalars.end());
7193 // Build a mask out of the reorder indices and reorder scalars per this
7194 // mask.
7195 SmallVector<int> ReorderMask;
7196 inversePermutation(E->ReorderIndices, ReorderMask);
7197 if (!ReorderMask.empty())
7198 reorderScalars(GatheredScalars, ReorderMask);
7199 SmallVector<int> Mask;
7200 SmallVector<int> ExtractMask;
7201 std::optional<TargetTransformInfo::ShuffleKind> ExtractShuffle;
7202 std::optional<TargetTransformInfo::ShuffleKind> GatherShuffle;
7203 SmallVector<const TreeEntry *> Entries;
7204 Type *ScalarTy = GatheredScalars.front()->getType();
7205 // Check for gathered extracts.
7206 ExtractShuffle = tryToGatherExtractElements(GatheredScalars, ExtractMask);
7207 SmallVector<Value *> IgnoredVals;
7208 if (UserIgnoreList)
7209 IgnoredVals.assign(UserIgnoreList->begin(), UserIgnoreList->end());
7210
7211 bool Resized = false;
7212 if (Value *VecBase = Estimator.adjustExtracts(
7213 E, ExtractMask, ExtractShuffle.value_or(TTI::SK_PermuteTwoSrc)))
7214 if (auto *VecBaseTy = dyn_cast<FixedVectorType>(VecBase->getType()))
7215 if (VF == VecBaseTy->getNumElements() && GatheredScalars.size() != VF) {
7216 Resized = true;
7217 GatheredScalars.append(VF - GatheredScalars.size(),
7218 PoisonValue::get(ScalarTy));
7219 }
7220
7221 // Do not try to look for reshuffled loads for gathered loads (they will be
7222 // handled later), for vectorized scalars, and cases, which are definitely
7223 // not profitable (splats and small gather nodes.)
7224 if (ExtractShuffle || E->getOpcode() != Instruction::Load ||
7225 E->isAltShuffle() ||
7226 all_of(E->Scalars, [this](Value *V) { return getTreeEntry(V); }) ||
7227 isSplat(E->Scalars) ||
7228 (E->Scalars != GatheredScalars && GatheredScalars.size() <= 2))
7229 GatherShuffle = isGatherShuffledEntry(E, GatheredScalars, Mask, Entries);
7230 if (GatherShuffle) {
7231 assert((Entries.size() == 1 || Entries.size() == 2) &&(static_cast <bool> ((Entries.size() == 1 || Entries.size
() == 2) && "Expected shuffle of 1 or 2 entries.") ? void
(0) : __assert_fail ("(Entries.size() == 1 || Entries.size() == 2) && \"Expected shuffle of 1 or 2 entries.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7232, __extension__
__PRETTY_FUNCTION__))
7232 "Expected shuffle of 1 or 2 entries.")(static_cast <bool> ((Entries.size() == 1 || Entries.size
() == 2) && "Expected shuffle of 1 or 2 entries.") ? void
(0) : __assert_fail ("(Entries.size() == 1 || Entries.size() == 2) && \"Expected shuffle of 1 or 2 entries.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7232, __extension__
__PRETTY_FUNCTION__))
;
7233 if (*GatherShuffle == TTI::SK_PermuteSingleSrc &&
7234 Entries.front()->isSame(E->Scalars)) {
7235 // Perfect match in the graph, will reuse the previously vectorized
7236 // node. Cost is 0.
7237 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: perfect diamond match for gather bundle that starts with "
<< *VL.front() << ".\n"; } } while (false)
7238 dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: perfect diamond match for gather bundle that starts with "
<< *VL.front() << ".\n"; } } while (false)
7239 << "SLP: perfect diamond match for gather bundle that starts with "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: perfect diamond match for gather bundle that starts with "
<< *VL.front() << ".\n"; } } while (false)
7240 << *VL.front() << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: perfect diamond match for gather bundle that starts with "
<< *VL.front() << ".\n"; } } while (false)
;
7241 return 0;
7242 }
7243 if (!Resized) {
7244 unsigned VF1 = Entries.front()->getVectorFactor();
7245 unsigned VF2 = Entries.back()->getVectorFactor();
7246 if ((VF == VF1 || VF == VF2) && GatheredScalars.size() != VF)
7247 GatheredScalars.append(VF - GatheredScalars.size(),
7248 PoisonValue::get(ScalarTy));
7249 }
7250 // Remove shuffled elements from list of gathers.
7251 for (int I = 0, Sz = Mask.size(); I < Sz; ++I) {
7252 if (Mask[I] != PoisonMaskElem)
7253 GatheredScalars[I] = PoisonValue::get(ScalarTy);
7254 }
7255 LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: shuffled " << Entries.
size() << " entries for bundle that starts with " <<
*VL.front() << ".\n";; } } while (false)
7256 << " entries for bundle that starts with "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: shuffled " << Entries.
size() << " entries for bundle that starts with " <<
*VL.front() << ".\n";; } } while (false)
7257 << *VL.front() << ".\n";)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: shuffled " << Entries.
size() << " entries for bundle that starts with " <<
*VL.front() << ".\n";; } } while (false)
;
7258 if (Entries.size() == 1)
7259 Estimator.add(Entries.front(), Mask);
7260 else
7261 Estimator.add(Entries.front(), Entries.back(), Mask);
7262 Estimator.gather(
7263 GatheredScalars,
7264 Constant::getNullValue(FixedVectorType::get(
7265 GatheredScalars.front()->getType(), GatheredScalars.size())));
7266 return Estimator.finalize(E->ReuseShuffleIndices);
7267 }
7268 Estimator.gather(
7269 GatheredScalars,
7270 VL.equals(GatheredScalars)
7271 ? nullptr
7272 : Constant::getNullValue(FixedVectorType::get(
7273 GatheredScalars.front()->getType(), GatheredScalars.size())));
7274 return Estimator.finalize(E->ReuseShuffleIndices);
7275 }
7276 InstructionCost CommonCost = 0;
7277 SmallVector<int> Mask;
7278 if (!E->ReorderIndices.empty()) {
7279 SmallVector<int> NewMask;
7280 if (E->getOpcode() == Instruction::Store) {
7281 // For stores the order is actually a mask.
7282 NewMask.resize(E->ReorderIndices.size());
7283 copy(E->ReorderIndices, NewMask.begin());
7284 } else {
7285 inversePermutation(E->ReorderIndices, NewMask);
7286 }
7287 ::addMask(Mask, NewMask);
7288 }
7289 if (NeedToShuffleReuses)
7290 ::addMask(Mask, E->ReuseShuffleIndices);
7291 if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
7292 CommonCost =
7293 TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
7294 assert((E->State == TreeEntry::Vectorize ||(static_cast <bool> ((E->State == TreeEntry::Vectorize
|| E->State == TreeEntry::ScatterVectorize) && "Unhandled state"
) ? void (0) : __assert_fail ("(E->State == TreeEntry::Vectorize || E->State == TreeEntry::ScatterVectorize) && \"Unhandled state\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7296, __extension__
__PRETTY_FUNCTION__))
7295 E->State == TreeEntry::ScatterVectorize) &&(static_cast <bool> ((E->State == TreeEntry::Vectorize
|| E->State == TreeEntry::ScatterVectorize) && "Unhandled state"
) ? void (0) : __assert_fail ("(E->State == TreeEntry::Vectorize || E->State == TreeEntry::ScatterVectorize) && \"Unhandled state\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7296, __extension__
__PRETTY_FUNCTION__))
7296 "Unhandled state")(static_cast <bool> ((E->State == TreeEntry::Vectorize
|| E->State == TreeEntry::ScatterVectorize) && "Unhandled state"
) ? void (0) : __assert_fail ("(E->State == TreeEntry::Vectorize || E->State == TreeEntry::ScatterVectorize) && \"Unhandled state\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7296, __extension__
__PRETTY_FUNCTION__))
;
7297 assert(E->getOpcode() &&(static_cast <bool> (E->getOpcode() && ((allSameType
(VL) && allSameBlock(VL)) || (E->getOpcode() == Instruction
::GetElementPtr && E->getMainOp()->getType()->
isPointerTy())) && "Invalid VL") ? void (0) : __assert_fail
("E->getOpcode() && ((allSameType(VL) && allSameBlock(VL)) || (E->getOpcode() == Instruction::GetElementPtr && E->getMainOp()->getType()->isPointerTy())) && \"Invalid VL\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7301, __extension__
__PRETTY_FUNCTION__))
7298 ((allSameType(VL) && allSameBlock(VL)) ||(static_cast <bool> (E->getOpcode() && ((allSameType
(VL) && allSameBlock(VL)) || (E->getOpcode() == Instruction
::GetElementPtr && E->getMainOp()->getType()->
isPointerTy())) && "Invalid VL") ? void (0) : __assert_fail
("E->getOpcode() && ((allSameType(VL) && allSameBlock(VL)) || (E->getOpcode() == Instruction::GetElementPtr && E->getMainOp()->getType()->isPointerTy())) && \"Invalid VL\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7301, __extension__
__PRETTY_FUNCTION__))
7299 (E->getOpcode() == Instruction::GetElementPtr &&(static_cast <bool> (E->getOpcode() && ((allSameType
(VL) && allSameBlock(VL)) || (E->getOpcode() == Instruction
::GetElementPtr && E->getMainOp()->getType()->
isPointerTy())) && "Invalid VL") ? void (0) : __assert_fail
("E->getOpcode() && ((allSameType(VL) && allSameBlock(VL)) || (E->getOpcode() == Instruction::GetElementPtr && E->getMainOp()->getType()->isPointerTy())) && \"Invalid VL\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7301, __extension__
__PRETTY_FUNCTION__))
7300 E->getMainOp()->getType()->isPointerTy())) &&(static_cast <bool> (E->getOpcode() && ((allSameType
(VL) && allSameBlock(VL)) || (E->getOpcode() == Instruction
::GetElementPtr && E->getMainOp()->getType()->
isPointerTy())) && "Invalid VL") ? void (0) : __assert_fail
("E->getOpcode() && ((allSameType(VL) && allSameBlock(VL)) || (E->getOpcode() == Instruction::GetElementPtr && E->getMainOp()->getType()->isPointerTy())) && \"Invalid VL\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7301, __extension__
__PRETTY_FUNCTION__))
7301 "Invalid VL")(static_cast <bool> (E->getOpcode() && ((allSameType
(VL) && allSameBlock(VL)) || (E->getOpcode() == Instruction
::GetElementPtr && E->getMainOp()->getType()->
isPointerTy())) && "Invalid VL") ? void (0) : __assert_fail
("E->getOpcode() && ((allSameType(VL) && allSameBlock(VL)) || (E->getOpcode() == Instruction::GetElementPtr && E->getMainOp()->getType()->isPointerTy())) && \"Invalid VL\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7301, __extension__
__PRETTY_FUNCTION__))
;
7302 Instruction *VL0 = E->getMainOp();
7303 unsigned ShuffleOrOp =
7304 E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
7305 const unsigned Sz = VL.size();
7306 auto GetCostDiff =
7307 [=](function_ref<InstructionCost(unsigned)> ScalarEltCost,
7308 function_ref<InstructionCost(InstructionCost)> VectorCost) {
7309 // Calculate the cost of this instruction.
7310 InstructionCost ScalarCost = 0;
7311 if (isa<CastInst, CmpInst, SelectInst, CallInst>(VL0)) {
7312 // For some of the instructions no need to calculate cost for each
7313 // particular instruction, we can use the cost of the single
7314 // instruction x total number of scalar instructions.
7315 ScalarCost = Sz * ScalarEltCost(0);
7316 } else {
7317 for (unsigned I = 0; I < Sz; ++I)
7318 ScalarCost += ScalarEltCost(I);
7319 }
7320
7321 InstructionCost VecCost = VectorCost(CommonCost);
7322 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost - CommonCost,do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dumpTreeCosts(E, CommonCost, VecCost - CommonCost,
ScalarCost, "Calculated costs for Tree"); } } while (false)
7323 ScalarCost, "Calculated costs for Tree"))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dumpTreeCosts(E, CommonCost, VecCost - CommonCost,
ScalarCost, "Calculated costs for Tree"); } } while (false)
;
7324 return VecCost - ScalarCost;
7325 };
7326 // Calculate cost difference from vectorizing set of GEPs.
7327 // Negative value means vectorizing is profitable.
7328 auto GetGEPCostDiff = [=](ArrayRef<Value *> Ptrs, Value *BasePtr) {
7329 InstructionCost ScalarCost = 0;
7330 InstructionCost VecCost = 0;
7331 // Here we differentiate two cases: (1) when Ptrs represent a regular
7332 // vectorization tree node (as they are pointer arguments of scattered
7333 // loads) or (2) when Ptrs are the arguments of loads or stores being
7334 // vectorized as plane wide unit-stride load/store since all the
7335 // loads/stores are known to be from/to adjacent locations.
7336 assert(E->State == TreeEntry::Vectorize &&(static_cast <bool> (E->State == TreeEntry::Vectorize
&& "Entry state expected to be Vectorize here.") ? void
(0) : __assert_fail ("E->State == TreeEntry::Vectorize && \"Entry state expected to be Vectorize here.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7337, __extension__
__PRETTY_FUNCTION__))
7337 "Entry state expected to be Vectorize here.")(static_cast <bool> (E->State == TreeEntry::Vectorize
&& "Entry state expected to be Vectorize here.") ? void
(0) : __assert_fail ("E->State == TreeEntry::Vectorize && \"Entry state expected to be Vectorize here.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7337, __extension__
__PRETTY_FUNCTION__))
;
7338 if (isa<LoadInst, StoreInst>(VL0)) {
7339 // Case 2: estimate costs for pointer related costs when vectorizing to
7340 // a wide load/store.
7341 // Scalar cost is estimated as a set of pointers with known relationship
7342 // between them.
7343 // For vector code we will use BasePtr as argument for the wide load/store
7344 // but we also need to account all the instructions which are going to
7345 // stay in vectorized code due to uses outside of these scalar
7346 // loads/stores.
7347 ScalarCost = TTI->getPointersChainCost(
7348 Ptrs, BasePtr, TTI::PointersChainInfo::getKnownUniformStrided(),
7349 CostKind);
7350
7351 SmallVector<const Value *> PtrsRetainedInVecCode;
7352 for (Value *V : Ptrs) {
7353 if (V == BasePtr) {
7354 PtrsRetainedInVecCode.push_back(V);
7355 continue;
7356 }
7357 auto *Ptr = dyn_cast<GetElementPtrInst>(V);
7358 // For simplicity assume Ptr to stay in vectorized code if it's not a
7359 // GEP instruction. We don't care since it's cost considered free.
7360 // TODO: We should check for any uses outside of vectorizable tree
7361 // rather than just single use.
7362 if (!Ptr || !Ptr->hasOneUse())
7363 PtrsRetainedInVecCode.push_back(V);
7364 }
7365
7366 if (PtrsRetainedInVecCode.size() == Ptrs.size()) {
7367 // If all pointers stay in vectorized code then we don't have
7368 // any savings on that.
7369 LLVM_DEBUG(dumpTreeCosts(E, 0, ScalarCost, ScalarCost,do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dumpTreeCosts(E, 0, ScalarCost, ScalarCost, "Calculated GEPs cost for Tree"
); } } while (false)
7370 "Calculated GEPs cost for Tree"))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dumpTreeCosts(E, 0, ScalarCost, ScalarCost, "Calculated GEPs cost for Tree"
); } } while (false)
;
7371 return InstructionCost{TTI::TCC_Free};
7372 }
7373 VecCost = TTI->getPointersChainCost(
7374 PtrsRetainedInVecCode, BasePtr,
7375 TTI::PointersChainInfo::getKnownNonUniformStrided(), CostKind);
7376 } else {
7377 // Case 1: Ptrs are the arguments of loads that we are going to transform
7378 // into masked gather load intrinsic.
7379 // All the scalar GEPs will be removed as a result of vectorization.
7380 // For any external uses of some lanes extract element instructions will
7381 // be generated (which cost is estimated separately).
7382 TTI::PointersChainInfo PtrsInfo =
7383 all_of(Ptrs,
7384 [](const Value *V) {
7385 auto *Ptr = dyn_cast<GetElementPtrInst>(V);
7386 return Ptr && !Ptr->hasAllConstantIndices();
7387 })
7388 ? TTI::PointersChainInfo::getNonUniformStrided()
7389 : TTI::PointersChainInfo::getKnownNonUniformStrided();
7390
7391 ScalarCost = TTI->getPointersChainCost(Ptrs, BasePtr, PtrsInfo, CostKind);
7392
7393 // Remark: it not quite correct to use scalar GEP cost for a vector GEP,
7394 // but it's not clear how to do that without having vector GEP arguments
7395 // ready.
7396 // Perhaps using just TTI::TCC_Free/TTI::TCC_Basic would be better option.
7397 if (const auto *Base = dyn_cast<GetElementPtrInst>(BasePtr)) {
7398 SmallVector<const Value *> Indices(Base->indices());
7399 VecCost = TTI->getGEPCost(Base->getSourceElementType(),
7400 Base->getPointerOperand(), Indices, CostKind);
7401 }
7402 }
7403
7404 LLVM_DEBUG(dumpTreeCosts(E, 0, VecCost, ScalarCost,do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dumpTreeCosts(E, 0, VecCost, ScalarCost, "Calculated GEPs cost for Tree"
); } } while (false)
7405 "Calculated GEPs cost for Tree"))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dumpTreeCosts(E, 0, VecCost, ScalarCost, "Calculated GEPs cost for Tree"
); } } while (false)
;
7406
7407 return VecCost - ScalarCost;
7408 };
7409
7410 switch (ShuffleOrOp) {
7411 case Instruction::PHI: {
7412 // Count reused scalars.
7413 InstructionCost ScalarCost = 0;
7414 SmallPtrSet<const TreeEntry *, 4> CountedOps;
7415 for (Value *V : VL) {
7416 auto *PHI = dyn_cast<PHINode>(V);
7417 if (!PHI)
7418 continue;
7419
7420 ValueList Operands(PHI->getNumIncomingValues(), nullptr);
7421 for (unsigned I = 0, N = PHI->getNumIncomingValues(); I < N; ++I) {
7422 Value *Op = PHI->getIncomingValue(I);
7423 Operands[I] = Op;
7424 }
7425 if (const TreeEntry *OpTE = getTreeEntry(Operands.front()))
7426 if (OpTE->isSame(Operands) && CountedOps.insert(OpTE).second)
7427 if (!OpTE->ReuseShuffleIndices.empty())
7428 ScalarCost += TTI::TCC_Basic * (OpTE->ReuseShuffleIndices.size() -
7429 OpTE->Scalars.size());
7430 }
7431
7432 return CommonCost - ScalarCost;
7433 }
7434 case Instruction::ExtractValue:
7435 case Instruction::ExtractElement: {
7436 auto GetScalarCost = [=](unsigned Idx) {
7437 auto *I = cast<Instruction>(VL[Idx]);
7438 VectorType *SrcVecTy;
7439 if (ShuffleOrOp == Instruction::ExtractElement) {
7440 auto *EE = cast<ExtractElementInst>(I);
7441 SrcVecTy = EE->getVectorOperandType();
7442 } else {
7443 auto *EV = cast<ExtractValueInst>(I);
7444 Type *AggregateTy = EV->getAggregateOperand()->getType();
7445 unsigned NumElts;
7446 if (auto *ATy = dyn_cast<ArrayType>(AggregateTy))
7447 NumElts = ATy->getNumElements();
7448 else
7449 NumElts = AggregateTy->getStructNumElements();
7450 SrcVecTy = FixedVectorType::get(ScalarTy, NumElts);
7451 }
7452 if (I->hasOneUse()) {
7453 Instruction *Ext = I->user_back();
7454 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
7455 all_of(Ext->users(),
7456 [](User *U) { return isa<GetElementPtrInst>(U); })) {
7457 // Use getExtractWithExtendCost() to calculate the cost of
7458 // extractelement/ext pair.
7459 InstructionCost Cost = TTI->getExtractWithExtendCost(
7460 Ext->getOpcode(), Ext->getType(), SrcVecTy, *getExtractIndex(I));
7461 // Subtract the cost of s|zext which is subtracted separately.
7462 Cost -= TTI->getCastInstrCost(
7463 Ext->getOpcode(), Ext->getType(), I->getType(),
7464 TTI::getCastContextHint(Ext), CostKind, Ext);
7465 return Cost;
7466 }
7467 }
7468 return TTI->getVectorInstrCost(Instruction::ExtractElement, SrcVecTy,
7469 CostKind, *getExtractIndex(I));
7470 };
7471 auto GetVectorCost = [](InstructionCost CommonCost) { return CommonCost; };
7472 return GetCostDiff(GetScalarCost, GetVectorCost);
7473 }
7474 case Instruction::InsertElement: {
7475 assert(E->ReuseShuffleIndices.empty() &&(static_cast <bool> (E->ReuseShuffleIndices.empty() &&
"Unique insertelements only are expected.") ? void (0) : __assert_fail
("E->ReuseShuffleIndices.empty() && \"Unique insertelements only are expected.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7476, __extension__
__PRETTY_FUNCTION__))
7476 "Unique insertelements only are expected.")(static_cast <bool> (E->ReuseShuffleIndices.empty() &&
"Unique insertelements only are expected.") ? void (0) : __assert_fail
("E->ReuseShuffleIndices.empty() && \"Unique insertelements only are expected.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7476, __extension__
__PRETTY_FUNCTION__))
;
7477 auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
7478 unsigned const NumElts = SrcVecTy->getNumElements();
7479 unsigned const NumScalars = VL.size();
7480
7481 unsigned NumOfParts = TTI->getNumberOfParts(SrcVecTy);
7482
7483 SmallVector<int> InsertMask(NumElts, PoisonMaskElem);
7484 unsigned OffsetBeg = *getInsertIndex(VL.front());
7485 unsigned OffsetEnd = OffsetBeg;
7486 InsertMask[OffsetBeg] = 0;
7487 for (auto [I, V] : enumerate(VL.drop_front())) {
7488 unsigned Idx = *getInsertIndex(V);
7489 if (OffsetBeg > Idx)
7490 OffsetBeg = Idx;
7491 else if (OffsetEnd < Idx)
7492 OffsetEnd = Idx;
7493 InsertMask[Idx] = I + 1;
7494 }
7495 unsigned VecScalarsSz = PowerOf2Ceil(NumElts);
7496 if (NumOfParts > 0)
7497 VecScalarsSz = PowerOf2Ceil((NumElts + NumOfParts - 1) / NumOfParts);
7498 unsigned VecSz = (1 + OffsetEnd / VecScalarsSz - OffsetBeg / VecScalarsSz) *
7499 VecScalarsSz;
7500 unsigned Offset = VecScalarsSz * (OffsetBeg / VecScalarsSz);
7501 unsigned InsertVecSz = std::min<unsigned>(
7502 PowerOf2Ceil(OffsetEnd - OffsetBeg + 1),
7503 ((OffsetEnd - OffsetBeg + VecScalarsSz) / VecScalarsSz) * VecScalarsSz);
7504 bool IsWholeSubvector =
7505 OffsetBeg == Offset && ((OffsetEnd + 1) % VecScalarsSz == 0);
7506 // Check if we can safely insert a subvector. If it is not possible, just
7507 // generate a whole-sized vector and shuffle the source vector and the new
7508 // subvector.
7509 if (OffsetBeg + InsertVecSz > VecSz) {
7510 // Align OffsetBeg to generate correct mask.
7511 OffsetBeg = alignDown(OffsetBeg, VecSz, Offset);
7512 InsertVecSz = VecSz;
7513 }
7514
7515 APInt DemandedElts = APInt::getZero(NumElts);
7516 // TODO: Add support for Instruction::InsertValue.
7517 SmallVector<int> Mask;
7518 if (!E->ReorderIndices.empty()) {
7519 inversePermutation(E->ReorderIndices, Mask);
7520 Mask.append(InsertVecSz - Mask.size(), PoisonMaskElem);
7521 } else {
7522 Mask.assign(VecSz, PoisonMaskElem);
7523 std::iota(Mask.begin(), std::next(Mask.begin(), InsertVecSz), 0);
7524 }
7525 bool IsIdentity = true;
7526 SmallVector<int> PrevMask(InsertVecSz, PoisonMaskElem);
7527 Mask.swap(PrevMask);
7528 for (unsigned I = 0; I < NumScalars; ++I) {
7529 unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
7530 DemandedElts.setBit(InsertIdx);
7531 IsIdentity &= InsertIdx - OffsetBeg == I;
7532 Mask[InsertIdx - OffsetBeg] = I;
7533 }
7534 assert(Offset < NumElts && "Failed to find vector index offset")(static_cast <bool> (Offset < NumElts && "Failed to find vector index offset"
) ? void (0) : __assert_fail ("Offset < NumElts && \"Failed to find vector index offset\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7534, __extension__
__PRETTY_FUNCTION__))
;
7535
7536 InstructionCost Cost = 0;
7537 Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
7538 /*Insert*/ true, /*Extract*/ false,
7539 CostKind);
7540
7541 // First cost - resize to actual vector size if not identity shuffle or
7542 // need to shift the vector.
7543 // Do not calculate the cost if the actual size is the register size and
7544 // we can merge this shuffle with the following SK_Select.
7545 auto *InsertVecTy =
7546 FixedVectorType::get(SrcVecTy->getElementType(), InsertVecSz);
7547 if (!IsIdentity)
7548 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
7549 InsertVecTy, Mask);
7550 auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
7551 return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
7552 }));
7553 // Second cost - permutation with subvector, if some elements are from the
7554 // initial vector or inserting a subvector.
7555 // TODO: Implement the analysis of the FirstInsert->getOperand(0)
7556 // subvector of ActualVecTy.
7557 SmallBitVector InMask =
7558 isUndefVector(FirstInsert->getOperand(0),
7559 buildUseMask(NumElts, InsertMask, UseMask::UndefsAsMask));
7560 if (!InMask.all() && NumScalars != NumElts && !IsWholeSubvector) {
7561 if (InsertVecSz != VecSz) {
7562 auto *ActualVecTy =
7563 FixedVectorType::get(SrcVecTy->getElementType(), VecSz);
7564 Cost += TTI->getShuffleCost(TTI::SK_InsertSubvector, ActualVecTy,
7565 std::nullopt, CostKind, OffsetBeg - Offset,
7566 InsertVecTy);
7567 } else {
7568 for (unsigned I = 0, End = OffsetBeg - Offset; I < End; ++I)
7569 Mask[I] = InMask.test(I) ? PoisonMaskElem : I;
7570 for (unsigned I = OffsetBeg - Offset, End = OffsetEnd - Offset;
7571 I <= End; ++I)
7572 if (Mask[I] != PoisonMaskElem)
7573 Mask[I] = I + VecSz;
7574 for (unsigned I = OffsetEnd + 1 - Offset; I < VecSz; ++I)
7575 Mask[I] =
7576 ((I >= InMask.size()) || InMask.test(I)) ? PoisonMaskElem : I;
7577 Cost += TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, InsertVecTy, Mask);
7578 }
7579 }
7580 return Cost;
7581 }
7582 case Instruction::ZExt:
7583 case Instruction::SExt:
7584 case Instruction::FPToUI:
7585 case Instruction::FPToSI:
7586 case Instruction::FPExt:
7587 case Instruction::PtrToInt:
7588 case Instruction::IntToPtr:
7589 case Instruction::SIToFP:
7590 case Instruction::UIToFP:
7591 case Instruction::Trunc:
7592 case Instruction::FPTrunc:
7593 case Instruction::BitCast: {
7594 auto GetScalarCost = [=](unsigned Idx) {
7595 auto *VI = cast<Instruction>(VL[Idx]);
7596 return TTI->getCastInstrCost(E->getOpcode(), ScalarTy,
7597 VI->getOperand(0)->getType(),
7598 TTI::getCastContextHint(VI), CostKind, VI);
7599 };
7600 auto GetVectorCost = [=](InstructionCost CommonCost) {
7601 Type *SrcTy = VL0->getOperand(0)->getType();
7602 auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
7603 InstructionCost VecCost = CommonCost;
7604 // Check if the values are candidates to demote.
7605 if (!MinBWs.count(VL0) || VecTy != SrcVecTy)
7606 VecCost +=
7607 TTI->getCastInstrCost(E->getOpcode(), VecTy, SrcVecTy,
7608 TTI::getCastContextHint(VL0), CostKind, VL0);
7609 return VecCost;
7610 };
7611 return GetCostDiff(GetScalarCost, GetVectorCost);
7612 }
7613 case Instruction::FCmp:
7614 case Instruction::ICmp:
7615 case Instruction::Select: {
7616 CmpInst::Predicate VecPred, SwappedVecPred;
7617 auto MatchCmp = m_Cmp(VecPred, m_Value(), m_Value());
7618 if (match(VL0, m_Select(MatchCmp, m_Value(), m_Value())) ||
7619 match(VL0, MatchCmp))
7620 SwappedVecPred = CmpInst::getSwappedPredicate(VecPred);
7621 else
7622 SwappedVecPred = VecPred = ScalarTy->isFloatingPointTy()
7623 ? CmpInst::BAD_FCMP_PREDICATE
7624 : CmpInst::BAD_ICMP_PREDICATE;
7625 auto GetScalarCost = [&](unsigned Idx) {
7626 auto *VI = cast<Instruction>(VL[Idx]);
7627 CmpInst::Predicate CurrentPred = ScalarTy->isFloatingPointTy()
7628 ? CmpInst::BAD_FCMP_PREDICATE
7629 : CmpInst::BAD_ICMP_PREDICATE;
7630 auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
7631 if ((!match(VI, m_Select(MatchCmp, m_Value(), m_Value())) &&
7632 !match(VI, MatchCmp)) ||
7633 (CurrentPred != VecPred && CurrentPred != SwappedVecPred))
7634 VecPred = SwappedVecPred = ScalarTy->isFloatingPointTy()
7635 ? CmpInst::BAD_FCMP_PREDICATE
7636 : CmpInst::BAD_ICMP_PREDICATE;
7637
7638 return TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
7639 Builder.getInt1Ty(), CurrentPred, CostKind,
7640 VI);
7641 };
7642 auto GetVectorCost = [&](InstructionCost CommonCost) {
7643 auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
7644
7645 InstructionCost VecCost = TTI->getCmpSelInstrCost(
7646 E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
7647 // Check if it is possible and profitable to use min/max for selects
7648 // in VL.
7649 //
7650 auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
7651 if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
7652 IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
7653 {VecTy, VecTy});
7654 InstructionCost IntrinsicCost =
7655 TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
7656 // If the selects are the only uses of the compares, they will be
7657 // dead and we can adjust the cost by removing their cost.
7658 if (IntrinsicAndUse.second)
7659 IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
7660 MaskTy, VecPred, CostKind);
7661 VecCost = std::min(VecCost, IntrinsicCost);
7662 }
7663 return VecCost + CommonCost;
7664 };
7665 return GetCostDiff(GetScalarCost, GetVectorCost);
7666 }
7667 case Instruction::FNeg:
7668 case Instruction::Add:
7669 case Instruction::FAdd:
7670 case Instruction::Sub:
7671 case Instruction::FSub:
7672 case Instruction::Mul:
7673 case Instruction::FMul:
7674 case Instruction::UDiv:
7675 case Instruction::SDiv:
7676 case Instruction::FDiv:
7677 case Instruction::URem:
7678 case Instruction::SRem:
7679 case Instruction::FRem:
7680 case Instruction::Shl:
7681 case Instruction::LShr:
7682 case Instruction::AShr:
7683 case Instruction::And:
7684 case Instruction::Or:
7685 case Instruction::Xor: {
7686 auto GetScalarCost = [=](unsigned Idx) {
7687 auto *VI = cast<Instruction>(VL[Idx]);
7688 unsigned OpIdx = isa<UnaryOperator>(VI) ? 0 : 1;
7689 TTI::OperandValueInfo Op1Info = TTI::getOperandInfo(VI->getOperand(0));
7690 TTI::OperandValueInfo Op2Info =
7691 TTI::getOperandInfo(VI->getOperand(OpIdx));
7692 SmallVector<const Value *> Operands(VI->operand_values());
7693 return TTI->getArithmeticInstrCost(ShuffleOrOp, ScalarTy, CostKind,
7694 Op1Info, Op2Info, Operands, VI);
7695 };
7696 auto GetVectorCost = [=](InstructionCost CommonCost) {
7697 unsigned OpIdx = isa<UnaryOperator>(VL0) ? 0 : 1;
7698 TTI::OperandValueInfo Op1Info = getOperandInfo(VL, 0);
7699 TTI::OperandValueInfo Op2Info = getOperandInfo(VL, OpIdx);
7700 return TTI->getArithmeticInstrCost(ShuffleOrOp, VecTy, CostKind, Op1Info,
7701 Op2Info) +
7702 CommonCost;
7703 };
7704 return GetCostDiff(GetScalarCost, GetVectorCost);
7705 }
7706 case Instruction::GetElementPtr: {
7707 return CommonCost + GetGEPCostDiff(VL, VL0);
7708 }
7709 case Instruction::Load: {
7710 auto GetScalarCost = [=](unsigned Idx) {
7711 auto *VI = cast<LoadInst>(VL[Idx]);
7712 return TTI->getMemoryOpCost(Instruction::Load, ScalarTy, VI->getAlign(),
7713 VI->getPointerAddressSpace(), CostKind,
7714 TTI::OperandValueInfo(), VI);
7715 };
7716 auto *LI0 = cast<LoadInst>(VL0);
7717 auto GetVectorCost = [=](InstructionCost CommonCost) {
7718 InstructionCost VecLdCost;
7719 if (E->State == TreeEntry::Vectorize) {
7720 VecLdCost = TTI->getMemoryOpCost(
7721 Instruction::Load, VecTy, LI0->getAlign(),
7722 LI0->getPointerAddressSpace(), CostKind, TTI::OperandValueInfo());
7723 } else {
7724 assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState")(static_cast <bool> (E->State == TreeEntry::ScatterVectorize
&& "Unknown EntryState") ? void (0) : __assert_fail (
"E->State == TreeEntry::ScatterVectorize && \"Unknown EntryState\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7724, __extension__
__PRETTY_FUNCTION__))
;
7725 Align CommonAlignment = LI0->getAlign();
7726 for (Value *V : VL)
7727 CommonAlignment =
7728 std::min(CommonAlignment, cast<LoadInst>(V)->getAlign());
7729 VecLdCost = TTI->getGatherScatterOpCost(
7730 Instruction::Load, VecTy, LI0->getPointerOperand(),
7731 /*VariableMask=*/false, CommonAlignment, CostKind);
7732 }
7733 return VecLdCost + CommonCost;
7734 };
7735
7736 InstructionCost Cost = GetCostDiff(GetScalarCost, GetVectorCost);
7737 // If this node generates masked gather load then it is not a terminal node.
7738 // Hence address operand cost is estimated separately.
7739 if (E->State == TreeEntry::ScatterVectorize)
7740 return Cost;
7741
7742 // Estimate cost of GEPs since this tree node is a terminator.
7743 SmallVector<Value *> PointerOps(VL.size());
7744 for (auto [I, V] : enumerate(VL))
7745 PointerOps[I] = cast<LoadInst>(V)->getPointerOperand();
7746 return Cost + GetGEPCostDiff(PointerOps, LI0->getPointerOperand());
7747 }
7748 case Instruction::Store: {
7749 bool IsReorder = !E->ReorderIndices.empty();
7750 auto GetScalarCost = [=](unsigned Idx) {
7751 auto *VI = cast<StoreInst>(VL[Idx]);
7752 TTI::OperandValueInfo OpInfo = getOperandInfo(VI, 0);
7753 return TTI->getMemoryOpCost(Instruction::Store, ScalarTy, VI->getAlign(),
7754 VI->getPointerAddressSpace(), CostKind,
7755 OpInfo, VI);
7756 };
7757 auto *BaseSI =
7758 cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
7759 auto GetVectorCost = [=](InstructionCost CommonCost) {
7760 // We know that we can merge the stores. Calculate the cost.
7761 TTI::OperandValueInfo OpInfo = getOperandInfo(VL, 0);
7762 return TTI->getMemoryOpCost(Instruction::Store, VecTy, BaseSI->getAlign(),
7763 BaseSI->getPointerAddressSpace(), CostKind,
7764 OpInfo) +
7765 CommonCost;
7766 };
7767 SmallVector<Value *> PointerOps(VL.size());
7768 for (auto [I, V] : enumerate(VL)) {
7769 unsigned Idx = IsReorder ? E->ReorderIndices[I] : I;
7770 PointerOps[Idx] = cast<StoreInst>(V)->getPointerOperand();
7771 }
7772
7773 return GetCostDiff(GetScalarCost, GetVectorCost) +
7774 GetGEPCostDiff(PointerOps, BaseSI->getPointerOperand());
7775 }
7776 case Instruction::Call: {
7777 auto GetScalarCost = [=](unsigned Idx) {
7778 auto *CI = cast<CallInst>(VL[Idx]);
7779 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7780 if (ID != Intrinsic::not_intrinsic) {
7781 IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
7782 return TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
7783 }
7784 return TTI->getCallInstrCost(CI->getCalledFunction(),
7785 CI->getFunctionType()->getReturnType(),
7786 CI->getFunctionType()->params(), CostKind);
7787 };
7788 auto GetVectorCost = [=](InstructionCost CommonCost) {
7789 auto *CI = cast<CallInst>(VL0);
7790 auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7791 return std::min(VecCallCosts.first, VecCallCosts.second) + CommonCost;
7792 };
7793 return GetCostDiff(GetScalarCost, GetVectorCost);
7794 }
7795 case Instruction::ShuffleVector: {
7796 assert(E->isAltShuffle() &&(static_cast <bool> (E->isAltShuffle() && ((
Instruction::isBinaryOp(E->getOpcode()) && Instruction
::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E
->getOpcode()) && Instruction::isCast(E->getAltOpcode
())) || (isa<CmpInst>(VL0) && isa<CmpInst>
(E->getAltOp()))) && "Invalid Shuffle Vector Operand"
) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7802, __extension__
__PRETTY_FUNCTION__))
7797 ((Instruction::isBinaryOp(E->getOpcode()) &&(static_cast <bool> (E->isAltShuffle() && ((
Instruction::isBinaryOp(E->getOpcode()) && Instruction
::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E
->getOpcode()) && Instruction::isCast(E->getAltOpcode
())) || (isa<CmpInst>(VL0) && isa<CmpInst>
(E->getAltOp()))) && "Invalid Shuffle Vector Operand"
) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7802, __extension__
__PRETTY_FUNCTION__))
7798 Instruction::isBinaryOp(E->getAltOpcode())) ||(static_cast <bool> (E->isAltShuffle() && ((
Instruction::isBinaryOp(E->getOpcode()) && Instruction
::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E
->getOpcode()) && Instruction::isCast(E->getAltOpcode
())) || (isa<CmpInst>(VL0) && isa<CmpInst>
(E->getAltOp()))) && "Invalid Shuffle Vector Operand"
) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7802, __extension__
__PRETTY_FUNCTION__))
7799 (Instruction::isCast(E->getOpcode()) &&(static_cast <bool> (E->isAltShuffle() && ((
Instruction::isBinaryOp(E->getOpcode()) && Instruction
::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E
->getOpcode()) && Instruction::isCast(E->getAltOpcode
())) || (isa<CmpInst>(VL0) && isa<CmpInst>
(E->getAltOp()))) && "Invalid Shuffle Vector Operand"
) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7802, __extension__
__PRETTY_FUNCTION__))
7800 Instruction::isCast(E->getAltOpcode())) ||(static_cast <bool> (E->isAltShuffle() && ((
Instruction::isBinaryOp(E->getOpcode()) && Instruction
::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E
->getOpcode()) && Instruction::isCast(E->getAltOpcode
())) || (isa<CmpInst>(VL0) && isa<CmpInst>
(E->getAltOp()))) && "Invalid Shuffle Vector Operand"
) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7802, __extension__
__PRETTY_FUNCTION__))
7801 (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&(static_cast <bool> (E->isAltShuffle() && ((
Instruction::isBinaryOp(E->getOpcode()) && Instruction
::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E
->getOpcode()) && Instruction::isCast(E->getAltOpcode
())) || (isa<CmpInst>(VL0) && isa<CmpInst>
(E->getAltOp()))) && "Invalid Shuffle Vector Operand"
) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7802, __extension__
__PRETTY_FUNCTION__))
7802 "Invalid Shuffle Vector Operand")(static_cast <bool> (E->isAltShuffle() && ((
Instruction::isBinaryOp(E->getOpcode()) && Instruction
::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E
->getOpcode()) && Instruction::isCast(E->getAltOpcode
())) || (isa<CmpInst>(VL0) && isa<CmpInst>
(E->getAltOp()))) && "Invalid Shuffle Vector Operand"
) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7802, __extension__
__PRETTY_FUNCTION__))
;
7803 // Try to find the previous shuffle node with the same operands and same
7804 // main/alternate ops.
7805 auto TryFindNodeWithEqualOperands = [=]() {
7806 for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
7807 if (TE.get() == E)
7808 break;
7809 if (TE->isAltShuffle() &&
7810 ((TE->getOpcode() == E->getOpcode() &&
7811 TE->getAltOpcode() == E->getAltOpcode()) ||
7812 (TE->getOpcode() == E->getAltOpcode() &&
7813 TE->getAltOpcode() == E->getOpcode())) &&
7814 TE->hasEqualOperands(*E))
7815 return true;
7816 }
7817 return false;
7818 };
7819 auto GetScalarCost = [=](unsigned Idx) {
7820 auto *VI = cast<Instruction>(VL[Idx]);
7821 assert(E->isOpcodeOrAlt(VI) && "Unexpected main/alternate opcode")(static_cast <bool> (E->isOpcodeOrAlt(VI) &&
"Unexpected main/alternate opcode") ? void (0) : __assert_fail
("E->isOpcodeOrAlt(VI) && \"Unexpected main/alternate opcode\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7821, __extension__
__PRETTY_FUNCTION__))
;
7822 (void)E;
7823 return TTI->getInstructionCost(VI, CostKind);
7824 };
7825 // Need to clear CommonCost since the final shuffle cost is included into
7826 // vector cost.
7827 auto GetVectorCost = [&](InstructionCost) {
7828 // VecCost is equal to sum of the cost of creating 2 vectors
7829 // and the cost of creating shuffle.
7830 InstructionCost VecCost = 0;
7831 if (TryFindNodeWithEqualOperands()) {
7832 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { { dbgs() << "SLP: diamond match for alternate node found.\n"
; E->dump(); }; } } while (false)
7833 dbgs() << "SLP: diamond match for alternate node found.\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { { dbgs() << "SLP: diamond match for alternate node found.\n"
; E->dump(); }; } } while (false)
7834 E->dump();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { { dbgs() << "SLP: diamond match for alternate node found.\n"
; E->dump(); }; } } while (false)
7835 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { { dbgs() << "SLP: diamond match for alternate node found.\n"
; E->dump(); }; } } while (false)
;
7836 // No need to add new vector costs here since we're going to reuse
7837 // same main/alternate vector ops, just do different shuffling.
7838 } else if (Instruction::isBinaryOp(E->getOpcode())) {
7839 VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
7840 VecCost +=
7841 TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy, CostKind);
7842 } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7843 VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
7844 Builder.getInt1Ty(),
7845 CI0->getPredicate(), CostKind, VL0);
7846 VecCost += TTI->getCmpSelInstrCost(
7847 E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
7848 cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
7849 E->getAltOp());
7850 } else {
7851 Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
7852 Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
7853 auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
7854 auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
7855 VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
7856 TTI::CastContextHint::None, CostKind);
7857 VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
7858 TTI::CastContextHint::None, CostKind);
7859 }
7860 if (E->ReuseShuffleIndices.empty()) {
7861 VecCost +=
7862 TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy);
7863 } else {
7864 SmallVector<int> Mask;
7865 buildShuffleEntryMask(
7866 E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7867 [E](Instruction *I) {
7868 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode")(static_cast <bool> (E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"
) ? void (0) : __assert_fail ("E->isOpcodeOrAlt(I) && \"Unexpected main/alternate opcode\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7868, __extension__
__PRETTY_FUNCTION__))
;
7869 return I->getOpcode() == E->getAltOpcode();
7870 },
7871 Mask);
7872 VecCost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc,
7873 FinalVecTy, Mask);
7874 }
7875 return VecCost;
7876 };
7877 return GetCostDiff(GetScalarCost, GetVectorCost);
7878 }
7879 default:
7880 llvm_unreachable("Unknown instruction")::llvm::llvm_unreachable_internal("Unknown instruction", "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 7880)
;
7881 }
7882}
7883
7884bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
7885 LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Check whether the tree with height "
<< VectorizableTree.size() << " is fully vectorizable .\n"
; } } while (false)
7886 << VectorizableTree.size() << " is fully vectorizable .\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Check whether the tree with height "
<< VectorizableTree.size() << " is fully vectorizable .\n"
; } } while (false)
;
7887
7888 auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
7889 SmallVector<int> Mask;
7890 return TE->State == TreeEntry::NeedToGather &&
7891 !any_of(TE->Scalars,
7892 [this](Value *V) { return EphValues.contains(V); }) &&
7893 (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
7894 TE->Scalars.size() < Limit ||
7895 ((TE->getOpcode() == Instruction::ExtractElement ||
7896 all_of(TE->Scalars,
7897 [](Value *V) {
7898 return isa<ExtractElementInst, UndefValue>(V);
7899 })) &&
7900 isFixedVectorShuffle(TE->Scalars, Mask)) ||
7901 (TE->State == TreeEntry::NeedToGather &&
7902 TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
7903 };
7904
7905 // We only handle trees of heights 1 and 2.
7906 if (VectorizableTree.size() == 1 &&
7907 (VectorizableTree[0]->State == TreeEntry::Vectorize ||
7908 (ForReduction &&
7909 AreVectorizableGathers(VectorizableTree[0].get(),
7910 VectorizableTree[0]->Scalars.size()) &&
7911 VectorizableTree[0]->getVectorFactor() > 2)))
7912 return true;
7913
7914 if (VectorizableTree.size() != 2)
7915 return false;
7916
7917 // Handle splat and all-constants stores. Also try to vectorize tiny trees
7918 // with the second gather nodes if they have less scalar operands rather than
7919 // the initial tree element (may be profitable to shuffle the second gather)
7920 // or they are extractelements, which form shuffle.
7921 SmallVector<int> Mask;
7922 if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
7923 AreVectorizableGathers(VectorizableTree[1].get(),
7924 VectorizableTree[0]->Scalars.size()))
7925 return true;
7926
7927 // Gathering cost would be too much for tiny trees.
7928 if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
7929 (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
7930 VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
7931 return false;
7932
7933 return true;
7934}
7935
7936static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
7937 TargetTransformInfo *TTI,
7938 bool MustMatchOrInst) {
7939 // Look past the root to find a source value. Arbitrarily follow the
7940 // path through operand 0 of any 'or'. Also, peek through optional
7941 // shift-left-by-multiple-of-8-bits.
7942 Value *ZextLoad = Root;
7943 const APInt *ShAmtC;
7944 bool FoundOr = false;
7945 while (!isa<ConstantExpr>(ZextLoad) &&
7946 (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
7947 (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
7948 ShAmtC->urem(8) == 0))) {
7949 auto *BinOp = cast<BinaryOperator>(ZextLoad);
7950 ZextLoad = BinOp->getOperand(0);
7951 if (BinOp->getOpcode() == Instruction::Or)
7952 FoundOr = true;
7953 }
7954 // Check if the input is an extended load of the required or/shift expression.
7955 Value *Load;
7956 if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
7957 !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
7958 return false;
7959
7960 // Require that the total load bit width is a legal integer type.
7961 // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
7962 // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
7963 Type *SrcTy = Load->getType();
7964 unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
7965 if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
7966 return false;
7967
7968 // Everything matched - assume that we can fold the whole sequence using
7969 // load combining.
7970 LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Assume load combining for tree starting at "
<< *(cast<Instruction>(Root)) << "\n"; } }
while (false)
7971 << *(cast<Instruction>(Root)) << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Assume load combining for tree starting at "
<< *(cast<Instruction>(Root)) << "\n"; } }
while (false)
;
7972
7973 return true;
7974}
7975
7976bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
7977 if (RdxKind != RecurKind::Or)
7978 return false;
7979
7980 unsigned NumElts = VectorizableTree[0]->Scalars.size();
7981 Value *FirstReduced = VectorizableTree[0]->Scalars[0];
7982 return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
7983 /* MatchOr */ false);
7984}
7985
7986bool BoUpSLP::isLoadCombineCandidate() const {
7987 // Peek through a final sequence of stores and check if all operations are
7988 // likely to be load-combined.
7989 unsigned NumElts = VectorizableTree[0]->Scalars.size();
7990 for (Value *Scalar : VectorizableTree[0]->Scalars) {
7991 Value *X;
7992 if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
7993 !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
7994 return false;
7995 }
7996 return true;
7997}
7998
7999bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
8000 // No need to vectorize inserts of gathered values.
8001 if (VectorizableTree.size() == 2 &&
8002 isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
8003 VectorizableTree[1]->State == TreeEntry::NeedToGather &&
8004 (VectorizableTree[1]->getVectorFactor() <= 2 ||
8005 !(isSplat(VectorizableTree[1]->Scalars) ||
8006 allConstant(VectorizableTree[1]->Scalars))))
8007 return true;
8008
8009 // We can vectorize the tree if its size is greater than or equal to the
8010 // minimum size specified by the MinTreeSize command line option.
8011 if (VectorizableTree.size() >= MinTreeSize)
8012 return false;
8013
8014 // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
8015 // can vectorize it if we can prove it fully vectorizable.
8016 if (isFullyVectorizableTinyTree(ForReduction))
8017 return false;
8018
8019 assert(VectorizableTree.empty()(static_cast <bool> (VectorizableTree.empty() ? ExternalUses
.empty() : true && "We shouldn't have any external users"
) ? void (0) : __assert_fail ("VectorizableTree.empty() ? ExternalUses.empty() : true && \"We shouldn't have any external users\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8021, __extension__
__PRETTY_FUNCTION__))
8020 ? ExternalUses.empty()(static_cast <bool> (VectorizableTree.empty() ? ExternalUses
.empty() : true && "We shouldn't have any external users"
) ? void (0) : __assert_fail ("VectorizableTree.empty() ? ExternalUses.empty() : true && \"We shouldn't have any external users\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8021, __extension__
__PRETTY_FUNCTION__))
8021 : true && "We shouldn't have any external users")(static_cast <bool> (VectorizableTree.empty() ? ExternalUses
.empty() : true && "We shouldn't have any external users"
) ? void (0) : __assert_fail ("VectorizableTree.empty() ? ExternalUses.empty() : true && \"We shouldn't have any external users\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8021, __extension__
__PRETTY_FUNCTION__))
;
8022
8023 // Otherwise, we can't vectorize the tree. It is both tiny and not fully
8024 // vectorizable.
8025 return true;
8026}
8027
8028InstructionCost BoUpSLP::getSpillCost() const {
8029 // Walk from the bottom of the tree to the top, tracking which values are
8030 // live. When we see a call instruction that is not part of our tree,
8031 // query TTI to see if there is a cost to keeping values live over it
8032 // (for example, if spills and fills are required).
8033 unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
8034 InstructionCost Cost = 0;
8035
8036 SmallPtrSet<Instruction*, 4> LiveValues;
8037 Instruction *PrevInst = nullptr;
8038
8039 // The entries in VectorizableTree are not necessarily ordered by their
8040 // position in basic blocks. Collect them and order them by dominance so later
8041 // instructions are guaranteed to be visited first. For instructions in
8042 // different basic blocks, we only scan to the beginning of the block, so
8043 // their order does not matter, as long as all instructions in a basic block
8044 // are grouped together. Using dominance ensures a deterministic order.
8045 SmallVector<Instruction *, 16> OrderedScalars;
8046 for (const auto &TEPtr : VectorizableTree) {
8047 Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
8048 if (!Inst)
8049 continue;
8050 OrderedScalars.push_back(Inst);
8051 }
8052 llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
8053 auto *NodeA = DT->getNode(A->getParent());
8054 auto *NodeB = DT->getNode(B->getParent());
8055 assert(NodeA && "Should only process reachable instructions")(static_cast <bool> (NodeA && "Should only process reachable instructions"
) ? void (0) : __assert_fail ("NodeA && \"Should only process reachable instructions\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8055, __extension__
__PRETTY_FUNCTION__))
;
8056 assert(NodeB && "Should only process reachable instructions")(static_cast <bool> (NodeB && "Should only process reachable instructions"
) ? void (0) : __assert_fail ("NodeB && \"Should only process reachable instructions\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8056, __extension__
__PRETTY_FUNCTION__))
;
8057 assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&(static_cast <bool> ((NodeA == NodeB) == (NodeA->getDFSNumIn
() == NodeB->getDFSNumIn()) && "Different nodes should have different DFS numbers"
) ? void (0) : __assert_fail ("(NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && \"Different nodes should have different DFS numbers\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8058, __extension__
__PRETTY_FUNCTION__))
8058 "Different nodes should have different DFS numbers")(static_cast <bool> ((NodeA == NodeB) == (NodeA->getDFSNumIn
() == NodeB->getDFSNumIn()) && "Different nodes should have different DFS numbers"
) ? void (0) : __assert_fail ("(NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && \"Different nodes should have different DFS numbers\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8058, __extension__
__PRETTY_FUNCTION__))
;
8059 if (NodeA != NodeB)
8060 return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
8061 return B->comesBefore(A);
8062 });
8063
8064 for (Instruction *Inst : OrderedScalars) {
8065 if (!PrevInst) {
8066 PrevInst = Inst;
8067 continue;
8068 }
8069
8070 // Update LiveValues.
8071 LiveValues.erase(PrevInst);
8072 for (auto &J : PrevInst->operands()) {
8073 if (isa<Instruction>(&*J) && getTreeEntry(&*J))
8074 LiveValues.insert(cast<Instruction>(&*J));
8075 }
8076
8077 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { { dbgs() << "SLP: #LV: " << LiveValues
.size(); for (auto *X : LiveValues) dbgs() << " " <<
X->getName(); dbgs() << ", Looking at "; Inst->dump
(); }; } } while (false)
8078 dbgs() << "SLP: #LV: " << LiveValues.size();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { { dbgs() << "SLP: #LV: " << LiveValues
.size(); for (auto *X : LiveValues) dbgs() << " " <<
X->getName(); dbgs() << ", Looking at "; Inst->dump
(); }; } } while (false)
8079 for (auto *X : LiveValues)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { { dbgs() << "SLP: #LV: " << LiveValues
.size(); for (auto *X : LiveValues) dbgs() << " " <<
X->getName(); dbgs() << ", Looking at "; Inst->dump
(); }; } } while (false)
8080 dbgs() << " " << X->getName();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { { dbgs() << "SLP: #LV: " << LiveValues
.size(); for (auto *X : LiveValues) dbgs() << " " <<
X->getName(); dbgs() << ", Looking at "; Inst->dump
(); }; } } while (false)
8081 dbgs() << ", Looking at ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { { dbgs() << "SLP: #LV: " << LiveValues
.size(); for (auto *X : LiveValues) dbgs() << " " <<
X->getName(); dbgs() << ", Looking at "; Inst->dump
(); }; } } while (false)
8082 Inst->dump();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { { dbgs() << "SLP: #LV: " << LiveValues
.size(); for (auto *X : LiveValues) dbgs() << " " <<
X->getName(); dbgs() << ", Looking at "; Inst->dump
(); }; } } while (false)
8083 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { { dbgs() << "SLP: #LV: " << LiveValues
.size(); for (auto *X : LiveValues) dbgs() << " " <<
X->getName(); dbgs() << ", Looking at "; Inst->dump
(); }; } } while (false)
;
8084
8085 // Now find the sequence of instructions between PrevInst and Inst.
8086 unsigned NumCalls = 0;
8087 BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
8088 PrevInstIt =
8089 PrevInst->getIterator().getReverse();
8090 while (InstIt != PrevInstIt) {
8091 if (PrevInstIt == PrevInst->getParent()->rend()) {
8092 PrevInstIt = Inst->getParent()->rbegin();
8093 continue;
8094 }
8095
8096 auto NoCallIntrinsic = [this](Instruction *I) {
8097 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
8098 if (II->isAssumeLikeIntrinsic())
8099 return true;
8100 FastMathFlags FMF;
8101 SmallVector<Type *, 4> Tys;
8102 for (auto &ArgOp : II->args())
8103 Tys.push_back(ArgOp->getType());
8104 if (auto *FPMO = dyn_cast<FPMathOperator>(II))
8105 FMF = FPMO->getFastMathFlags();
8106 IntrinsicCostAttributes ICA(II->getIntrinsicID(), II->getType(), Tys,
8107 FMF);
8108 InstructionCost IntrCost =
8109 TTI->getIntrinsicInstrCost(ICA, TTI::TCK_RecipThroughput);
8110 InstructionCost CallCost = TTI->getCallInstrCost(
8111 nullptr, II->getType(), Tys, TTI::TCK_RecipThroughput);
8112 if (IntrCost < CallCost)
8113 return true;
8114 }
8115 return false;
8116 };
8117
8118 // Debug information does not impact spill cost.
8119 if (isa<CallInst>(&*PrevInstIt) && !NoCallIntrinsic(&*PrevInstIt) &&
8120 &*PrevInstIt != PrevInst)
8121 NumCalls++;
8122
8123 ++PrevInstIt;
8124 }
8125
8126 if (NumCalls) {
8127 SmallVector<Type*, 4> V;
8128 for (auto *II : LiveValues) {
8129 auto *ScalarTy = II->getType();
8130 if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
8131 ScalarTy = VectorTy->getElementType();
8132 V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
8133 }
8134 Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
8135 }
8136
8137 PrevInst = Inst;
8138 }
8139
8140 return Cost;
8141}
8142
8143/// Checks if the \p IE1 instructions is followed by \p IE2 instruction in the
8144/// buildvector sequence.
8145static bool isFirstInsertElement(const InsertElementInst *IE1,
8146 const InsertElementInst *IE2) {
8147 if (IE1 == IE2)
8148 return false;
8149 const auto *I1 = IE1;
8150 const auto *I2 = IE2;
8151 const InsertElementInst *PrevI1;
8152 const InsertElementInst *PrevI2;
8153 unsigned Idx1 = *getInsertIndex(IE1);
8154 unsigned Idx2 = *getInsertIndex(IE2);
8155 do {
8156 if (I2 == IE1)
8157 return true;
8158 if (I1 == IE2)
8159 return false;
8160 PrevI1 = I1;
8161 PrevI2 = I2;
8162 if (I1 && (I1 == IE1 || I1->hasOneUse()) &&
8163 getInsertIndex(I1).value_or(Idx2) != Idx2)
8164 I1 = dyn_cast<InsertElementInst>(I1->getOperand(0));
8165 if (I2 && ((I2 == IE2 || I2->hasOneUse())) &&
8166 getInsertIndex(I2).value_or(Idx1) != Idx1)
8167 I2 = dyn_cast<InsertElementInst>(I2->getOperand(0));
8168 } while ((I1 && PrevI1 != I1) || (I2 && PrevI2 != I2));
8169 llvm_unreachable("Two different buildvectors not expected.")::llvm::llvm_unreachable_internal("Two different buildvectors not expected."
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8169)
;
8170}
8171
8172namespace {
8173/// Returns incoming Value *, if the requested type is Value * too, or a default
8174/// value, otherwise.
8175struct ValueSelect {
8176 template <typename U>
8177 static std::enable_if_t<std::is_same_v<Value *, U>, Value *> get(Value *V) {
8178 return V;
8179 }
8180 template <typename U>
8181 static std::enable_if_t<!std::is_same_v<Value *, U>, U> get(Value *) {
8182 return U();
8183 }
8184};
8185} // namespace
8186
8187/// Does the analysis of the provided shuffle masks and performs the requested
8188/// actions on the vectors with the given shuffle masks. It tries to do it in
8189/// several steps.
8190/// 1. If the Base vector is not undef vector, resizing the very first mask to
8191/// have common VF and perform action for 2 input vectors (including non-undef
8192/// Base). Other shuffle masks are combined with the resulting after the 1 stage
8193/// and processed as a shuffle of 2 elements.
8194/// 2. If the Base is undef vector and have only 1 shuffle mask, perform the
8195/// action only for 1 vector with the given mask, if it is not the identity
8196/// mask.
8197/// 3. If > 2 masks are used, perform the remaining shuffle actions for 2
8198/// vectors, combing the masks properly between the steps.
8199template <typename T>
8200static T *performExtractsShuffleAction(
8201 MutableArrayRef<std::pair<T *, SmallVector<int>>> ShuffleMask, Value *Base,
8202 function_ref<unsigned(T *)> GetVF,
8203 function_ref<std::pair<T *, bool>(T *, ArrayRef<int>, bool)> ResizeAction,
8204 function_ref<T *(ArrayRef<int>, ArrayRef<T *>)> Action) {
8205 assert(!ShuffleMask.empty() && "Empty list of shuffles for inserts.")(static_cast <bool> (!ShuffleMask.empty() && "Empty list of shuffles for inserts."
) ? void (0) : __assert_fail ("!ShuffleMask.empty() && \"Empty list of shuffles for inserts.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8205, __extension__
__PRETTY_FUNCTION__))
;
8206 SmallVector<int> Mask(ShuffleMask.begin()->second);
8207 auto VMIt = std::next(ShuffleMask.begin());
8208 T *Prev = nullptr;
8209 SmallBitVector UseMask =
8210 buildUseMask(Mask.size(), Mask, UseMask::UndefsAsMask);
8211 SmallBitVector IsBaseUndef = isUndefVector(Base, UseMask);
8212 if (!IsBaseUndef.all()) {
8213 // Base is not undef, need to combine it with the next subvectors.
8214 std::pair<T *, bool> Res =
8215 ResizeAction(ShuffleMask.begin()->first, Mask, /*ForSingleMask=*/false);
8216 SmallBitVector IsBasePoison = isUndefVector<true>(Base, UseMask);
8217 for (unsigned Idx = 0, VF = Mask.size(); Idx < VF; ++Idx) {
8218 if (Mask[Idx] == PoisonMaskElem)
8219 Mask[Idx] = IsBasePoison.test(Idx) ? PoisonMaskElem : Idx;
8220 else
8221 Mask[Idx] = (Res.second ? Idx : Mask[Idx]) + VF;
8222 }
8223 auto *V = ValueSelect::get<T *>(Base);
8224 (void)V;
8225 assert((!V || GetVF(V) == Mask.size()) &&(static_cast <bool> ((!V || GetVF(V) == Mask.size()) &&
"Expected base vector of VF number of elements.") ? void (0)
: __assert_fail ("(!V || GetVF(V) == Mask.size()) && \"Expected base vector of VF number of elements.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8226, __extension__
__PRETTY_FUNCTION__))
8226 "Expected base vector of VF number of elements.")(static_cast <bool> ((!V || GetVF(V) == Mask.size()) &&
"Expected base vector of VF number of elements.") ? void (0)
: __assert_fail ("(!V || GetVF(V) == Mask.size()) && \"Expected base vector of VF number of elements.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8226, __extension__
__PRETTY_FUNCTION__))
;
8227 Prev = Action(Mask, {nullptr, Res.first});
8228 } else if (ShuffleMask.size() == 1) {
8229 // Base is undef and only 1 vector is shuffled - perform the action only for
8230 // single vector, if the mask is not the identity mask.
8231 std::pair<T *, bool> Res = ResizeAction(ShuffleMask.begin()->first, Mask,
8232 /*ForSingleMask=*/true);
8233 if (Res.second)
8234 // Identity mask is found.
8235 Prev = Res.first;
8236 else
8237 Prev = Action(Mask, {ShuffleMask.begin()->first});
8238 } else {
8239 // Base is undef and at least 2 input vectors shuffled - perform 2 vectors
8240 // shuffles step by step, combining shuffle between the steps.
8241 unsigned Vec1VF = GetVF(ShuffleMask.begin()->first);
8242 unsigned Vec2VF = GetVF(VMIt->first);
8243 if (Vec1VF == Vec2VF) {
8244 // No need to resize the input vectors since they are of the same size, we
8245 // can shuffle them directly.
8246 ArrayRef<int> SecMask = VMIt->second;
8247 for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
8248 if (SecMask[I] != PoisonMaskElem) {
8249 assert(Mask[I] == PoisonMaskElem && "Multiple uses of scalars.")(static_cast <bool> (Mask[I] == PoisonMaskElem &&
"Multiple uses of scalars.") ? void (0) : __assert_fail ("Mask[I] == PoisonMaskElem && \"Multiple uses of scalars.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8249, __extension__
__PRETTY_FUNCTION__))
;
8250 Mask[I] = SecMask[I] + Vec1VF;
8251 }
8252 }
8253 Prev = Action(Mask, {ShuffleMask.begin()->first, VMIt->first});
8254 } else {
8255 // Vectors of different sizes - resize and reshuffle.
8256 std::pair<T *, bool> Res1 = ResizeAction(ShuffleMask.begin()->first, Mask,
8257 /*ForSingleMask=*/false);
8258 std::pair<T *, bool> Res2 =
8259 ResizeAction(VMIt->first, VMIt->second, /*ForSingleMask=*/false);
8260 ArrayRef<int> SecMask = VMIt->second;
8261 for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
8262 if (Mask[I] != PoisonMaskElem) {
8263 assert(SecMask[I] == PoisonMaskElem && "Multiple uses of scalars.")(static_cast <bool> (SecMask[I] == PoisonMaskElem &&
"Multiple uses of scalars.") ? void (0) : __assert_fail ("SecMask[I] == PoisonMaskElem && \"Multiple uses of scalars.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8263, __extension__
__PRETTY_FUNCTION__))
;
8264 if (Res1.second)
8265 Mask[I] = I;
8266 } else if (SecMask[I] != PoisonMaskElem) {
8267 assert(Mask[I] == PoisonMaskElem && "Multiple uses of scalars.")(static_cast <bool> (Mask[I] == PoisonMaskElem &&
"Multiple uses of scalars.") ? void (0) : __assert_fail ("Mask[I] == PoisonMaskElem && \"Multiple uses of scalars.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8267, __extension__
__PRETTY_FUNCTION__))
;
8268 Mask[I] = (Res2.second ? I : SecMask[I]) + VF;
8269 }
8270 }
8271 Prev = Action(Mask, {Res1.first, Res2.first});
8272 }
8273 VMIt = std::next(VMIt);
8274 }
8275 bool IsBaseNotUndef = !IsBaseUndef.all();
8276 (void)IsBaseNotUndef;
8277 // Perform requested actions for the remaining masks/vectors.
8278 for (auto E = ShuffleMask.end(); VMIt != E; ++VMIt) {
8279 // Shuffle other input vectors, if any.
8280 std::pair<T *, bool> Res =
8281 ResizeAction(VMIt->first, VMIt->second, /*ForSingleMask=*/false);
8282 ArrayRef<int> SecMask = VMIt->second;
8283 for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
8284 if (SecMask[I] != PoisonMaskElem) {
8285 assert((Mask[I] == PoisonMaskElem || IsBaseNotUndef) &&(static_cast <bool> ((Mask[I] == PoisonMaskElem || IsBaseNotUndef
) && "Multiple uses of scalars.") ? void (0) : __assert_fail
("(Mask[I] == PoisonMaskElem || IsBaseNotUndef) && \"Multiple uses of scalars.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8286, __extension__
__PRETTY_FUNCTION__))
8286 "Multiple uses of scalars.")(static_cast <bool> ((Mask[I] == PoisonMaskElem || IsBaseNotUndef
) && "Multiple uses of scalars.") ? void (0) : __assert_fail
("(Mask[I] == PoisonMaskElem || IsBaseNotUndef) && \"Multiple uses of scalars.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8286, __extension__
__PRETTY_FUNCTION__))
;
8287 Mask[I] = (Res.second ? I : SecMask[I]) + VF;
8288 } else if (Mask[I] != PoisonMaskElem) {
8289 Mask[I] = I;
8290 }
8291 }
8292 Prev = Action(Mask, {Prev, Res.first});
8293 }
8294 return Prev;
8295}
8296
8297InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
8298 // Build a map for gathered scalars to the nodes where they are used.
8299 ValueToGatherNodes.clear();
8300 for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
8301 if (EntryPtr->State != TreeEntry::NeedToGather)
8302 continue;
8303 for (Value *V : EntryPtr->Scalars)
8304 if (!isConstant(V))
8305 ValueToGatherNodes.try_emplace(V).first->getSecond().insert(
8306 EntryPtr.get());
8307 }
8308 InstructionCost Cost = 0;
8309 LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Calculating cost for tree of size "
<< VectorizableTree.size() << ".\n"; } } while (
false)
8310 << VectorizableTree.size() << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Calculating cost for tree of size "
<< VectorizableTree.size() << ".\n"; } } while (
false)
;
8311
8312 unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
8313
8314 SmallPtrSet<Value *, 4> CheckedExtracts;
8315 for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
8316 TreeEntry &TE = *VectorizableTree[I];
8317 if (TE.State == TreeEntry::NeedToGather) {
8318 if (const TreeEntry *E = getTreeEntry(TE.getMainOp());
8319 E && E->getVectorFactor() == TE.getVectorFactor() &&
8320 E->isSame(TE.Scalars)) {
8321 // Some gather nodes might be absolutely the same as some vectorizable
8322 // nodes after reordering, need to handle it.
8323 LLVM_DEBUG(dbgs() << "SLP: Adding cost 0 for bundle that starts with "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost 0 for bundle that starts with "
<< *TE.Scalars[0] << ".\n" << "SLP: Current total cost = "
<< Cost << "\n"; } } while (false)
8324 << *TE.Scalars[0] << ".\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost 0 for bundle that starts with "
<< *TE.Scalars[0] << ".\n" << "SLP: Current total cost = "
<< Cost << "\n"; } } while (false)
8325 << "SLP: Current total cost = " << Cost << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost 0 for bundle that starts with "
<< *TE.Scalars[0] << ".\n" << "SLP: Current total cost = "
<< Cost << "\n"; } } while (false)
;
8326 continue;
8327 }
8328 }
8329
8330 InstructionCost C = getEntryCost(&TE, VectorizedVals, CheckedExtracts);
8331 Cost += C;
8332 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << Cdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << C <<
" for bundle that starts with " << *TE.Scalars[0] <<
".\n" << "SLP: Current total cost = " << Cost <<
"\n"; } } while (false)
8333 << " for bundle that starts with " << *TE.Scalars[0]do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << C <<
" for bundle that starts with " << *TE.Scalars[0] <<
".\n" << "SLP: Current total cost = " << Cost <<
"\n"; } } while (false)
8334 << ".\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << C <<
" for bundle that starts with " << *TE.Scalars[0] <<
".\n" << "SLP: Current total cost = " << Cost <<
"\n"; } } while (false)
8335 << "SLP: Current total cost = " << Cost << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << C <<
" for bundle that starts with " << *TE.Scalars[0] <<
".\n" << "SLP: Current total cost = " << Cost <<
"\n"; } } while (false)
;
8336 }
8337
8338 SmallPtrSet<Value *, 16> ExtractCostCalculated;
8339 InstructionCost ExtractCost = 0;
8340 SmallVector<MapVector<const TreeEntry *, SmallVector<int>>> ShuffleMasks;
8341 SmallVector<std::pair<Value *, const TreeEntry *>> FirstUsers;
8342 SmallVector<APInt> DemandedElts;
8343 for (ExternalUser &EU : ExternalUses) {
8344 // We only add extract cost once for the same scalar.
8345 if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
8346 !ExtractCostCalculated.insert(EU.Scalar).second)
8347 continue;
8348
8349 // Uses by ephemeral values are free (because the ephemeral value will be
8350 // removed prior to code generation, and so the extraction will be
8351 // removed as well).
8352 if (EphValues.count(EU.User))
8353 continue;
8354
8355 // No extract cost for vector "scalar"
8356 if (isa<FixedVectorType>(EU.Scalar->getType()))
8357 continue;
8358
8359 // If found user is an insertelement, do not calculate extract cost but try
8360 // to detect it as a final shuffled/identity match.
8361 if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
8362 if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
8363 std::optional<unsigned> InsertIdx = getInsertIndex(VU);
8364 if (InsertIdx) {
8365 const TreeEntry *ScalarTE = getTreeEntry(EU.Scalar);
8366 auto *It = find_if(
8367 FirstUsers,
8368 [this, VU](const std::pair<Value *, const TreeEntry *> &Pair) {
8369 return areTwoInsertFromSameBuildVector(
8370 VU, cast<InsertElementInst>(Pair.first),
8371 [this](InsertElementInst *II) -> Value * {
8372 Value *Op0 = II->getOperand(0);
8373 if (getTreeEntry(II) && !getTreeEntry(Op0))
8374 return nullptr;
8375 return Op0;
8376 });
8377 });
8378 int VecId = -1;
8379 if (It == FirstUsers.end()) {
8380 (void)ShuffleMasks.emplace_back();
8381 SmallVectorImpl<int> &Mask = ShuffleMasks.back()[ScalarTE];
8382 if (Mask.empty())
8383 Mask.assign(FTy->getNumElements(), PoisonMaskElem);
8384 // Find the insertvector, vectorized in tree, if any.
8385 Value *Base = VU;
8386 while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) {
8387 if (IEBase != EU.User &&
8388 (!IEBase->hasOneUse() ||
8389 getInsertIndex(IEBase).value_or(*InsertIdx) == *InsertIdx))
8390 break;
8391 // Build the mask for the vectorized insertelement instructions.
8392 if (const TreeEntry *E = getTreeEntry(IEBase)) {
8393 VU = IEBase;
8394 do {
8395 IEBase = cast<InsertElementInst>(Base);
8396 int Idx = *getInsertIndex(IEBase);
8397 assert(Mask[Idx] == PoisonMaskElem &&(static_cast <bool> (Mask[Idx] == PoisonMaskElem &&
"InsertElementInstruction used already.") ? void (0) : __assert_fail
("Mask[Idx] == PoisonMaskElem && \"InsertElementInstruction used already.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8398, __extension__
__PRETTY_FUNCTION__))
8398 "InsertElementInstruction used already.")(static_cast <bool> (Mask[Idx] == PoisonMaskElem &&
"InsertElementInstruction used already.") ? void (0) : __assert_fail
("Mask[Idx] == PoisonMaskElem && \"InsertElementInstruction used already.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8398, __extension__
__PRETTY_FUNCTION__))
;
8399 Mask[Idx] = Idx;
8400 Base = IEBase->getOperand(0);
8401 } while (E == getTreeEntry(Base));
8402 break;
8403 }
8404 Base = cast<InsertElementInst>(Base)->getOperand(0);
8405 }
8406 FirstUsers.emplace_back(VU, ScalarTE);
8407 DemandedElts.push_back(APInt::getZero(FTy->getNumElements()));
8408 VecId = FirstUsers.size() - 1;
8409 } else {
8410 if (isFirstInsertElement(VU, cast<InsertElementInst>(It->first)))
8411 It->first = VU;
8412 VecId = std::distance(FirstUsers.begin(), It);
8413 }
8414 int InIdx = *InsertIdx;
8415 SmallVectorImpl<int> &Mask = ShuffleMasks[VecId][ScalarTE];
8416 if (Mask.empty())
8417 Mask.assign(FTy->getNumElements(), PoisonMaskElem);
8418 Mask[InIdx] = EU.Lane;
8419 DemandedElts[VecId].setBit(InIdx);
8420 continue;
8421 }
8422 }
8423 }
8424
8425 // If we plan to rewrite the tree in a smaller type, we will need to sign
8426 // extend the extracted value back to the original type. Here, we account
8427 // for the extract and the added cost of the sign extend if needed.
8428 auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
8429 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
8430 auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
8431 if (MinBWs.count(ScalarRoot)) {
8432 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
8433 auto Extend =
8434 MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
8435 VecTy = FixedVectorType::get(MinTy, BundleWidth);
8436 ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
8437 VecTy, EU.Lane);
8438 } else {
8439 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
8440 CostKind, EU.Lane);
8441 }
8442 }
8443
8444 InstructionCost SpillCost = getSpillCost();
8445 Cost += SpillCost + ExtractCost;
8446 auto &&ResizeToVF = [this, &Cost](const TreeEntry *TE, ArrayRef<int> Mask,
8447 bool) {
8448 InstructionCost C = 0;
8449 unsigned VF = Mask.size();
8450 unsigned VecVF = TE->getVectorFactor();
8451 if (VF != VecVF &&
8452 (any_of(Mask, [VF](int Idx) { return Idx >= static_cast<int>(VF); }) ||
8453 (all_of(Mask,
8454 [VF](int Idx) { return Idx < 2 * static_cast<int>(VF); }) &&
8455 !ShuffleVectorInst::isIdentityMask(Mask)))) {
8456 SmallVector<int> OrigMask(VecVF, PoisonMaskElem);
8457 std::copy(Mask.begin(), std::next(Mask.begin(), std::min(VF, VecVF)),
8458 OrigMask.begin());
8459 C = TTI->getShuffleCost(
8460 TTI::SK_PermuteSingleSrc,
8461 FixedVectorType::get(TE->getMainOp()->getType(), VecVF), OrigMask);
8462 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << C <<
" for final shuffle of insertelement external users.\n"; TE->
dump(); dbgs() << "SLP: Current total cost = " <<
Cost << "\n"; } } while (false)
8463 dbgs() << "SLP: Adding cost " << Cdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << C <<
" for final shuffle of insertelement external users.\n"; TE->
dump(); dbgs() << "SLP: Current total cost = " <<
Cost << "\n"; } } while (false)
8464 << " for final shuffle of insertelement external users.\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << C <<
" for final shuffle of insertelement external users.\n"; TE->
dump(); dbgs() << "SLP: Current total cost = " <<
Cost << "\n"; } } while (false)
8465 TE->dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << C <<
" for final shuffle of insertelement external users.\n"; TE->
dump(); dbgs() << "SLP: Current total cost = " <<
Cost << "\n"; } } while (false)
;
8466 Cost += C;
8467 return std::make_pair(TE, true);
8468 }
8469 return std::make_pair(TE, false);
8470 };
8471 // Calculate the cost of the reshuffled vectors, if any.
8472 for (int I = 0, E = FirstUsers.size(); I < E; ++I) {
8473 Value *Base = cast<Instruction>(FirstUsers[I].first)->getOperand(0);
8474 unsigned VF = ShuffleMasks[I].begin()->second.size();
8475 auto *FTy = FixedVectorType::get(
8476 cast<VectorType>(FirstUsers[I].first->getType())->getElementType(), VF);
8477 auto Vector = ShuffleMasks[I].takeVector();
8478 auto &&EstimateShufflesCost = [this, FTy,
8479 &Cost](ArrayRef<int> Mask,
8480 ArrayRef<const TreeEntry *> TEs) {
8481 assert((TEs.size() == 1 || TEs.size() == 2) &&(static_cast <bool> ((TEs.size() == 1 || TEs.size() == 2
) && "Expected exactly 1 or 2 tree entries.") ? void (
0) : __assert_fail ("(TEs.size() == 1 || TEs.size() == 2) && \"Expected exactly 1 or 2 tree entries.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8482, __extension__
__PRETTY_FUNCTION__))
8482 "Expected exactly 1 or 2 tree entries.")(static_cast <bool> ((TEs.size() == 1 || TEs.size() == 2
) && "Expected exactly 1 or 2 tree entries.") ? void (
0) : __assert_fail ("(TEs.size() == 1 || TEs.size() == 2) && \"Expected exactly 1 or 2 tree entries.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8482, __extension__
__PRETTY_FUNCTION__))
;
8483 if (TEs.size() == 1) {
8484 int Limit = 2 * Mask.size();
8485 if (!all_of(Mask, [Limit](int Idx) { return Idx < Limit; }) ||
8486 !ShuffleVectorInst::isIdentityMask(Mask)) {
8487 InstructionCost C =
8488 TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FTy, Mask);
8489 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << Cdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << C <<
" for final shuffle of insertelement " "external users.\n"; TEs
.front()->dump(); dbgs() << "SLP: Current total cost = "
<< Cost << "\n"; } } while (false)
8490 << " for final shuffle of insertelement "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << C <<
" for final shuffle of insertelement " "external users.\n"; TEs
.front()->dump(); dbgs() << "SLP: Current total cost = "
<< Cost << "\n"; } } while (false)
8491 "external users.\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << C <<
" for final shuffle of insertelement " "external users.\n"; TEs
.front()->dump(); dbgs() << "SLP: Current total cost = "
<< Cost << "\n"; } } while (false)
8492 TEs.front()->dump();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << C <<
" for final shuffle of insertelement " "external users.\n"; TEs
.front()->dump(); dbgs() << "SLP: Current total cost = "
<< Cost << "\n"; } } while (false)
8493 dbgs() << "SLP: Current total cost = " << Cost << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << C <<
" for final shuffle of insertelement " "external users.\n"; TEs
.front()->dump(); dbgs() << "SLP: Current total cost = "
<< Cost << "\n"; } } while (false)
;
8494 Cost += C;
8495 }
8496 } else {
8497 InstructionCost C =
8498 TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, FTy, Mask);
8499 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << Cdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << C <<
" for final shuffle of vector node and external " "insertelement users.\n"
; if (TEs.front()) { TEs.front()->dump(); } TEs.back()->
dump(); dbgs() << "SLP: Current total cost = " <<
Cost << "\n"; } } while (false)
8500 << " for final shuffle of vector node and external "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << C <<
" for final shuffle of vector node and external " "insertelement users.\n"
; if (TEs.front()) { TEs.front()->dump(); } TEs.back()->
dump(); dbgs() << "SLP: Current total cost = " <<
Cost << "\n"; } } while (false)
8501 "insertelement users.\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << C <<
" for final shuffle of vector node and external " "insertelement users.\n"
; if (TEs.front()) { TEs.front()->dump(); } TEs.back()->
dump(); dbgs() << "SLP: Current total cost = " <<
Cost << "\n"; } } while (false)
8502 if (TEs.front()) { TEs.front()->dump(); } TEs.back()->dump();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << C <<
" for final shuffle of vector node and external " "insertelement users.\n"
; if (TEs.front()) { TEs.front()->dump(); } TEs.back()->
dump(); dbgs() << "SLP: Current total cost = " <<
Cost << "\n"; } } while (false)
8503 dbgs() << "SLP: Current total cost = " << Cost << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << C <<
" for final shuffle of vector node and external " "insertelement users.\n"
; if (TEs.front()) { TEs.front()->dump(); } TEs.back()->
dump(); dbgs() << "SLP: Current total cost = " <<
Cost << "\n"; } } while (false)
;
8504 Cost += C;
8505 }
8506 return TEs.back();
8507 };
8508 (void)performExtractsShuffleAction<const TreeEntry>(
8509 MutableArrayRef(Vector.data(), Vector.size()), Base,
8510 [](const TreeEntry *E) { return E->getVectorFactor(); }, ResizeToVF,
8511 EstimateShufflesCost);
8512 InstructionCost InsertCost = TTI->getScalarizationOverhead(
8513 cast<FixedVectorType>(FirstUsers[I].first->getType()), DemandedElts[I],
8514 /*Insert*/ true, /*Extract*/ false, TTI::TCK_RecipThroughput);
8515 Cost -= InsertCost;
8516 }
8517
8518#ifndef NDEBUG
8519 SmallString<256> Str;
8520 {
8521 raw_svector_ostream OS(Str);
8522 OS << "SLP: Spill Cost = " << SpillCost << ".\n"
8523 << "SLP: Extract Cost = " << ExtractCost << ".\n"
8524 << "SLP: Total Cost = " << Cost << ".\n";
8525 }
8526 LLVM_DEBUG(dbgs() << Str)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << Str; } } while (false)
;
8527 if (ViewSLPTree)
8528 ViewGraph(this, "SLP" + F->getName(), false, Str);
8529#endif
8530
8531 return Cost;
8532}
8533
8534std::optional<TargetTransformInfo::ShuffleKind>
8535BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, ArrayRef<Value *> VL,
8536 SmallVectorImpl<int> &Mask,
8537 SmallVectorImpl<const TreeEntry *> &Entries) {
8538 Entries.clear();
8539 // No need to check for the topmost gather node.
8540 if (TE == VectorizableTree.front().get())
8541 return std::nullopt;
8542 Mask.assign(VL.size(), PoisonMaskElem);
8543 assert(TE->UserTreeIndices.size() == 1 &&(static_cast <bool> (TE->UserTreeIndices.size() == 1
&& "Expected only single user of the gather node.") ?
void (0) : __assert_fail ("TE->UserTreeIndices.size() == 1 && \"Expected only single user of the gather node.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8544, __extension__
__PRETTY_FUNCTION__))
8544 "Expected only single user of the gather node.")(static_cast <bool> (TE->UserTreeIndices.size() == 1
&& "Expected only single user of the gather node.") ?
void (0) : __assert_fail ("TE->UserTreeIndices.size() == 1 && \"Expected only single user of the gather node.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8544, __extension__
__PRETTY_FUNCTION__))
;
8545 // TODO: currently checking only for Scalars in the tree entry, need to count
8546 // reused elements too for better cost estimation.
8547 Instruction &UserInst =
8548 getLastInstructionInBundle(TE->UserTreeIndices.front().UserTE);
8549 BasicBlock *ParentBB = nullptr;
8550 // Main node of PHI entries keeps the correct order of operands/incoming
8551 // blocks.
8552 if (auto *PHI =
8553 dyn_cast<PHINode>(TE->UserTreeIndices.front().UserTE->getMainOp())) {
8554 ParentBB = PHI->getIncomingBlock(TE->UserTreeIndices.front().EdgeIdx);
8555 } else {
8556 ParentBB = UserInst.getParent();
8557 }
8558 auto *NodeUI = DT->getNode(ParentBB);
8559 assert(NodeUI && "Should only process reachable instructions")(static_cast <bool> (NodeUI && "Should only process reachable instructions"
) ? void (0) : __assert_fail ("NodeUI && \"Should only process reachable instructions\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8559, __extension__
__PRETTY_FUNCTION__))
;
8560 SmallPtrSet<Value *, 4> GatheredScalars(VL.begin(), VL.end());
8561 auto CheckOrdering = [&](Instruction *LastEI) {
8562 // Check if the user node of the TE comes after user node of EntryPtr,
8563 // otherwise EntryPtr depends on TE.
8564 // Gather nodes usually are not scheduled and inserted before their first
8565 // user node. So, instead of checking dependency between the gather nodes
8566 // themselves, we check the dependency between their user nodes.
8567 // If one user node comes before the second one, we cannot use the second
8568 // gather node as the source vector for the first gather node, because in
8569 // the list of instructions it will be emitted later.
8570 auto *EntryParent = LastEI->getParent();
8571 auto *NodeEUI = DT->getNode(EntryParent);
8572 if (!NodeEUI)
8573 return false;
8574 assert((NodeUI == NodeEUI) ==(static_cast <bool> ((NodeUI == NodeEUI) == (NodeUI->
getDFSNumIn() == NodeEUI->getDFSNumIn()) && "Different nodes should have different DFS numbers"
) ? void (0) : __assert_fail ("(NodeUI == NodeEUI) == (NodeUI->getDFSNumIn() == NodeEUI->getDFSNumIn()) && \"Different nodes should have different DFS numbers\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8576, __extension__
__PRETTY_FUNCTION__))
8575 (NodeUI->getDFSNumIn() == NodeEUI->getDFSNumIn()) &&(static_cast <bool> ((NodeUI == NodeEUI) == (NodeUI->
getDFSNumIn() == NodeEUI->getDFSNumIn()) && "Different nodes should have different DFS numbers"
) ? void (0) : __assert_fail ("(NodeUI == NodeEUI) == (NodeUI->getDFSNumIn() == NodeEUI->getDFSNumIn()) && \"Different nodes should have different DFS numbers\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8576, __extension__
__PRETTY_FUNCTION__))
8576 "Different nodes should have different DFS numbers")(static_cast <bool> ((NodeUI == NodeEUI) == (NodeUI->
getDFSNumIn() == NodeEUI->getDFSNumIn()) && "Different nodes should have different DFS numbers"
) ? void (0) : __assert_fail ("(NodeUI == NodeEUI) == (NodeUI->getDFSNumIn() == NodeEUI->getDFSNumIn()) && \"Different nodes should have different DFS numbers\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8576, __extension__
__PRETTY_FUNCTION__))
;
8577 // Check the order of the gather nodes users.
8578 if (UserInst.getParent() != EntryParent &&
8579 (DT->dominates(NodeUI, NodeEUI) || !DT->dominates(NodeEUI, NodeUI)))
8580 return false;
8581 if (UserInst.getParent() == EntryParent && UserInst.comesBefore(LastEI))
8582 return false;
8583 return true;
8584 };
8585 // Find all tree entries used by the gathered values. If no common entries
8586 // found - not a shuffle.
8587 // Here we build a set of tree nodes for each gathered value and trying to
8588 // find the intersection between these sets. If we have at least one common
8589 // tree node for each gathered value - we have just a permutation of the
8590 // single vector. If we have 2 different sets, we're in situation where we
8591 // have a permutation of 2 input vectors.
8592 SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
8593 DenseMap<Value *, int> UsedValuesEntry;
8594 for (Value *V : VL) {
8595 if (isConstant(V))
8596 continue;
8597 // Build a list of tree entries where V is used.
8598 SmallPtrSet<const TreeEntry *, 4> VToTEs;
8599 for (const TreeEntry *TEPtr : ValueToGatherNodes.find(V)->second) {
8600 if (TEPtr == TE)
8601 continue;
8602 if (!any_of(TEPtr->Scalars, [&GatheredScalars](Value *V) {
8603 return GatheredScalars.contains(V);
8604 }))
8605 continue;
8606 assert(TEPtr->UserTreeIndices.size() == 1 &&(static_cast <bool> (TEPtr->UserTreeIndices.size() ==
1 && "Expected only single user of the gather node."
) ? void (0) : __assert_fail ("TEPtr->UserTreeIndices.size() == 1 && \"Expected only single user of the gather node.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8607, __extension__
__PRETTY_FUNCTION__))
8607 "Expected only single user of the gather node.")(static_cast <bool> (TEPtr->UserTreeIndices.size() ==
1 && "Expected only single user of the gather node."
) ? void (0) : __assert_fail ("TEPtr->UserTreeIndices.size() == 1 && \"Expected only single user of the gather node.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8607, __extension__
__PRETTY_FUNCTION__))
;
8608 Instruction &EntryUserInst =
8609 getLastInstructionInBundle(TEPtr->UserTreeIndices.front().UserTE);
8610 PHINode *EntryPHI =
8611 dyn_cast<PHINode>(TEPtr->UserTreeIndices.front().UserTE->getMainOp());
8612 if (&UserInst == &EntryUserInst && !EntryPHI) {
8613 // If 2 gathers are operands of the same entry, compare operands
8614 // indices, use the earlier one as the base.
8615 if (TE->UserTreeIndices.front().UserTE ==
8616 TEPtr->UserTreeIndices.front().UserTE &&
8617 TE->UserTreeIndices.front().EdgeIdx <
8618 TEPtr->UserTreeIndices.front().EdgeIdx)
8619 continue;
8620 }
8621 // Check if the user node of the TE comes after user node of EntryPtr,
8622 // otherwise EntryPtr depends on TE.
8623 auto *EntryI = EntryPHI
8624 ? EntryPHI
8625 ->getIncomingBlock(
8626 TEPtr->UserTreeIndices.front().EdgeIdx)
8627 ->getTerminator()
8628 : &EntryUserInst;
8629 if (!CheckOrdering(EntryI) &&
8630 (ParentBB != EntryI->getParent() ||
8631 TE->UserTreeIndices.front().UserTE !=
8632 TEPtr->UserTreeIndices.front().UserTE ||
8633 TE->UserTreeIndices.front().EdgeIdx <
8634 TEPtr->UserTreeIndices.front().EdgeIdx))
8635 continue;
8636 VToTEs.insert(TEPtr);
8637 }
8638 if (const TreeEntry *VTE = getTreeEntry(V)) {
8639 Instruction &EntryUserInst = getLastInstructionInBundle(VTE);
8640 if (&EntryUserInst == &UserInst || !CheckOrdering(&EntryUserInst))
8641 continue;
8642 VToTEs.insert(VTE);
8643 }
8644 if (VToTEs.empty())
8645 continue;
8646 if (UsedTEs.empty()) {
8647 // The first iteration, just insert the list of nodes to vector.
8648 UsedTEs.push_back(VToTEs);
8649 UsedValuesEntry.try_emplace(V, 0);
8650 } else {
8651 // Need to check if there are any previously used tree nodes which use V.
8652 // If there are no such nodes, consider that we have another one input
8653 // vector.
8654 SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
8655 unsigned Idx = 0;
8656 for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
8657 // Do we have a non-empty intersection of previously listed tree entries
8658 // and tree entries using current V?
8659 set_intersect(VToTEs, Set);
8660 if (!VToTEs.empty()) {
8661 // Yes, write the new subset and continue analysis for the next
8662 // scalar.
8663 Set.swap(VToTEs);
8664 break;
8665 }
8666 VToTEs = SavedVToTEs;
8667 ++Idx;
8668 }
8669 // No non-empty intersection found - need to add a second set of possible
8670 // source vectors.
8671 if (Idx == UsedTEs.size()) {
8672 // If the number of input vectors is greater than 2 - not a permutation,
8673 // fallback to the regular gather.
8674 // TODO: support multiple reshuffled nodes.
8675 if (UsedTEs.size() == 2)
8676 continue;
8677 UsedTEs.push_back(SavedVToTEs);
8678 Idx = UsedTEs.size() - 1;
8679 }
8680 UsedValuesEntry.try_emplace(V, Idx);
8681 }
8682 }
8683
8684 if (UsedTEs.empty())
8685 return std::nullopt;
8686
8687 unsigned VF = 0;
8688 if (UsedTEs.size() == 1) {
8689 // Keep the order to avoid non-determinism.
8690 SmallVector<const TreeEntry *> FirstEntries(UsedTEs.front().begin(),
8691 UsedTEs.front().end());
8692 sort(FirstEntries, [](const TreeEntry *TE1, const TreeEntry *TE2) {
8693 return TE1->Idx < TE2->Idx;
8694 });
8695 // Try to find the perfect match in another gather node at first.
8696 auto *It = find_if(FirstEntries, [=](const TreeEntry *EntryPtr) {
8697 return EntryPtr->isSame(VL) || EntryPtr->isSame(TE->Scalars);
8698 });
8699 if (It != FirstEntries.end() && (*It)->getVectorFactor() == VL.size()) {
8700 Entries.push_back(*It);
8701 std::iota(Mask.begin(), Mask.end(), 0);
8702 // Clear undef scalars.
8703 for (int I = 0, Sz = VL.size(); I < Sz; ++I)
8704 if (isa<PoisonValue>(VL[I]))
8705 Mask[I] = PoisonMaskElem;
8706 return TargetTransformInfo::SK_PermuteSingleSrc;
8707 }
8708 // No perfect match, just shuffle, so choose the first tree node from the
8709 // tree.
8710 Entries.push_back(FirstEntries.front());
8711 } else {
8712 // Try to find nodes with the same vector factor.
8713 assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.")(static_cast <bool> (UsedTEs.size() == 2 && "Expected at max 2 permuted entries."
) ? void (0) : __assert_fail ("UsedTEs.size() == 2 && \"Expected at max 2 permuted entries.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8713, __extension__
__PRETTY_FUNCTION__))
;
8714 // Keep the order of tree nodes to avoid non-determinism.
8715 DenseMap<int, const TreeEntry *> VFToTE;
8716 for (const TreeEntry *TE : UsedTEs.front()) {
8717 unsigned VF = TE->getVectorFactor();
8718 auto It = VFToTE.find(VF);
8719 if (It != VFToTE.end()) {
8720 if (It->second->Idx > TE->Idx)
8721 It->getSecond() = TE;
8722 continue;
8723 }
8724 VFToTE.try_emplace(VF, TE);
8725 }
8726 // Same, keep the order to avoid non-determinism.
8727 SmallVector<const TreeEntry *> SecondEntries(UsedTEs.back().begin(),
8728 UsedTEs.back().end());
8729 sort(SecondEntries, [](const TreeEntry *TE1, const TreeEntry *TE2) {
8730 return TE1->Idx < TE2->Idx;
8731 });
8732 for (const TreeEntry *TE : SecondEntries) {
8733 auto It = VFToTE.find(TE->getVectorFactor());
8734 if (It != VFToTE.end()) {
8735 VF = It->first;
8736 Entries.push_back(It->second);
8737 Entries.push_back(TE);
8738 break;
8739 }
8740 }
8741 // No 2 source vectors with the same vector factor - just choose 2 with max
8742 // index.
8743 if (Entries.empty()) {
8744 Entries.push_back(
8745 *std::max_element(UsedTEs.front().begin(), UsedTEs.front().end(),
8746 [](const TreeEntry *TE1, const TreeEntry *TE2) {
8747 return TE1->Idx < TE2->Idx;
8748 }));
8749 Entries.push_back(SecondEntries.front());
8750 VF = std::max(Entries.front()->getVectorFactor(),
8751 Entries.back()->getVectorFactor());
8752 }
8753 }
8754
8755 bool IsSplatOrUndefs = isSplat(VL) || all_of(VL, UndefValue::classof);
8756 // Checks if the 2 PHIs are compatible in terms of high possibility to be
8757 // vectorized.
8758 auto AreCompatiblePHIs = [&](Value *V, Value *V1) {
8759 auto *PHI = cast<PHINode>(V);
8760 auto *PHI1 = cast<PHINode>(V1);
8761 // Check that all incoming values are compatible/from same parent (if they
8762 // are instructions).
8763 // The incoming values are compatible if they all are constants, or
8764 // instruction with the same/alternate opcodes from the same basic block.
8765 for (int I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
8766 Value *In = PHI->getIncomingValue(I);
8767 Value *In1 = PHI1->getIncomingValue(I);
8768 if (isConstant(In) && isConstant(In1))
8769 continue;
8770 if (!getSameOpcode({In, In1}, *TLI).getOpcode())
8771 return false;
8772 if (cast<Instruction>(In)->getParent() !=
8773 cast<Instruction>(In1)->getParent())
8774 return false;
8775 }
8776 return true;
8777 };
8778 // Check if the value can be ignored during analysis for shuffled gathers.
8779 // We suppose it is better to ignore instruction, which do not form splats,
8780 // are not vectorized/not extractelements (these instructions will be handled
8781 // by extractelements processing) or may form vector node in future.
8782 auto MightBeIgnored = [=](Value *V) {
8783 auto *I = dyn_cast<Instruction>(V);
8784 SmallVector<Value *> IgnoredVals;
8785 if (UserIgnoreList)
8786 IgnoredVals.assign(UserIgnoreList->begin(), UserIgnoreList->end());
8787 return I && !IsSplatOrUndefs && !ScalarToTreeEntry.count(I) &&
8788 !isVectorLikeInstWithConstOps(I) &&
8789 !areAllUsersVectorized(I, IgnoredVals) && isSimple(I);
8790 };
8791 // Check that the neighbor instruction may form a full vector node with the
8792 // current instruction V. It is possible, if they have same/alternate opcode
8793 // and same parent basic block.
8794 auto NeighborMightBeIgnored = [&](Value *V, int Idx) {
8795 Value *V1 = VL[Idx];
8796 bool UsedInSameVTE = false;
8797 auto It = UsedValuesEntry.find(V1);
8798 if (It != UsedValuesEntry.end())
8799 UsedInSameVTE = It->second == UsedValuesEntry.find(V)->second;
8800 return V != V1 && MightBeIgnored(V1) && !UsedInSameVTE &&
8801 getSameOpcode({V, V1}, *TLI).getOpcode() &&
8802 cast<Instruction>(V)->getParent() ==
8803 cast<Instruction>(V1)->getParent() &&
8804 (!isa<PHINode>(V1) || AreCompatiblePHIs(V, V1));
8805 };
8806 // Build a shuffle mask for better cost estimation and vector emission.
8807 SmallBitVector UsedIdxs(Entries.size());
8808 SmallVector<std::pair<unsigned, int>> EntryLanes;
8809 for (int I = 0, E = VL.size(); I < E; ++I) {
8810 Value *V = VL[I];
8811 auto It = UsedValuesEntry.find(V);
8812 if (It == UsedValuesEntry.end())
8813 continue;
8814 // Do not try to shuffle scalars, if they are constants, or instructions
8815 // that can be vectorized as a result of the following vector build
8816 // vectorization.
8817 if (isConstant(V) || (MightBeIgnored(V) &&
8818 ((I > 0 && NeighborMightBeIgnored(V, I - 1)) ||
8819 (I != E - 1 && NeighborMightBeIgnored(V, I + 1)))))
8820 continue;
8821 unsigned Idx = It->second;
8822 EntryLanes.emplace_back(Idx, I);
8823 UsedIdxs.set(Idx);
8824 }
8825 // Iterate through all shuffled scalars and select entries, which can be used
8826 // for final shuffle.
8827 SmallVector<const TreeEntry *> TempEntries;
8828 for (unsigned I = 0, Sz = Entries.size(); I < Sz; ++I) {
8829 if (!UsedIdxs.test(I))
8830 continue;
8831 // Fix the entry number for the given scalar. If it is the first entry, set
8832 // Pair.first to 0, otherwise to 1 (currently select at max 2 nodes).
8833 // These indices are used when calculating final shuffle mask as the vector
8834 // offset.
8835 for (std::pair<unsigned, int> &Pair : EntryLanes)
8836 if (Pair.first == I)
8837 Pair.first = TempEntries.size();
8838 TempEntries.push_back(Entries[I]);
8839 }
8840 Entries.swap(TempEntries);
8841 if (EntryLanes.size() == Entries.size() && !VL.equals(TE->Scalars)) {
8842 // We may have here 1 or 2 entries only. If the number of scalars is equal
8843 // to the number of entries, no need to do the analysis, it is not very
8844 // profitable. Since VL is not the same as TE->Scalars, it means we already
8845 // have some shuffles before. Cut off not profitable case.
8846 Entries.clear();
8847 return std::nullopt;
8848 }
8849 // Build the final mask, check for the identity shuffle, if possible.
8850 bool IsIdentity = Entries.size() == 1;
8851 // Pair.first is the offset to the vector, while Pair.second is the index of
8852 // scalar in the list.
8853 for (const std::pair<unsigned, int> &Pair : EntryLanes) {
8854 Mask[Pair.second] = Pair.first * VF +
8855 Entries[Pair.first]->findLaneForValue(VL[Pair.second]);
8856 IsIdentity &= Mask[Pair.second] == Pair.second;
8857 }
8858 switch (Entries.size()) {
8859 case 1:
8860 if (IsIdentity || EntryLanes.size() > 1 || VL.size() <= 2)
8861 return TargetTransformInfo::SK_PermuteSingleSrc;
8862 break;
8863 case 2:
8864 if (EntryLanes.size() > 2 || VL.size() <= 2)
8865 return TargetTransformInfo::SK_PermuteTwoSrc;
8866 break;
8867 default:
8868 break;
8869 }
8870 Entries.clear();
8871 return std::nullopt;
8872}
8873
8874InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL,
8875 bool ForPoisonSrc) const {
8876 // Find the type of the operands in VL.
8877 Type *ScalarTy = VL[0]->getType();
8878 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
8879 ScalarTy = SI->getValueOperand()->getType();
8880 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
8881 bool DuplicateNonConst = false;
8882 // Find the cost of inserting/extracting values from the vector.
8883 // Check if the same elements are inserted several times and count them as
8884 // shuffle candidates.
8885 APInt ShuffledElements = APInt::getZero(VL.size());
8886 DenseSet<Value *> UniqueElements;
8887 constexpr TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
8888 InstructionCost Cost;
8889 auto EstimateInsertCost = [&](unsigned I, Value *V) {
8890 if (!ForPoisonSrc)
8891 Cost +=
8892 TTI->getVectorInstrCost(Instruction::InsertElement, VecTy, CostKind,
8893 I, Constant::getNullValue(VecTy), V);
8894 };
8895 for (unsigned I = 0, E = VL.size(); I < E; ++I) {
8896 Value *V = VL[I];
8897 // No need to shuffle duplicates for constants.
8898 if ((ForPoisonSrc && isConstant(V)) || isa<UndefValue>(V)) {
8899 ShuffledElements.setBit(I);
8900 continue;
8901 }
8902 if (!UniqueElements.insert(V).second) {
8903 DuplicateNonConst = true;
8904 ShuffledElements.setBit(I);
8905 continue;
8906 }
8907 EstimateInsertCost(I, V);
8908 }
8909 if (ForPoisonSrc)
8910 Cost =
8911 TTI->getScalarizationOverhead(VecTy, ~ShuffledElements, /*Insert*/ true,
8912 /*Extract*/ false, CostKind);
8913 if (DuplicateNonConst)
8914 Cost +=
8915 TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
8916 return Cost;
8917}
8918
8919// Perform operand reordering on the instructions in VL and return the reordered
8920// operands in Left and Right.
8921void BoUpSLP::reorderInputsAccordingToOpcode(
8922 ArrayRef<Value *> VL, SmallVectorImpl<Value *> &Left,
8923 SmallVectorImpl<Value *> &Right, const TargetLibraryInfo &TLI,
8924 const DataLayout &DL, ScalarEvolution &SE, const BoUpSLP &R) {
8925 if (VL.empty())
8926 return;
8927 VLOperands Ops(VL, TLI, DL, SE, R);
8928 // Reorder the operands in place.
8929 Ops.reorder();
8930 Left = Ops.getVL(0);
8931 Right = Ops.getVL(1);
8932}
8933
8934Instruction &BoUpSLP::getLastInstructionInBundle(const TreeEntry *E) {
8935 // Get the basic block this bundle is in. All instructions in the bundle
8936 // should be in this block (except for extractelement-like instructions with
8937 // constant indeces).
8938 auto *Front = E->getMainOp();
8939 auto *BB = Front->getParent();
8940 assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {(static_cast <bool> (llvm::all_of(E->Scalars, [=](Value
*V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr
&& !isa<GetElementPtrInst>(V)) return true; auto
*I = cast<Instruction>(V); return !E->isOpcodeOrAlt
(I) || I->getParent() == BB || isVectorLikeInstWithConstOps
(I); })) ? void (0) : __assert_fail ("llvm::all_of(E->Scalars, [=](Value *V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(V)) return true; auto *I = cast<Instruction>(V); return !E->isOpcodeOrAlt(I) || I->getParent() == BB || isVectorLikeInstWithConstOps(I); })"
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8947, __extension__
__PRETTY_FUNCTION__))
8941 if (E->getOpcode() == Instruction::GetElementPtr &&(static_cast <bool> (llvm::all_of(E->Scalars, [=](Value
*V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr
&& !isa<GetElementPtrInst>(V)) return true; auto
*I = cast<Instruction>(V); return !E->isOpcodeOrAlt
(I) || I->getParent() == BB || isVectorLikeInstWithConstOps
(I); })) ? void (0) : __assert_fail ("llvm::all_of(E->Scalars, [=](Value *V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(V)) return true; auto *I = cast<Instruction>(V); return !E->isOpcodeOrAlt(I) || I->getParent() == BB || isVectorLikeInstWithConstOps(I); })"
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8947, __extension__
__PRETTY_FUNCTION__))
8942 !isa<GetElementPtrInst>(V))(static_cast <bool> (llvm::all_of(E->Scalars, [=](Value
*V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr
&& !isa<GetElementPtrInst>(V)) return true; auto
*I = cast<Instruction>(V); return !E->isOpcodeOrAlt
(I) || I->getParent() == BB || isVectorLikeInstWithConstOps
(I); })) ? void (0) : __assert_fail ("llvm::all_of(E->Scalars, [=](Value *V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(V)) return true; auto *I = cast<Instruction>(V); return !E->isOpcodeOrAlt(I) || I->getParent() == BB || isVectorLikeInstWithConstOps(I); })"
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8947, __extension__
__PRETTY_FUNCTION__))
8943 return true;(static_cast <bool> (llvm::all_of(E->Scalars, [=](Value
*V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr
&& !isa<GetElementPtrInst>(V)) return true; auto
*I = cast<Instruction>(V); return !E->isOpcodeOrAlt
(I) || I->getParent() == BB || isVectorLikeInstWithConstOps
(I); })) ? void (0) : __assert_fail ("llvm::all_of(E->Scalars, [=](Value *V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(V)) return true; auto *I = cast<Instruction>(V); return !E->isOpcodeOrAlt(I) || I->getParent() == BB || isVectorLikeInstWithConstOps(I); })"
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8947, __extension__
__PRETTY_FUNCTION__))
8944 auto *I = cast<Instruction>(V);(static_cast <bool> (llvm::all_of(E->Scalars, [=](Value
*V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr
&& !isa<GetElementPtrInst>(V)) return true; auto
*I = cast<Instruction>(V); return !E->isOpcodeOrAlt
(I) || I->getParent() == BB || isVectorLikeInstWithConstOps
(I); })) ? void (0) : __assert_fail ("llvm::all_of(E->Scalars, [=](Value *V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(V)) return true; auto *I = cast<Instruction>(V); return !E->isOpcodeOrAlt(I) || I->getParent() == BB || isVectorLikeInstWithConstOps(I); })"
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8947, __extension__
__PRETTY_FUNCTION__))
8945 return !E->isOpcodeOrAlt(I) || I->getParent() == BB ||(static_cast <bool> (llvm::all_of(E->Scalars, [=](Value
*V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr
&& !isa<GetElementPtrInst>(V)) return true; auto
*I = cast<Instruction>(V); return !E->isOpcodeOrAlt
(I) || I->getParent() == BB || isVectorLikeInstWithConstOps
(I); })) ? void (0) : __assert_fail ("llvm::all_of(E->Scalars, [=](Value *V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(V)) return true; auto *I = cast<Instruction>(V); return !E->isOpcodeOrAlt(I) || I->getParent() == BB || isVectorLikeInstWithConstOps(I); })"
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8947, __extension__
__PRETTY_FUNCTION__))
8946 isVectorLikeInstWithConstOps(I);(static_cast <bool> (llvm::all_of(E->Scalars, [=](Value
*V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr
&& !isa<GetElementPtrInst>(V)) return true; auto
*I = cast<Instruction>(V); return !E->isOpcodeOrAlt
(I) || I->getParent() == BB || isVectorLikeInstWithConstOps
(I); })) ? void (0) : __assert_fail ("llvm::all_of(E->Scalars, [=](Value *V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(V)) return true; auto *I = cast<Instruction>(V); return !E->isOpcodeOrAlt(I) || I->getParent() == BB || isVectorLikeInstWithConstOps(I); })"
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8947, __extension__
__PRETTY_FUNCTION__))
8947 }))(static_cast <bool> (llvm::all_of(E->Scalars, [=](Value
*V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr
&& !isa<GetElementPtrInst>(V)) return true; auto
*I = cast<Instruction>(V); return !E->isOpcodeOrAlt
(I) || I->getParent() == BB || isVectorLikeInstWithConstOps
(I); })) ? void (0) : __assert_fail ("llvm::all_of(E->Scalars, [=](Value *V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(V)) return true; auto *I = cast<Instruction>(V); return !E->isOpcodeOrAlt(I) || I->getParent() == BB || isVectorLikeInstWithConstOps(I); })"
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8947, __extension__
__PRETTY_FUNCTION__))
;
8948
8949 auto &&FindLastInst = [E, Front, this, &BB]() {
8950 Instruction *LastInst = Front;
8951 for (Value *V : E->Scalars) {
8952 auto *I = dyn_cast<Instruction>(V);
8953 if (!I)
8954 continue;
8955 if (LastInst->getParent() == I->getParent()) {
8956 if (LastInst->comesBefore(I))
8957 LastInst = I;
8958 continue;
8959 }
8960 assert(((E->getOpcode() == Instruction::GetElementPtr &&(static_cast <bool> (((E->getOpcode() == Instruction
::GetElementPtr && !isa<GetElementPtrInst>(I)) ||
(isVectorLikeInstWithConstOps(LastInst) && isVectorLikeInstWithConstOps
(I))) && "Expected vector-like or non-GEP in GEP node insts only."
) ? void (0) : __assert_fail ("((E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(I)) || (isVectorLikeInstWithConstOps(LastInst) && isVectorLikeInstWithConstOps(I))) && \"Expected vector-like or non-GEP in GEP node insts only.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8964, __extension__
__PRETTY_FUNCTION__))
8961 !isa<GetElementPtrInst>(I)) ||(static_cast <bool> (((E->getOpcode() == Instruction
::GetElementPtr && !isa<GetElementPtrInst>(I)) ||
(isVectorLikeInstWithConstOps(LastInst) && isVectorLikeInstWithConstOps
(I))) && "Expected vector-like or non-GEP in GEP node insts only."
) ? void (0) : __assert_fail ("((E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(I)) || (isVectorLikeInstWithConstOps(LastInst) && isVectorLikeInstWithConstOps(I))) && \"Expected vector-like or non-GEP in GEP node insts only.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8964, __extension__
__PRETTY_FUNCTION__))
8962 (isVectorLikeInstWithConstOps(LastInst) &&(static_cast <bool> (((E->getOpcode() == Instruction
::GetElementPtr && !isa<GetElementPtrInst>(I)) ||
(isVectorLikeInstWithConstOps(LastInst) && isVectorLikeInstWithConstOps
(I))) && "Expected vector-like or non-GEP in GEP node insts only."
) ? void (0) : __assert_fail ("((E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(I)) || (isVectorLikeInstWithConstOps(LastInst) && isVectorLikeInstWithConstOps(I))) && \"Expected vector-like or non-GEP in GEP node insts only.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8964, __extension__
__PRETTY_FUNCTION__))
8963 isVectorLikeInstWithConstOps(I))) &&(static_cast <bool> (((E->getOpcode() == Instruction
::GetElementPtr && !isa<GetElementPtrInst>(I)) ||
(isVectorLikeInstWithConstOps(LastInst) && isVectorLikeInstWithConstOps
(I))) && "Expected vector-like or non-GEP in GEP node insts only."
) ? void (0) : __assert_fail ("((E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(I)) || (isVectorLikeInstWithConstOps(LastInst) && isVectorLikeInstWithConstOps(I))) && \"Expected vector-like or non-GEP in GEP node insts only.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8964, __extension__
__PRETTY_FUNCTION__))
8964 "Expected vector-like or non-GEP in GEP node insts only.")(static_cast <bool> (((E->getOpcode() == Instruction
::GetElementPtr && !isa<GetElementPtrInst>(I)) ||
(isVectorLikeInstWithConstOps(LastInst) && isVectorLikeInstWithConstOps
(I))) && "Expected vector-like or non-GEP in GEP node insts only."
) ? void (0) : __assert_fail ("((E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(I)) || (isVectorLikeInstWithConstOps(LastInst) && isVectorLikeInstWithConstOps(I))) && \"Expected vector-like or non-GEP in GEP node insts only.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8964, __extension__
__PRETTY_FUNCTION__))
;
8965 if (!DT->isReachableFromEntry(LastInst->getParent())) {
8966 LastInst = I;
8967 continue;
8968 }
8969 if (!DT->isReachableFromEntry(I->getParent()))
8970 continue;
8971 auto *NodeA = DT->getNode(LastInst->getParent());
8972 auto *NodeB = DT->getNode(I->getParent());
8973 assert(NodeA && "Should only process reachable instructions")(static_cast <bool> (NodeA && "Should only process reachable instructions"
) ? void (0) : __assert_fail ("NodeA && \"Should only process reachable instructions\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8973, __extension__
__PRETTY_FUNCTION__))
;
8974 assert(NodeB && "Should only process reachable instructions")(static_cast <bool> (NodeB && "Should only process reachable instructions"
) ? void (0) : __assert_fail ("NodeB && \"Should only process reachable instructions\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8974, __extension__
__PRETTY_FUNCTION__))
;
8975 assert((NodeA == NodeB) ==(static_cast <bool> ((NodeA == NodeB) == (NodeA->getDFSNumIn
() == NodeB->getDFSNumIn()) && "Different nodes should have different DFS numbers"
) ? void (0) : __assert_fail ("(NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && \"Different nodes should have different DFS numbers\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8977, __extension__
__PRETTY_FUNCTION__))
8976 (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&(static_cast <bool> ((NodeA == NodeB) == (NodeA->getDFSNumIn
() == NodeB->getDFSNumIn()) && "Different nodes should have different DFS numbers"
) ? void (0) : __assert_fail ("(NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && \"Different nodes should have different DFS numbers\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8977, __extension__
__PRETTY_FUNCTION__))
8977 "Different nodes should have different DFS numbers")(static_cast <bool> ((NodeA == NodeB) == (NodeA->getDFSNumIn
() == NodeB->getDFSNumIn()) && "Different nodes should have different DFS numbers"
) ? void (0) : __assert_fail ("(NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && \"Different nodes should have different DFS numbers\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8977, __extension__
__PRETTY_FUNCTION__))
;
8978 if (NodeA->getDFSNumIn() < NodeB->getDFSNumIn())
8979 LastInst = I;
8980 }
8981 BB = LastInst->getParent();
8982 return LastInst;
8983 };
8984
8985 auto &&FindFirstInst = [E, Front, this]() {
8986 Instruction *FirstInst = Front;
8987 for (Value *V : E->Scalars) {
8988 auto *I = dyn_cast<Instruction>(V);
8989 if (!I)
8990 continue;
8991 if (FirstInst->getParent() == I->getParent()) {
8992 if (I->comesBefore(FirstInst))
8993 FirstInst = I;
8994 continue;
8995 }
8996 assert(((E->getOpcode() == Instruction::GetElementPtr &&(static_cast <bool> (((E->getOpcode() == Instruction
::GetElementPtr && !isa<GetElementPtrInst>(I)) ||
(isVectorLikeInstWithConstOps(FirstInst) && isVectorLikeInstWithConstOps
(I))) && "Expected vector-like or non-GEP in GEP node insts only."
) ? void (0) : __assert_fail ("((E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(I)) || (isVectorLikeInstWithConstOps(FirstInst) && isVectorLikeInstWithConstOps(I))) && \"Expected vector-like or non-GEP in GEP node insts only.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9000, __extension__
__PRETTY_FUNCTION__))
8997 !isa<GetElementPtrInst>(I)) ||(static_cast <bool> (((E->getOpcode() == Instruction
::GetElementPtr && !isa<GetElementPtrInst>(I)) ||
(isVectorLikeInstWithConstOps(FirstInst) && isVectorLikeInstWithConstOps
(I))) && "Expected vector-like or non-GEP in GEP node insts only."
) ? void (0) : __assert_fail ("((E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(I)) || (isVectorLikeInstWithConstOps(FirstInst) && isVectorLikeInstWithConstOps(I))) && \"Expected vector-like or non-GEP in GEP node insts only.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9000, __extension__
__PRETTY_FUNCTION__))
8998 (isVectorLikeInstWithConstOps(FirstInst) &&(static_cast <bool> (((E->getOpcode() == Instruction
::GetElementPtr && !isa<GetElementPtrInst>(I)) ||
(isVectorLikeInstWithConstOps(FirstInst) && isVectorLikeInstWithConstOps
(I))) && "Expected vector-like or non-GEP in GEP node insts only."
) ? void (0) : __assert_fail ("((E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(I)) || (isVectorLikeInstWithConstOps(FirstInst) && isVectorLikeInstWithConstOps(I))) && \"Expected vector-like or non-GEP in GEP node insts only.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9000, __extension__
__PRETTY_FUNCTION__))
8999 isVectorLikeInstWithConstOps(I))) &&(static_cast <bool> (((E->getOpcode() == Instruction
::GetElementPtr && !isa<GetElementPtrInst>(I)) ||
(isVectorLikeInstWithConstOps(FirstInst) && isVectorLikeInstWithConstOps
(I))) && "Expected vector-like or non-GEP in GEP node insts only."
) ? void (0) : __assert_fail ("((E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(I)) || (isVectorLikeInstWithConstOps(FirstInst) && isVectorLikeInstWithConstOps(I))) && \"Expected vector-like or non-GEP in GEP node insts only.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9000, __extension__
__PRETTY_FUNCTION__))
9000 "Expected vector-like or non-GEP in GEP node insts only.")(static_cast <bool> (((E->getOpcode() == Instruction
::GetElementPtr && !isa<GetElementPtrInst>(I)) ||
(isVectorLikeInstWithConstOps(FirstInst) && isVectorLikeInstWithConstOps
(I))) && "Expected vector-like or non-GEP in GEP node insts only."
) ? void (0) : __assert_fail ("((E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(I)) || (isVectorLikeInstWithConstOps(FirstInst) && isVectorLikeInstWithConstOps(I))) && \"Expected vector-like or non-GEP in GEP node insts only.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9000, __extension__
__PRETTY_FUNCTION__))
;
9001 if (!DT->isReachableFromEntry(FirstInst->getParent())) {
9002 FirstInst = I;
9003 continue;
9004 }
9005 if (!DT->isReachableFromEntry(I->getParent()))
9006 continue;
9007 auto *NodeA = DT->getNode(FirstInst->getParent());
9008 auto *NodeB = DT->getNode(I->getParent());
9009 assert(NodeA && "Should only process reachable instructions")(static_cast <bool> (NodeA && "Should only process reachable instructions"
) ? void (0) : __assert_fail ("NodeA && \"Should only process reachable instructions\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9009, __extension__
__PRETTY_FUNCTION__))
;
9010 assert(NodeB && "Should only process reachable instructions")(static_cast <bool> (NodeB && "Should only process reachable instructions"
) ? void (0) : __assert_fail ("NodeB && \"Should only process reachable instructions\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9010, __extension__
__PRETTY_FUNCTION__))
;
9011 assert((NodeA == NodeB) ==(static_cast <bool> ((NodeA == NodeB) == (NodeA->getDFSNumIn
() == NodeB->getDFSNumIn()) && "Different nodes should have different DFS numbers"
) ? void (0) : __assert_fail ("(NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && \"Different nodes should have different DFS numbers\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9013, __extension__
__PRETTY_FUNCTION__))
9012 (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&(static_cast <bool> ((NodeA == NodeB) == (NodeA->getDFSNumIn
() == NodeB->getDFSNumIn()) && "Different nodes should have different DFS numbers"
) ? void (0) : __assert_fail ("(NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && \"Different nodes should have different DFS numbers\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9013, __extension__
__PRETTY_FUNCTION__))
9013 "Different nodes should have different DFS numbers")(static_cast <bool> ((NodeA == NodeB) == (NodeA->getDFSNumIn
() == NodeB->getDFSNumIn()) && "Different nodes should have different DFS numbers"
) ? void (0) : __assert_fail ("(NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && \"Different nodes should have different DFS numbers\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9013, __extension__
__PRETTY_FUNCTION__))
;
9014 if (NodeA->getDFSNumIn() > NodeB->getDFSNumIn())
9015 FirstInst = I;
9016 }
9017 return FirstInst;
9018 };
9019
9020 // Set the insert point to the beginning of the basic block if the entry
9021 // should not be scheduled.
9022 if (E->State != TreeEntry::NeedToGather &&
9023 (doesNotNeedToSchedule(E->Scalars) ||
9024 all_of(E->Scalars, isVectorLikeInstWithConstOps))) {
9025 Instruction *InsertInst;
9026 if ((E->getOpcode() == Instruction::GetElementPtr &&
9027 any_of(E->Scalars,
9028 [](Value *V) {
9029 return !isa<GetElementPtrInst>(V) && isa<Instruction>(V);
9030 })) ||
9031 all_of(E->Scalars, [](Value *V) {
9032 return !isVectorLikeInstWithConstOps(V) && isUsedOutsideBlock(V);
9033 }))
9034 InsertInst = FindLastInst();
9035 else
9036 InsertInst = FindFirstInst();
9037 return *InsertInst;
9038 }
9039
9040 // The last instruction in the bundle in program order.
9041 Instruction *LastInst = nullptr;
9042
9043 // Find the last instruction. The common case should be that BB has been
9044 // scheduled, and the last instruction is VL.back(). So we start with
9045 // VL.back() and iterate over schedule data until we reach the end of the
9046 // bundle. The end of the bundle is marked by null ScheduleData.
9047 if (BlocksSchedules.count(BB)) {
9048 Value *V = E->isOneOf(E->Scalars.back());
9049 if (doesNotNeedToBeScheduled(V))
9050 V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
9051 auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
9052 if (Bundle && Bundle->isPartOfBundle())
9053 for (; Bundle; Bundle = Bundle->NextInBundle)
9054 if (Bundle->OpValue == Bundle->Inst)
9055 LastInst = Bundle->Inst;
9056 }
9057
9058 // LastInst can still be null at this point if there's either not an entry
9059 // for BB in BlocksSchedules or there's no ScheduleData available for
9060 // VL.back(). This can be the case if buildTree_rec aborts for various
9061 // reasons (e.g., the maximum recursion depth is reached, the maximum region
9062 // size is reached, etc.). ScheduleData is initialized in the scheduling
9063 // "dry-run".
9064 //
9065 // If this happens, we can still find the last instruction by brute force. We
9066 // iterate forwards from Front (inclusive) until we either see all
9067 // instructions in the bundle or reach the end of the block. If Front is the
9068 // last instruction in program order, LastInst will be set to Front, and we
9069 // will visit all the remaining instructions in the block.
9070 //
9071 // One of the reasons we exit early from buildTree_rec is to place an upper
9072 // bound on compile-time. Thus, taking an additional compile-time hit here is
9073 // not ideal. However, this should be exceedingly rare since it requires that
9074 // we both exit early from buildTree_rec and that the bundle be out-of-order
9075 // (causing us to iterate all the way to the end of the block).
9076 if (!LastInst)
9077 LastInst = FindLastInst();
9078 assert(LastInst && "Failed to find last instruction in bundle")(static_cast <bool> (LastInst && "Failed to find last instruction in bundle"
) ? void (0) : __assert_fail ("LastInst && \"Failed to find last instruction in bundle\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9078, __extension__
__PRETTY_FUNCTION__))
;
9079 return *LastInst;
9080}
9081
9082void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
9083 auto *Front = E->getMainOp();
9084 Instruction *LastInst = EntryToLastInstruction.lookup(E);
9085 assert(LastInst && "Failed to find last instruction in bundle")(static_cast <bool> (LastInst && "Failed to find last instruction in bundle"
) ? void (0) : __assert_fail ("LastInst && \"Failed to find last instruction in bundle\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9085, __extension__
__PRETTY_FUNCTION__))
;
9086 // If the instruction is PHI, set the insert point after all the PHIs.
9087 bool IsPHI = isa<PHINode>(LastInst);
9088 if (IsPHI)
9089 LastInst = LastInst->getParent()->getFirstNonPHI();
9090 if (IsPHI || (E->State != TreeEntry::NeedToGather &&
9091 doesNotNeedToSchedule(E->Scalars))) {
9092 Builder.SetInsertPoint(LastInst);
9093 } else {
9094 // Set the insertion point after the last instruction in the bundle. Set the
9095 // debug location to Front.
9096 Builder.SetInsertPoint(LastInst->getParent(),
9097 std::next(LastInst->getIterator()));
9098 }
9099 Builder.SetCurrentDebugLocation(Front->getDebugLoc());
9100}
9101
9102Value *BoUpSLP::gather(ArrayRef<Value *> VL, Value *Root) {
9103 // List of instructions/lanes from current block and/or the blocks which are
9104 // part of the current loop. These instructions will be inserted at the end to
9105 // make it possible to optimize loops and hoist invariant instructions out of
9106 // the loops body with better chances for success.
9107 SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
9108 SmallSet<int, 4> PostponedIndices;
9109 Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
9110 auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
9111 SmallPtrSet<BasicBlock *, 4> Visited;
9112 while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
9113 InsertBB = InsertBB->getSinglePredecessor();
9114 return InsertBB && InsertBB == InstBB;
9115 };
9116 for (int I = 0, E = VL.size(); I < E; ++I) {
9117 if (auto *Inst = dyn_cast<Instruction>(VL[I]))
9118 if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
9119 getTreeEntry(Inst) ||
9120 (L && (!Root || L->isLoopInvariant(Root)) && L->contains(Inst))) &&
9121 PostponedIndices.insert(I).second)
9122 PostponedInsts.emplace_back(Inst, I);
9123 }
9124
9125 auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
9126 Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
9127 auto *InsElt = dyn_cast<InsertElementInst>(Vec);
9128 if (!InsElt)
9129 return Vec;
9130 GatherShuffleExtractSeq.insert(InsElt);
9131 CSEBlocks.insert(InsElt->getParent());
9132 // Add to our 'need-to-extract' list.
9133 if (TreeEntry *Entry = getTreeEntry(V)) {
9134 // Find which lane we need to extract.
9135 unsigned FoundLane = Entry->findLaneForValue(V);
9136 ExternalUses.emplace_back(V, InsElt, FoundLane);
9137 }
9138 return Vec;
9139 };
9140 Value *Val0 =
9141 isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
9142 FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
9143 Value *Vec = Root ? Root : PoisonValue::get(VecTy);
9144 SmallVector<int> NonConsts;
9145 // Insert constant values at first.
9146 for (int I = 0, E = VL.size(); I < E; ++I) {
9147 if (PostponedIndices.contains(I))
9148 continue;
9149 if (!isConstant(VL[I])) {
9150 NonConsts.push_back(I);
9151 continue;
9152 }
9153 if (Root) {
9154 if (!isa<UndefValue>(VL[I])) {
9155 NonConsts.push_back(I);
9156 continue;
9157 }
9158 if (isa<PoisonValue>(VL[I]))
9159 continue;
9160 if (auto *SV = dyn_cast<ShuffleVectorInst>(Root)) {
9161 if (SV->getMaskValue(I) == PoisonMaskElem)
9162 continue;
9163 }
9164 }
9165 Vec = CreateInsertElement(Vec, VL[I], I);
9166 }
9167 // Insert non-constant values.
9168 for (int I : NonConsts)
9169 Vec = CreateInsertElement(Vec, VL[I], I);
9170 // Append instructions, which are/may be part of the loop, in the end to make
9171 // it possible to hoist non-loop-based instructions.
9172 for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
9173 Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
9174
9175 return Vec;
9176}
9177
9178/// Merges shuffle masks and emits final shuffle instruction, if required. It
9179/// supports shuffling of 2 input vectors. It implements lazy shuffles emission,
9180/// when the actual shuffle instruction is generated only if this is actually
9181/// required. Otherwise, the shuffle instruction emission is delayed till the
9182/// end of the process, to reduce the number of emitted instructions and further
9183/// analysis/transformations.
9184/// The class also will look through the previously emitted shuffle instructions
9185/// and properly mark indices in mask as undef.
9186/// For example, given the code
9187/// \code
9188/// %s1 = shufflevector <2 x ty> %0, poison, <1, 0>
9189/// %s2 = shufflevector <2 x ty> %1, poison, <1, 0>
9190/// \endcode
9191/// and if need to emit shuffle of %s1 and %s2 with mask <1, 0, 3, 2>, it will
9192/// look through %s1 and %s2 and emit
9193/// \code
9194/// %res = shufflevector <2 x ty> %0, %1, <0, 1, 2, 3>
9195/// \endcode
9196/// instead.
9197/// If 2 operands are of different size, the smallest one will be resized and
9198/// the mask recalculated properly.
9199/// For example, given the code
9200/// \code
9201/// %s1 = shufflevector <2 x ty> %0, poison, <1, 0, 1, 0>
9202/// %s2 = shufflevector <2 x ty> %1, poison, <1, 0, 1, 0>
9203/// \endcode
9204/// and if need to emit shuffle of %s1 and %s2 with mask <1, 0, 5, 4>, it will
9205/// look through %s1 and %s2 and emit
9206/// \code
9207/// %res = shufflevector <2 x ty> %0, %1, <0, 1, 2, 3>
9208/// \endcode
9209/// instead.
9210class BoUpSLP::ShuffleInstructionBuilder final : public BaseShuffleAnalysis {
9211 bool IsFinalized = false;
9212 /// Combined mask for all applied operands and masks. It is built during
9213 /// analysis and actual emission of shuffle vector instructions.
9214 SmallVector<int> CommonMask;
9215 /// List of operands for the shuffle vector instruction. It hold at max 2
9216 /// operands, if the 3rd is going to be added, the first 2 are combined into
9217 /// shuffle with \p CommonMask mask, the first operand sets to be the
9218 /// resulting shuffle and the second operand sets to be the newly added
9219 /// operand. The \p CommonMask is transformed in the proper way after that.
9220 SmallVector<Value *, 2> InVectors;
9221 IRBuilderBase &Builder;
9222 BoUpSLP &R;
9223
9224 class ShuffleIRBuilder {
9225 IRBuilderBase &Builder;
9226 /// Holds all of the instructions that we gathered.
9227 SetVector<Instruction *> &GatherShuffleExtractSeq;
9228 /// A list of blocks that we are going to CSE.
9229 SetVector<BasicBlock *> &CSEBlocks;
9230
9231 public:
9232 ShuffleIRBuilder(IRBuilderBase &Builder,
9233 SetVector<Instruction *> &GatherShuffleExtractSeq,
9234 SetVector<BasicBlock *> &CSEBlocks)
9235 : Builder(Builder), GatherShuffleExtractSeq(GatherShuffleExtractSeq),
9236 CSEBlocks(CSEBlocks) {}
9237 ~ShuffleIRBuilder() = default;
9238 /// Creates shufflevector for the 2 operands with the given mask.
9239 Value *createShuffleVector(Value *V1, Value *V2, ArrayRef<int> Mask) {
9240 Value *Vec = Builder.CreateShuffleVector(V1, V2, Mask);
9241 if (auto *I = dyn_cast<Instruction>(Vec)) {
9242 GatherShuffleExtractSeq.insert(I);
9243 CSEBlocks.insert(I->getParent());
9244 }
9245 return Vec;
9246 }
9247 /// Creates permutation of the single vector operand with the given mask, if
9248 /// it is not identity mask.
9249 Value *createShuffleVector(Value *V1, ArrayRef<int> Mask) {
9250 if (Mask.empty())
9251 return V1;
9252 unsigned VF = Mask.size();
9253 unsigned LocalVF = cast<FixedVectorType>(V1->getType())->getNumElements();
9254 if (VF == LocalVF && ShuffleVectorInst::isIdentityMask(Mask))
9255 return V1;
9256 Value *Vec = Builder.CreateShuffleVector(V1, Mask);
9257 if (auto *I = dyn_cast<Instruction>(Vec)) {
9258 GatherShuffleExtractSeq.insert(I);
9259 CSEBlocks.insert(I->getParent());
9260 }
9261 return Vec;
9262 }
9263 Value *createIdentity(Value *V) { return V; }
9264 Value *createPoison(Type *Ty, unsigned VF) {
9265 return PoisonValue::get(FixedVectorType::get(Ty, VF));
9266 }
9267 /// Resizes 2 input vector to match the sizes, if the they are not equal
9268 /// yet. The smallest vector is resized to the size of the larger vector.
9269 void resizeToMatch(Value *&V1, Value *&V2) {
9270 if (V1->getType() == V2->getType())
9271 return;
9272 int V1VF = cast<FixedVectorType>(V1->getType())->getNumElements();
9273 int V2VF = cast<FixedVectorType>(V2->getType())->getNumElements();
9274 int VF = std::max(V1VF, V2VF);
9275 int MinVF = std::min(V1VF, V2VF);
9276 SmallVector<int> IdentityMask(VF, PoisonMaskElem);
9277 std::iota(IdentityMask.begin(), std::next(IdentityMask.begin(), MinVF),
9278 0);
9279 Value *&Op = MinVF == V1VF ? V1 : V2;
9280 Op = Builder.CreateShuffleVector(Op, IdentityMask);
9281 if (auto *I = dyn_cast<Instruction>(Op)) {
9282 GatherShuffleExtractSeq.insert(I);
9283 CSEBlocks.insert(I->getParent());
9284 }
9285 if (MinVF == V1VF)
9286 V1 = Op;
9287 else
9288 V2 = Op;
9289 }
9290 };
9291
9292 /// Smart shuffle instruction emission, walks through shuffles trees and
9293 /// tries to find the best matching vector for the actual shuffle
9294 /// instruction.
9295 Value *createShuffle(Value *V1, Value *V2, ArrayRef<int> Mask) {
9296 assert(V1 && "Expected at least one vector value.")(static_cast <bool> (V1 && "Expected at least one vector value."
) ? void (0) : __assert_fail ("V1 && \"Expected at least one vector value.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9296, __extension__
__PRETTY_FUNCTION__))
;
9297 ShuffleIRBuilder ShuffleBuilder(Builder, R.GatherShuffleExtractSeq,
9298 R.CSEBlocks);
9299 return BaseShuffleAnalysis::createShuffle<Value *>(V1, V2, Mask,
9300 ShuffleBuilder);
9301 }
9302
9303 /// Transforms mask \p CommonMask per given \p Mask to make proper set after
9304 /// shuffle emission.
9305 static void transformMaskAfterShuffle(MutableArrayRef<int> CommonMask,
9306 ArrayRef<int> Mask) {
9307 for (unsigned Idx = 0, Sz = CommonMask.size(); Idx < Sz; ++Idx)
9308 if (Mask[Idx] != PoisonMaskElem)
9309 CommonMask[Idx] = Idx;
9310 }
9311
9312public:
9313 ShuffleInstructionBuilder(IRBuilderBase &Builder, BoUpSLP &R)
9314 : Builder(Builder), R(R) {}
9315
9316 /// Adjusts extractelements after reusing them.
9317 Value *adjustExtracts(const TreeEntry *E, ArrayRef<int> Mask) {
9318 Value *VecBase = nullptr;
9319 for (int I = 0, Sz = Mask.size(); I < Sz; ++I) {
9320 int Idx = Mask[I];
9321 if (Idx == PoisonMaskElem)
9322 continue;
9323 auto *EI = cast<ExtractElementInst>(E->Scalars[I]);
9324 VecBase = EI->getVectorOperand();
9325 // If the only one use is vectorized - can delete the extractelement
9326 // itself.
9327 if (!EI->hasOneUse() || any_of(EI->users(), [&](User *U) {
9328 return !R.ScalarToTreeEntry.count(U);
9329 }))
9330 continue;
9331 R.eraseInstruction(EI);
9332 }
9333 return VecBase;
9334 }
9335 /// Checks if the specified entry \p E needs to be delayed because of its
9336 /// dependency nodes.
9337 Value *needToDelay(const TreeEntry *E, ArrayRef<const TreeEntry *> Deps) {
9338 // No need to delay emission if all deps are ready.
9339 if (all_of(Deps, [](const TreeEntry *TE) { return TE->VectorizedValue; }))
9340 return nullptr;
9341 // Postpone gather emission, will be emitted after the end of the
9342 // process to keep correct order.
9343 auto *VecTy = FixedVectorType::get(E->Scalars.front()->getType(),
9344 E->getVectorFactor());
9345 Value *Vec = Builder.CreateAlignedLoad(
9346 VecTy, PoisonValue::get(VecTy->getPointerTo()), MaybeAlign());
9347 return Vec;
9348 }
9349 /// Adds 2 input vectors and the mask for their shuffling.
9350 void add(Value *V1, Value *V2, ArrayRef<int> Mask) {
9351 assert(V1 && V2 && !Mask.empty() && "Expected non-empty input vectors.")(static_cast <bool> (V1 && V2 && !Mask.
empty() && "Expected non-empty input vectors.") ? void
(0) : __assert_fail ("V1 && V2 && !Mask.empty() && \"Expected non-empty input vectors.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9351, __extension__
__PRETTY_FUNCTION__))
;
9352 if (InVectors.empty()) {
9353 InVectors.push_back(V1);
9354 InVectors.push_back(V2);
9355 CommonMask.assign(Mask.begin(), Mask.end());
9356 return;
9357 }
9358 Value *Vec = InVectors.front();
9359 if (InVectors.size() == 2) {
9360 Vec = createShuffle(Vec, InVectors.back(), CommonMask);
9361 transformMaskAfterShuffle(CommonMask, CommonMask);
9362 } else if (cast<FixedVectorType>(Vec->getType())->getNumElements() !=
9363 Mask.size()) {
9364 Vec = createShuffle(Vec, nullptr, CommonMask);
9365 transformMaskAfterShuffle(CommonMask, CommonMask);
9366 }
9367 V1 = createShuffle(V1, V2, Mask);
9368 for (unsigned Idx = 0, Sz = CommonMask.size(); Idx < Sz; ++Idx)
9369 if (Mask[Idx] != PoisonMaskElem)
9370 CommonMask[Idx] = Idx + Sz;
9371 InVectors.front() = Vec;
9372 if (InVectors.size() == 2)
9373 InVectors.back() = V1;
9374 else
9375 InVectors.push_back(V1);
9376 }
9377 /// Adds another one input vector and the mask for the shuffling.
9378 void add(Value *V1, ArrayRef<int> Mask) {
9379 if (InVectors.empty()) {
9380 if (!isa<FixedVectorType>(V1->getType())) {
9381 V1 = createShuffle(V1, nullptr, CommonMask);
9382 CommonMask.assign(Mask.size(), PoisonMaskElem);
9383 transformMaskAfterShuffle(CommonMask, Mask);
9384 }
9385 InVectors.push_back(V1);
9386 CommonMask.assign(Mask.begin(), Mask.end());
9387 return;
9388 }
9389 const auto *It = find(InVectors, V1);
9390 if (It == InVectors.end()) {
9391 if (InVectors.size() == 2 ||
9392 InVectors.front()->getType() != V1->getType() ||
9393 !isa<FixedVectorType>(V1->getType())) {
9394 Value *V = InVectors.front();
9395 if (InVectors.size() == 2) {
9396 V = createShuffle(InVectors.front(), InVectors.back(), CommonMask);
9397 transformMaskAfterShuffle(CommonMask, CommonMask);
9398 } else if (cast<FixedVectorType>(V->getType())->getNumElements() !=
9399 CommonMask.size()) {
9400 V = createShuffle(InVectors.front(), nullptr, CommonMask);
9401 transformMaskAfterShuffle(CommonMask, CommonMask);
9402 }
9403 for (unsigned Idx = 0, Sz = CommonMask.size(); Idx < Sz; ++Idx)
9404 if (CommonMask[Idx] == PoisonMaskElem && Mask[Idx] != PoisonMaskElem)
9405 CommonMask[Idx] =
9406 V->getType() != V1->getType()
9407 ? Idx + Sz
9408 : Mask[Idx] + cast<FixedVectorType>(V1->getType())
9409 ->getNumElements();
9410 if (V->getType() != V1->getType())
9411 V1 = createShuffle(V1, nullptr, Mask);
9412 InVectors.front() = V;
9413 if (InVectors.size() == 2)
9414 InVectors.back() = V1;
9415 else
9416 InVectors.push_back(V1);
9417 return;
9418 }
9419 // Check if second vector is required if the used elements are already
9420 // used from the first one.
9421 for (unsigned Idx = 0, Sz = CommonMask.size(); Idx < Sz; ++Idx)
9422 if (Mask[Idx] != PoisonMaskElem && CommonMask[Idx] == PoisonMaskElem) {
9423 InVectors.push_back(V1);
9424 break;
9425 }
9426 }
9427 int VF = CommonMask.size();
9428 if (auto *FTy = dyn_cast<FixedVectorType>(V1->getType()))
9429 VF = FTy->getNumElements();
9430 for (unsigned Idx = 0, Sz = CommonMask.size(); Idx < Sz; ++Idx)
9431 if (Mask[Idx] != PoisonMaskElem && CommonMask[Idx] == PoisonMaskElem)
9432 CommonMask[Idx] = Mask[Idx] + (It == InVectors.begin() ? 0 : VF);
9433 }
9434 /// Adds another one input vector and the mask for the shuffling.
9435 void addOrdered(Value *V1, ArrayRef<unsigned> Order) {
9436 SmallVector<int> NewMask;
9437 inversePermutation(Order, NewMask);
9438 add(V1, NewMask);
9439 }
9440 Value *gather(ArrayRef<Value *> VL, Value *Root = nullptr) {
9441 return R.gather(VL, Root);
9442 }
9443 Value *createFreeze(Value *V) { return Builder.CreateFreeze(V); }
9444 /// Finalize emission of the shuffles.
9445 /// \param Action the action (if any) to be performed before final applying of
9446 /// the \p ExtMask mask.
9447 Value *
9448 finalize(ArrayRef<int> ExtMask, unsigned VF = 0,
9449 function_ref<void(Value *&, SmallVectorImpl<int> &)> Action = {}) {
9450 IsFinalized = true;
9451 if (Action) {
9452 Value *Vec = InVectors.front();
9453 if (InVectors.size() == 2) {
9454 Vec = createShuffle(Vec, InVectors.back(), CommonMask);
9455 InVectors.pop_back();
9456 } else {
9457 Vec = createShuffle(Vec, nullptr, CommonMask);
9458 }
9459 for (unsigned Idx = 0, Sz = CommonMask.size(); Idx < Sz; ++Idx)
9460 if (CommonMask[Idx] != PoisonMaskElem)
9461 CommonMask[Idx] = Idx;
9462 assert(VF > 0 &&(static_cast <bool> (VF > 0 && "Expected vector length for the final value before action."
) ? void (0) : __assert_fail ("VF > 0 && \"Expected vector length for the final value before action.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9463, __extension__
__PRETTY_FUNCTION__))
9463 "Expected vector length for the final value before action.")(static_cast <bool> (VF > 0 && "Expected vector length for the final value before action."
) ? void (0) : __assert_fail ("VF > 0 && \"Expected vector length for the final value before action.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9463, __extension__
__PRETTY_FUNCTION__))
;
9464 unsigned VecVF = cast<FixedVectorType>(Vec->getType())->getNumElements();
9465 if (VecVF < VF) {
9466 SmallVector<int> ResizeMask(VF, PoisonMaskElem);
9467 std::iota(ResizeMask.begin(), std::next(ResizeMask.begin(), VecVF), 0);
9468 Vec = createShuffle(Vec, nullptr, ResizeMask);
9469 }
9470 Action(Vec, CommonMask);
9471 InVectors.front() = Vec;
9472 }
9473 if (!ExtMask.empty()) {
9474 if (CommonMask.empty()) {
9475 CommonMask.assign(ExtMask.begin(), ExtMask.end());
9476 } else {
9477 SmallVector<int> NewMask(ExtMask.size(), PoisonMaskElem);
9478 for (int I = 0, Sz = ExtMask.size(); I < Sz; ++I) {
9479 if (ExtMask[I] == PoisonMaskElem)
9480 continue;
9481 NewMask[I] = CommonMask[ExtMask[I]];
9482 }
9483 CommonMask.swap(NewMask);
9484 }
9485 }
9486 if (CommonMask.empty()) {
9487 assert(InVectors.size() == 1 && "Expected only one vector with no mask")(static_cast <bool> (InVectors.size() == 1 && "Expected only one vector with no mask"
) ? void (0) : __assert_fail ("InVectors.size() == 1 && \"Expected only one vector with no mask\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9487, __extension__
__PRETTY_FUNCTION__))
;
9488 return InVectors.front();
9489 }
9490 if (InVectors.size() == 2)
9491 return createShuffle(InVectors.front(), InVectors.back(), CommonMask);
9492 return createShuffle(InVectors.front(), nullptr, CommonMask);
9493 }
9494
9495 ~ShuffleInstructionBuilder() {
9496 assert((IsFinalized || CommonMask.empty()) &&(static_cast <bool> ((IsFinalized || CommonMask.empty()
) && "Shuffle construction must be finalized.") ? void
(0) : __assert_fail ("(IsFinalized || CommonMask.empty()) && \"Shuffle construction must be finalized.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9497, __extension__
__PRETTY_FUNCTION__))
9497 "Shuffle construction must be finalized.")(static_cast <bool> ((IsFinalized || CommonMask.empty()
) && "Shuffle construction must be finalized.") ? void
(0) : __assert_fail ("(IsFinalized || CommonMask.empty()) && \"Shuffle construction must be finalized.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9497, __extension__
__PRETTY_FUNCTION__))
;
9498 }
9499};
9500
9501Value *BoUpSLP::vectorizeOperand(TreeEntry *E, unsigned NodeIdx) {
9502 ArrayRef<Value *> VL = E->getOperand(NodeIdx);
9503 const unsigned VF = VL.size();
9504 InstructionsState S = getSameOpcode(VL, *TLI);
9505 // Special processing for GEPs bundle, which may include non-gep values.
9506 if (!S.getOpcode() && VL.front()->getType()->isPointerTy()) {
9507 const auto *It =
9508 find_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); });
9509 if (It != VL.end())
9510 S = getSameOpcode(*It, *TLI);
9511 }
9512 if (S.getOpcode()) {
9513 if (TreeEntry *VE = getTreeEntry(S.OpValue);
9514 VE && VE->isSame(VL) &&
9515 (any_of(VE->UserTreeIndices,
9516 [E, NodeIdx](const EdgeInfo &EI) {
9517 return EI.UserTE == E && EI.EdgeIdx == NodeIdx;
9518 }) ||
9519 any_of(VectorizableTree,
9520 [E, NodeIdx, VE](const std::unique_ptr<TreeEntry> &TE) {
9521 return TE->isOperandGatherNode({E, NodeIdx}) &&
9522 VE->isSame(TE->Scalars);
9523 }))) {
9524 auto FinalShuffle = [&](Value *V, ArrayRef<int> Mask) {
9525 ShuffleInstructionBuilder ShuffleBuilder(Builder, *this);
9526 ShuffleBuilder.add(V, Mask);
9527 return ShuffleBuilder.finalize(std::nullopt);
9528 };
9529 Value *V = vectorizeTree(VE);
9530 if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
9531 if (!VE->ReuseShuffleIndices.empty()) {
9532 // Reshuffle to get only unique values.
9533 // If some of the scalars are duplicated in the vectorization
9534 // tree entry, we do not vectorize them but instead generate a
9535 // mask for the reuses. But if there are several users of the
9536 // same entry, they may have different vectorization factors.
9537 // This is especially important for PHI nodes. In this case, we
9538 // need to adapt the resulting instruction for the user
9539 // vectorization factor and have to reshuffle it again to take
9540 // only unique elements of the vector. Without this code the
9541 // function incorrectly returns reduced vector instruction with
9542 // the same elements, not with the unique ones.
9543
9544 // block:
9545 // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
9546 // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
9547 // ... (use %2)
9548 // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
9549 // br %block
9550 SmallVector<int> UniqueIdxs(VF, PoisonMaskElem);
9551 SmallSet<int, 4> UsedIdxs;
9552 int Pos = 0;
9553 for (int Idx : VE->ReuseShuffleIndices) {
9554 if (Idx != static_cast<int>(VF) && Idx != PoisonMaskElem &&
9555 UsedIdxs.insert(Idx).second)
9556 UniqueIdxs[Idx] = Pos;
9557 ++Pos;
9558 }
9559 assert(VF >= UsedIdxs.size() && "Expected vectorization factor "(static_cast <bool> (VF >= UsedIdxs.size() &&
"Expected vectorization factor " "less than original vector size."
) ? void (0) : __assert_fail ("VF >= UsedIdxs.size() && \"Expected vectorization factor \" \"less than original vector size.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9560, __extension__
__PRETTY_FUNCTION__))
9560 "less than original vector size.")(static_cast <bool> (VF >= UsedIdxs.size() &&
"Expected vectorization factor " "less than original vector size."
) ? void (0) : __assert_fail ("VF >= UsedIdxs.size() && \"Expected vectorization factor \" \"less than original vector size.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9560, __extension__
__PRETTY_FUNCTION__))
;
9561 UniqueIdxs.append(VF - UsedIdxs.size(), PoisonMaskElem);
9562 V = FinalShuffle(V, UniqueIdxs);
9563 } else {
9564 assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&(static_cast <bool> (VF < cast<FixedVectorType>
(V->getType())->getNumElements() && "Expected vectorization factor less "
"than original vector size.") ? void (0) : __assert_fail ("VF < cast<FixedVectorType>(V->getType())->getNumElements() && \"Expected vectorization factor less \" \"than original vector size.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9566, __extension__
__PRETTY_FUNCTION__))
9565 "Expected vectorization factor less "(static_cast <bool> (VF < cast<FixedVectorType>
(V->getType())->getNumElements() && "Expected vectorization factor less "
"than original vector size.") ? void (0) : __assert_fail ("VF < cast<FixedVectorType>(V->getType())->getNumElements() && \"Expected vectorization factor less \" \"than original vector size.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9566, __extension__
__PRETTY_FUNCTION__))
9566 "than original vector size.")(static_cast <bool> (VF < cast<FixedVectorType>
(V->getType())->getNumElements() && "Expected vectorization factor less "
"than original vector size.") ? void (0) : __assert_fail ("VF < cast<FixedVectorType>(V->getType())->getNumElements() && \"Expected vectorization factor less \" \"than original vector size.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9566, __extension__
__PRETTY_FUNCTION__))
;
9567 SmallVector<int> UniformMask(VF, 0);
9568 std::iota(UniformMask.begin(), UniformMask.end(), 0);
9569 V = FinalShuffle(V, UniformMask);
9570 }
9571 }
9572 // Need to update the operand gather node, if actually the operand is not a
9573 // vectorized node, but the buildvector/gather node, which matches one of
9574 // the vectorized nodes.
9575 if (find_if(VE->UserTreeIndices, [&](const EdgeInfo &EI) {
9576 return EI.UserTE == E && EI.EdgeIdx == NodeIdx;
9577 }) == VE->UserTreeIndices.end()) {
9578 auto *It = find_if(
9579 VectorizableTree, [&](const std::unique_ptr<TreeEntry> &TE) {
9580 return TE->State == TreeEntry::NeedToGather &&
9581 TE->UserTreeIndices.front().UserTE == E &&
9582 TE->UserTreeIndices.front().EdgeIdx == NodeIdx;
9583 });
9584 assert(It != VectorizableTree.end() && "Expected gather node operand.")(static_cast <bool> (It != VectorizableTree.end() &&
"Expected gather node operand.") ? void (0) : __assert_fail (
"It != VectorizableTree.end() && \"Expected gather node operand.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9584, __extension__
__PRETTY_FUNCTION__))
;
9585 (*It)->VectorizedValue = V;
9586 }
9587 return V;
9588 }
9589 }
9590
9591 // Find the corresponding gather entry and vectorize it.
9592 // Allows to be more accurate with tree/graph transformations, checks for the
9593 // correctness of the transformations in many cases.
9594 auto *I = find_if(VectorizableTree,
9595 [E, NodeIdx](const std::unique_ptr<TreeEntry> &TE) {
9596 return TE->isOperandGatherNode({E, NodeIdx});
9597 });
9598 assert(I != VectorizableTree.end() && "Gather node is not in the graph.")(static_cast <bool> (I != VectorizableTree.end() &&
"Gather node is not in the graph.") ? void (0) : __assert_fail
("I != VectorizableTree.end() && \"Gather node is not in the graph.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9598, __extension__
__PRETTY_FUNCTION__))
;
9599 assert(I->get()->UserTreeIndices.size() == 1 &&(static_cast <bool> (I->get()->UserTreeIndices.size
() == 1 && "Expected only single user for the gather node."
) ? void (0) : __assert_fail ("I->get()->UserTreeIndices.size() == 1 && \"Expected only single user for the gather node.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9600, __extension__
__PRETTY_FUNCTION__))
9600 "Expected only single user for the gather node.")(static_cast <bool> (I->get()->UserTreeIndices.size
() == 1 && "Expected only single user for the gather node."
) ? void (0) : __assert_fail ("I->get()->UserTreeIndices.size() == 1 && \"Expected only single user for the gather node.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9600, __extension__
__PRETTY_FUNCTION__))
;
9601 assert(I->get()->isSame(VL) && "Expected same list of scalars.")(static_cast <bool> (I->get()->isSame(VL) &&
"Expected same list of scalars.") ? void (0) : __assert_fail
("I->get()->isSame(VL) && \"Expected same list of scalars.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9601, __extension__
__PRETTY_FUNCTION__))
;
9602 IRBuilder<>::InsertPointGuard Guard(Builder);
9603 if (E->getOpcode() != Instruction::InsertElement &&
9604 E->getOpcode() != Instruction::PHI) {
9605 Instruction *LastInst = EntryToLastInstruction.lookup(E);
9606 assert(LastInst && "Failed to find last instruction in bundle")(static_cast <bool> (LastInst && "Failed to find last instruction in bundle"
) ? void (0) : __assert_fail ("LastInst && \"Failed to find last instruction in bundle\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9606, __extension__
__PRETTY_FUNCTION__))
;
9607 Builder.SetInsertPoint(LastInst);
9608 }
9609 return vectorizeTree(I->get());
9610}
9611
9612template <typename BVTy, typename ResTy, typename... Args>
9613ResTy BoUpSLP::processBuildVector(const TreeEntry *E, Args &...Params) {
9614 assert(E->State == TreeEntry::NeedToGather && "Expected gather node.")(static_cast <bool> (E->State == TreeEntry::NeedToGather
&& "Expected gather node.") ? void (0) : __assert_fail
("E->State == TreeEntry::NeedToGather && \"Expected gather node.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9614, __extension__
__PRETTY_FUNCTION__))
;
9615 unsigned VF = E->getVectorFactor();
9616
9617 bool NeedFreeze = false;
9618 SmallVector<int> ReuseShuffleIndicies(E->ReuseShuffleIndices.begin(),
9619 E->ReuseShuffleIndices.end());
9620 SmallVector<Value *> GatheredScalars(E->Scalars.begin(), E->Scalars.end());
9621 // Build a mask out of the reorder indices and reorder scalars per this
9622 // mask.
9623 SmallVector<int> ReorderMask;
9624 inversePermutation(E->ReorderIndices, ReorderMask);
9625 if (!ReorderMask.empty())
9626 reorderScalars(GatheredScalars, ReorderMask);
9627 auto FindReusedSplat = [&](SmallVectorImpl<int> &Mask) {
9628 if (!isSplat(E->Scalars) || none_of(E->Scalars, [](Value *V) {
9629 return isa<UndefValue>(V) && !isa<PoisonValue>(V);
9630 }))
9631 return false;
9632 TreeEntry *UserTE = E->UserTreeIndices.back().UserTE;
9633 unsigned EdgeIdx = E->UserTreeIndices.back().EdgeIdx;
9634 if (UserTE->getNumOperands() != 2)
9635 return false;
9636 auto *It =
9637 find_if(VectorizableTree, [=](const std::unique_ptr<TreeEntry> &TE) {
9638 return find_if(TE->UserTreeIndices, [=](const EdgeInfo &EI) {
9639 return EI.UserTE == UserTE && EI.EdgeIdx != EdgeIdx;
9640 }) != TE->UserTreeIndices.end();
9641 });
9642 if (It == VectorizableTree.end())
9643 return false;
9644 unsigned I =
9645 *find_if_not(Mask, [](int Idx) { return Idx == PoisonMaskElem; });
9646 int Sz = Mask.size();
9647 if (all_of(Mask, [Sz](int Idx) { return Idx < 2 * Sz; }) &&
9648 ShuffleVectorInst::isIdentityMask(Mask))
9649 std::iota(Mask.begin(), Mask.end(), 0);
9650 else
9651 std::fill(Mask.begin(), Mask.end(), I);
9652 return true;
9653 };
9654 BVTy ShuffleBuilder(Params...);
9655 ResTy Res = ResTy();
9656 SmallVector<int> Mask;
9657 SmallVector<int> ExtractMask;
9658 std::optional<TargetTransformInfo::ShuffleKind> ExtractShuffle;
9659 std::optional<TargetTransformInfo::ShuffleKind> GatherShuffle;
9660 SmallVector<const TreeEntry *> Entries;
9661 Type *ScalarTy = GatheredScalars.front()->getType();
9662 if (!all_of(GatheredScalars, UndefValue::classof)) {
9663 // Check for gathered extracts.
9664 ExtractShuffle = tryToGatherExtractElements(GatheredScalars, ExtractMask);
9665 SmallVector<Value *> IgnoredVals;
9666 if (UserIgnoreList)
9667 IgnoredVals.assign(UserIgnoreList->begin(), UserIgnoreList->end());
9668 bool Resized = false;
9669 if (Value *VecBase = ShuffleBuilder.adjustExtracts(E, ExtractMask))
9670 if (auto *VecBaseTy = dyn_cast<FixedVectorType>(VecBase->getType()))
9671 if (VF == VecBaseTy->getNumElements() && GatheredScalars.size() != VF) {
9672 Resized = true;
9673 GatheredScalars.append(VF - GatheredScalars.size(),
9674 PoisonValue::get(ScalarTy));
9675 }
9676 // Gather extracts after we check for full matched gathers only.
9677 if (ExtractShuffle || E->getOpcode() != Instruction::Load ||
9678 E->isAltShuffle() ||
9679 all_of(E->Scalars, [this](Value *V) { return getTreeEntry(V); }) ||
9680 isSplat(E->Scalars) ||
9681 (E->Scalars != GatheredScalars && GatheredScalars.size() <= 2)) {
9682 GatherShuffle = isGatherShuffledEntry(E, GatheredScalars, Mask, Entries);
9683 }
9684 if (GatherShuffle) {
9685 if (Value *Delayed = ShuffleBuilder.needToDelay(E, Entries)) {
9686 // Delay emission of gathers which are not ready yet.
9687 PostponedGathers.insert(E);
9688 // Postpone gather emission, will be emitted after the end of the
9689 // process to keep correct order.
9690 return Delayed;
9691 }
9692 assert((Entries.size() == 1 || Entries.size() == 2) &&(static_cast <bool> ((Entries.size() == 1 || Entries.size
() == 2) && "Expected shuffle of 1 or 2 entries.") ? void
(0) : __assert_fail ("(Entries.size() == 1 || Entries.size() == 2) && \"Expected shuffle of 1 or 2 entries.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9693, __extension__
__PRETTY_FUNCTION__))
9693 "Expected shuffle of 1 or 2 entries.")(static_cast <bool> ((Entries.size() == 1 || Entries.size
() == 2) && "Expected shuffle of 1 or 2 entries.") ? void
(0) : __assert_fail ("(Entries.size() == 1 || Entries.size() == 2) && \"Expected shuffle of 1 or 2 entries.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9693, __extension__
__PRETTY_FUNCTION__))
;
9694 if (*GatherShuffle == TTI::SK_PermuteSingleSrc &&
9695 Entries.front()->isSame(E->Scalars)) {
9696 // Perfect match in the graph, will reuse the previously vectorized
9697 // node. Cost is 0.
9698 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: perfect diamond match for gather bundle that starts with "
<< *E->Scalars.front() << ".\n"; } } while (false
)
9699 dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: perfect diamond match for gather bundle that starts with "
<< *E->Scalars.front() << ".\n"; } } while (false
)
9700 << "SLP: perfect diamond match for gather bundle that starts with "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: perfect diamond match for gather bundle that starts with "
<< *E->Scalars.front() << ".\n"; } } while (false
)
9701 << *E->Scalars.front() << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: perfect diamond match for gather bundle that starts with "
<< *E->Scalars.front() << ".\n"; } } while (false
)
;
9702 // Restore the mask for previous partially matched values.
9703 for (auto [I, V] : enumerate(E->Scalars)) {
9704 if (isa<PoisonValue>(V)) {
9705 Mask[I] = PoisonMaskElem;
9706 continue;
9707 }
9708 if (Mask[I] == PoisonMaskElem)
9709 Mask[I] = Entries.front()->findLaneForValue(V);
9710 }
9711 ShuffleBuilder.add(Entries.front()->VectorizedValue, Mask);
9712 Res = ShuffleBuilder.finalize(E->ReuseShuffleIndices);
9713 return Res;
9714 }
9715 if (!Resized) {
9716 unsigned VF1 = Entries.front()->getVectorFactor();
9717 unsigned VF2 = Entries.back()->getVectorFactor();
9718 if ((VF == VF1 || VF == VF2) && GatheredScalars.size() != VF)
9719 GatheredScalars.append(VF - GatheredScalars.size(),
9720 PoisonValue::get(ScalarTy));
9721 }
9722 // Remove shuffled elements from list of gathers.
9723 for (int I = 0, Sz = Mask.size(); I < Sz; ++I) {
9724 if (Mask[I] != PoisonMaskElem)
9725 GatheredScalars[I] = PoisonValue::get(ScalarTy);
9726 }
9727 }
9728 }
9729 auto TryPackScalars = [&](SmallVectorImpl<Value *> &Scalars,
9730 SmallVectorImpl<int> &ReuseMask,
9731 bool IsRootPoison) {
9732 // For splats with can emit broadcasts instead of gathers, so try to find
9733 // such sequences.
9734 bool IsSplat = IsRootPoison && isSplat(Scalars) &&
9735 (Scalars.size() > 2 || Scalars.front() == Scalars.back());
9736 Scalars.append(VF - Scalars.size(), PoisonValue::get(ScalarTy));
9737 SmallVector<int> UndefPos;
9738 DenseMap<Value *, unsigned> UniquePositions;
9739 // Gather unique non-const values and all constant values.
9740 // For repeated values, just shuffle them.
9741 int NumNonConsts = 0;
9742 int SinglePos = 0;
9743 for (auto [I, V] : enumerate(Scalars)) {
9744 if (isa<UndefValue>(V)) {
9745 if (!isa<PoisonValue>(V)) {
9746 ReuseMask[I] = I;
9747 UndefPos.push_back(I);
9748 }
9749 continue;
9750 }
9751 if (isConstant(V)) {
9752 ReuseMask[I] = I;
9753 continue;
9754 }
9755 ++NumNonConsts;
9756 SinglePos = I;
9757 Value *OrigV = V;
9758 Scalars[I] = PoisonValue::get(ScalarTy);
9759 if (IsSplat) {
9760 Scalars.front() = OrigV;
9761 ReuseMask[I] = 0;
9762 } else {
9763 const auto Res = UniquePositions.try_emplace(OrigV, I);
9764 Scalars[Res.first->second] = OrigV;
9765 ReuseMask[I] = Res.first->second;
9766 }
9767 }
9768 if (NumNonConsts == 1) {
9769 // Restore single insert element.
9770 if (IsSplat) {
9771 ReuseMask.assign(VF, PoisonMaskElem);
9772 std::swap(Scalars.front(), Scalars[SinglePos]);
9773 if (!UndefPos.empty() && UndefPos.front() == 0)
9774 Scalars.front() = UndefValue::get(ScalarTy);
9775 }
9776 ReuseMask[SinglePos] = SinglePos;
9777 } else if (!UndefPos.empty() && IsSplat) {
9778 // For undef values, try to replace them with the simple broadcast.
9779 // We can do it if the broadcasted value is guaranteed to be
9780 // non-poisonous, or by freezing the incoming scalar value first.
9781 auto *It = find_if(Scalars, [this, E](Value *V) {
9782 return !isa<UndefValue>(V) &&
9783 (getTreeEntry(V) || isGuaranteedNotToBePoison(V) ||
9784 (E->UserTreeIndices.size() == 1 &&
9785 any_of(V->uses(), [E](const Use &U) {
9786 // Check if the value already used in the same operation in
9787 // one of the nodes already.
9788 return E->UserTreeIndices.front().EdgeIdx !=
9789 U.getOperandNo() &&
9790 is_contained(
9791 E->UserTreeIndices.front().UserTE->Scalars,
9792 U.getUser());
9793 })));
9794 });
9795 if (It != Scalars.end()) {
9796 // Replace undefs by the non-poisoned scalars and emit broadcast.
9797 int Pos = std::distance(Scalars.begin(), It);
9798 for_each(UndefPos, [&](int I) {
9799 // Set the undef position to the non-poisoned scalar.
9800 ReuseMask[I] = Pos;
9801 // Replace the undef by the poison, in the mask it is replaced by
9802 // non-poisoned scalar already.
9803 if (I != Pos)
9804 Scalars[I] = PoisonValue::get(ScalarTy);
9805 });
9806 } else {
9807 // Replace undefs by the poisons, emit broadcast and then emit
9808 // freeze.
9809 for_each(UndefPos, [&](int I) {
9810 ReuseMask[I] = PoisonMaskElem;
9811 if (isa<UndefValue>(Scalars[I]))
9812 Scalars[I] = PoisonValue::get(ScalarTy);
9813 });
9814 NeedFreeze = true;
9815 }
9816 }
9817 };
9818 if (ExtractShuffle || GatherShuffle) {
9819 bool IsNonPoisoned = true;
9820 bool IsUsedInExpr = false;
9821 Value *Vec1 = nullptr;
9822 if (ExtractShuffle) {
9823 // Gather of extractelements can be represented as just a shuffle of
9824 // a single/two vectors the scalars are extracted from.
9825 // Find input vectors.
9826 Value *Vec2 = nullptr;
9827 for (unsigned I = 0, Sz = ExtractMask.size(); I < Sz; ++I) {
9828 if (ExtractMask[I] == PoisonMaskElem ||
9829 (!Mask.empty() && Mask[I] != PoisonMaskElem)) {
9830 ExtractMask[I] = PoisonMaskElem;
9831 continue;
9832 }
9833 if (isa<UndefValue>(E->Scalars[I]))
9834 continue;
9835 auto *EI = cast<ExtractElementInst>(E->Scalars[I]);
9836 if (!Vec1) {
9837 Vec1 = EI->getVectorOperand();
9838 } else if (Vec1 != EI->getVectorOperand()) {
9839 assert((!Vec2 || Vec2 == EI->getVectorOperand()) &&(static_cast <bool> ((!Vec2 || Vec2 == EI->getVectorOperand
()) && "Expected only 1 or 2 vectors shuffle.") ? void
(0) : __assert_fail ("(!Vec2 || Vec2 == EI->getVectorOperand()) && \"Expected only 1 or 2 vectors shuffle.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9840, __extension__
__PRETTY_FUNCTION__))
9840 "Expected only 1 or 2 vectors shuffle.")(static_cast <bool> ((!Vec2 || Vec2 == EI->getVectorOperand
()) && "Expected only 1 or 2 vectors shuffle.") ? void
(0) : __assert_fail ("(!Vec2 || Vec2 == EI->getVectorOperand()) && \"Expected only 1 or 2 vectors shuffle.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9840, __extension__
__PRETTY_FUNCTION__))
;
9841 Vec2 = EI->getVectorOperand();
9842 }
9843 }
9844 if (Vec2) {
9845 IsNonPoisoned &=
9846 isGuaranteedNotToBePoison(Vec1) && isGuaranteedNotToBePoison(Vec2);
9847 ShuffleBuilder.add(Vec1, Vec2, ExtractMask);
9848 } else if (Vec1) {
9849 IsUsedInExpr = FindReusedSplat(ExtractMask);
9850 ShuffleBuilder.add(Vec1, ExtractMask);
9851 IsNonPoisoned &= isGuaranteedNotToBePoison(Vec1);
9852 } else {
9853 ShuffleBuilder.add(PoisonValue::get(FixedVectorType::get(
9854 ScalarTy, GatheredScalars.size())),
9855 ExtractMask);
9856 }
9857 }
9858 if (GatherShuffle) {
9859 if (Entries.size() == 1) {
9860 IsUsedInExpr = FindReusedSplat(Mask);
9861 ShuffleBuilder.add(Entries.front()->VectorizedValue, Mask);
9862 IsNonPoisoned &=
9863 isGuaranteedNotToBePoison(Entries.front()->VectorizedValue);
9864 } else {
9865 ShuffleBuilder.add(Entries.front()->VectorizedValue,
9866 Entries.back()->VectorizedValue, Mask);
9867 IsNonPoisoned &=
9868 isGuaranteedNotToBePoison(Entries.front()->VectorizedValue) &&
9869 isGuaranteedNotToBePoison(Entries.back()->VectorizedValue);
9870 }
9871 }
9872 // Try to figure out best way to combine values: build a shuffle and insert
9873 // elements or just build several shuffles.
9874 // Insert non-constant scalars.
9875 SmallVector<Value *> NonConstants(GatheredScalars);
9876 int EMSz = ExtractMask.size();
9877 int MSz = Mask.size();
9878 // Try to build constant vector and shuffle with it only if currently we
9879 // have a single permutation and more than 1 scalar constants.
9880 bool IsSingleShuffle = !ExtractShuffle || !GatherShuffle;
9881 bool IsIdentityShuffle =
9882 (ExtractShuffle.value_or(TTI::SK_PermuteTwoSrc) ==
9883 TTI::SK_PermuteSingleSrc &&
9884 none_of(ExtractMask, [&](int I) { return I >= EMSz; }) &&
9885 ShuffleVectorInst::isIdentityMask(ExtractMask)) ||
9886 (GatherShuffle.value_or(TTI::SK_PermuteTwoSrc) ==
9887 TTI::SK_PermuteSingleSrc &&
9888 none_of(Mask, [&](int I) { return I >= MSz; }) &&
9889 ShuffleVectorInst::isIdentityMask(Mask));
9890 bool EnoughConstsForShuffle =
9891 IsSingleShuffle &&
9892 (none_of(GatheredScalars,
9893 [](Value *V) {
9894 return isa<UndefValue>(V) && !isa<PoisonValue>(V);
9895 }) ||
9896 any_of(GatheredScalars,
9897 [](Value *V) {
9898 return isa<Constant>(V) && !isa<UndefValue>(V);
9899 })) &&
9900 (!IsIdentityShuffle ||
9901 (GatheredScalars.size() == 2 &&
9902 any_of(GatheredScalars,
9903 [](Value *V) { return !isa<UndefValue>(V); })) ||
9904 count_if(GatheredScalars, [](Value *V) {
9905 return isa<Constant>(V) && !isa<PoisonValue>(V);
9906 }) > 1);
9907 // NonConstants array contains just non-constant values, GatheredScalars
9908 // contains only constant to build final vector and then shuffle.
9909 for (int I = 0, Sz = GatheredScalars.size(); I < Sz; ++I) {
9910 if (EnoughConstsForShuffle && isa<Constant>(GatheredScalars[I]))
9911 NonConstants[I] = PoisonValue::get(ScalarTy);
9912 else
9913 GatheredScalars[I] = PoisonValue::get(ScalarTy);
9914 }
9915 // Generate constants for final shuffle and build a mask for them.
9916 if (!all_of(GatheredScalars, PoisonValue::classof)) {
9917 SmallVector<int> BVMask(GatheredScalars.size(), PoisonMaskElem);
9918 TryPackScalars(GatheredScalars, BVMask, /*IsRootPoison=*/true);
9919 Value *BV = ShuffleBuilder.gather(GatheredScalars);
9920 ShuffleBuilder.add(BV, BVMask);
9921 }
9922 if (all_of(NonConstants, [=](Value *V) {
9923 return isa<PoisonValue>(V) ||
9924 (IsSingleShuffle && ((IsIdentityShuffle &&
9925 IsNonPoisoned) || IsUsedInExpr) && isa<UndefValue>(V));
9926 }))
9927 Res = ShuffleBuilder.finalize(E->ReuseShuffleIndices);
9928 else
9929 Res = ShuffleBuilder.finalize(
9930 E->ReuseShuffleIndices, E->Scalars.size(),
9931 [&](Value *&Vec, SmallVectorImpl<int> &Mask) {
9932 TryPackScalars(NonConstants, Mask, /*IsRootPoison=*/false);
9933 Vec = ShuffleBuilder.gather(NonConstants, Vec);
9934 });
9935 } else if (!allConstant(GatheredScalars)) {
9936 // Gather unique scalars and all constants.
9937 SmallVector<int> ReuseMask(GatheredScalars.size(), PoisonMaskElem);
9938 TryPackScalars(GatheredScalars, ReuseMask, /*IsRootPoison=*/true);
9939 Value *BV = ShuffleBuilder.gather(GatheredScalars);
9940 ShuffleBuilder.add(BV, ReuseMask);
9941 Res = ShuffleBuilder.finalize(E->ReuseShuffleIndices);
9942 } else {
9943 // Gather all constants.
9944 SmallVector<int> Mask(E->Scalars.size(), PoisonMaskElem);
9945 for (auto [I, V] : enumerate(E->Scalars)) {
9946 if (!isa<PoisonValue>(V))
9947 Mask[I] = I;
9948 }
9949 Value *BV = ShuffleBuilder.gather(E->Scalars);
9950 ShuffleBuilder.add(BV, Mask);
9951 Res = ShuffleBuilder.finalize(E->ReuseShuffleIndices);
9952 }
9953
9954 if (NeedFreeze)
9955 Res = ShuffleBuilder.createFreeze(Res);
9956 return Res;
9957}
9958
9959Value *BoUpSLP::createBuildVector(const TreeEntry *E) {
9960 return processBuildVector<ShuffleInstructionBuilder, Value *>(E, Builder,
9961 *this);
9962}
9963
9964Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
9965 IRBuilder<>::InsertPointGuard Guard(Builder);
9966
9967 if (E->VectorizedValue) {
9968 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Diamond merged for " <<
*E->Scalars[0] << ".\n"; } } while (false)
;
9969 return E->VectorizedValue;
9970 }
9971
9972 if (E->State == TreeEntry::NeedToGather) {
9973 if (E->getMainOp() && E->Idx == 0)
9974 setInsertPointAfterBundle(E);
9975 Value *Vec = createBuildVector(E);
9976 E->VectorizedValue = Vec;
9977 return Vec;
9978 }
9979
9980 auto FinalShuffle = [&](Value *V, const TreeEntry *E) {
9981 ShuffleInstructionBuilder ShuffleBuilder(Builder, *this);
9982 if (E->getOpcode() == Instruction::Store) {
9983 ArrayRef<int> Mask =
9984 ArrayRef(reinterpret_cast<const int *>(E->ReorderIndices.begin()),
9985 E->ReorderIndices.size());
9986 ShuffleBuilder.add(V, Mask);
9987 } else {
9988 ShuffleBuilder.addOrdered(V, E->ReorderIndices);
9989 }
9990 return ShuffleBuilder.finalize(E->ReuseShuffleIndices);
9991 };
9992
9993 assert((E->State == TreeEntry::Vectorize ||(static_cast <bool> ((E->State == TreeEntry::Vectorize
|| E->State == TreeEntry::ScatterVectorize) && "Unhandled state"
) ? void (0) : __assert_fail ("(E->State == TreeEntry::Vectorize || E->State == TreeEntry::ScatterVectorize) && \"Unhandled state\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9995, __extension__
__PRETTY_FUNCTION__))
9994 E->State == TreeEntry::ScatterVectorize) &&(static_cast <bool> ((E->State == TreeEntry::Vectorize
|| E->State == TreeEntry::ScatterVectorize) && "Unhandled state"
) ? void (0) : __assert_fail ("(E->State == TreeEntry::Vectorize || E->State == TreeEntry::ScatterVectorize) && \"Unhandled state\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9995, __extension__
__PRETTY_FUNCTION__))
9995 "Unhandled state")(static_cast <bool> ((E->State == TreeEntry::Vectorize
|| E->State == TreeEntry::ScatterVectorize) && "Unhandled state"
) ? void (0) : __assert_fail ("(E->State == TreeEntry::Vectorize || E->State == TreeEntry::ScatterVectorize) && \"Unhandled state\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9995, __extension__
__PRETTY_FUNCTION__))
;
9996 unsigned ShuffleOrOp =
9997 E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
9998 Instruction *VL0 = E->getMainOp();
9999 Type *ScalarTy = VL0->getType();
10000 if (auto *Store = dyn_cast<StoreInst>(VL0))
10001 ScalarTy = Store->getValueOperand()->getType();
10002 else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
10003 ScalarTy = IE->getOperand(1)->getType();
10004 auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
10005 switch (ShuffleOrOp) {
10006 case Instruction::PHI: {
10007 assert((E->ReorderIndices.empty() ||(static_cast <bool> ((E->ReorderIndices.empty() || E
!= VectorizableTree.front().get() || !E->UserTreeIndices.
empty()) && "PHI reordering is free.") ? void (0) : __assert_fail
("(E->ReorderIndices.empty() || E != VectorizableTree.front().get() || !E->UserTreeIndices.empty()) && \"PHI reordering is free.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10010, __extension__
__PRETTY_FUNCTION__))
10008 E != VectorizableTree.front().get() ||(static_cast <bool> ((E->ReorderIndices.empty() || E
!= VectorizableTree.front().get() || !E->UserTreeIndices.
empty()) && "PHI reordering is free.") ? void (0) : __assert_fail
("(E->ReorderIndices.empty() || E != VectorizableTree.front().get() || !E->UserTreeIndices.empty()) && \"PHI reordering is free.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10010, __extension__
__PRETTY_FUNCTION__))
10009 !E->UserTreeIndices.empty()) &&(static_cast <bool> ((E->ReorderIndices.empty() || E
!= VectorizableTree.front().get() || !E->UserTreeIndices.
empty()) && "PHI reordering is free.") ? void (0) : __assert_fail
("(E->ReorderIndices.empty() || E != VectorizableTree.front().get() || !E->UserTreeIndices.empty()) && \"PHI reordering is free.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10010, __extension__
__PRETTY_FUNCTION__))
10010 "PHI reordering is free.")(static_cast <bool> ((E->ReorderIndices.empty() || E
!= VectorizableTree.front().get() || !E->UserTreeIndices.
empty()) && "PHI reordering is free.") ? void (0) : __assert_fail
("(E->ReorderIndices.empty() || E != VectorizableTree.front().get() || !E->UserTreeIndices.empty()) && \"PHI reordering is free.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10010, __extension__
__PRETTY_FUNCTION__))
;
10011 auto *PH = cast<PHINode>(VL0);
10012 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
10013 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
10014 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
10015 Value *V = NewPhi;
10016
10017 // Adjust insertion point once all PHI's have been generated.
10018 Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
10019 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
10020
10021 V = FinalShuffle(V, E);
10022
10023 E->VectorizedValue = V;
10024
10025 // PHINodes may have multiple entries from the same block. We want to
10026 // visit every block once.
10027 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
10028
10029 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
10030 ValueList Operands;
10031 BasicBlock *IBB = PH->getIncomingBlock(i);
10032
10033 // Stop emission if all incoming values are generated.
10034 if (NewPhi->getNumIncomingValues() == PH->getNumIncomingValues()) {
10035 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Diamond merged for " <<
*VL0 << ".\n"; } } while (false)
;
10036 return V;
10037 }
10038
10039 if (!VisitedBBs.insert(IBB).second) {
10040 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
10041 continue;
10042 }
10043
10044 Builder.SetInsertPoint(IBB->getTerminator());
10045 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
10046 Value *Vec = vectorizeOperand(E, i);
10047 NewPhi->addIncoming(Vec, IBB);
10048 }
10049
10050 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&(static_cast <bool> (NewPhi->getNumIncomingValues() ==
PH->getNumIncomingValues() && "Invalid number of incoming values"
) ? void (0) : __assert_fail ("NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() && \"Invalid number of incoming values\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10051, __extension__
__PRETTY_FUNCTION__))
10051 "Invalid number of incoming values")(static_cast <bool> (NewPhi->getNumIncomingValues() ==
PH->getNumIncomingValues() && "Invalid number of incoming values"
) ? void (0) : __assert_fail ("NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() && \"Invalid number of incoming values\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10051, __extension__
__PRETTY_FUNCTION__))
;
10052 return V;
10053 }
10054
10055 case Instruction::ExtractElement: {
10056 Value *V = E->getSingleOperand(0);
10057 setInsertPointAfterBundle(E);
10058 V = FinalShuffle(V, E);
10059 E->VectorizedValue = V;
10060 return V;
10061 }
10062 case Instruction::ExtractValue: {
10063 auto *LI = cast<LoadInst>(E->getSingleOperand(0));
10064 Builder.SetInsertPoint(LI);
10065 auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
10066 Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
10067 LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
10068 Value *NewV = propagateMetadata(V, E->Scalars);
10069 NewV = FinalShuffle(NewV, E);
10070 E->VectorizedValue = NewV;
10071 return NewV;
10072 }
10073 case Instruction::InsertElement: {
10074 assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique")(static_cast <bool> (E->ReuseShuffleIndices.empty() &&
"All inserts should be unique") ? void (0) : __assert_fail (
"E->ReuseShuffleIndices.empty() && \"All inserts should be unique\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10074, __extension__
__PRETTY_FUNCTION__))
;
10075 Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
10076 Value *V = vectorizeOperand(E, 1);
10077
10078 // Create InsertVector shuffle if necessary
10079 auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
10080 return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
10081 }));
10082 const unsigned NumElts =
10083 cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
10084 const unsigned NumScalars = E->Scalars.size();
10085
10086 unsigned Offset = *getInsertIndex(VL0);
10087 assert(Offset < NumElts && "Failed to find vector index offset")(static_cast <bool> (Offset < NumElts && "Failed to find vector index offset"
) ? void (0) : __assert_fail ("Offset < NumElts && \"Failed to find vector index offset\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10087, __extension__
__PRETTY_FUNCTION__))
;
10088
10089 // Create shuffle to resize vector
10090 SmallVector<int> Mask;
10091 if (!E->ReorderIndices.empty()) {
10092 inversePermutation(E->ReorderIndices, Mask);
10093 Mask.append(NumElts - NumScalars, PoisonMaskElem);
10094 } else {
10095 Mask.assign(NumElts, PoisonMaskElem);
10096 std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
10097 }
10098 // Create InsertVector shuffle if necessary
10099 bool IsIdentity = true;
10100 SmallVector<int> PrevMask(NumElts, PoisonMaskElem);
10101 Mask.swap(PrevMask);
10102 for (unsigned I = 0; I < NumScalars; ++I) {
10103 Value *Scalar = E->Scalars[PrevMask[I]];
10104 unsigned InsertIdx = *getInsertIndex(Scalar);
10105 IsIdentity &= InsertIdx - Offset == I;
10106 Mask[InsertIdx - Offset] = I;
10107 }
10108 if (!IsIdentity || NumElts != NumScalars) {
10109 V = Builder.CreateShuffleVector(V, Mask);
10110 if (auto *I = dyn_cast<Instruction>(V)) {
10111 GatherShuffleExtractSeq.insert(I);
10112 CSEBlocks.insert(I->getParent());
10113 }
10114 }
10115
10116 SmallVector<int> InsertMask(NumElts, PoisonMaskElem);
10117 for (unsigned I = 0; I < NumElts; I++) {
10118 if (Mask[I] != PoisonMaskElem)
10119 InsertMask[Offset + I] = I;
10120 }
10121 SmallBitVector UseMask =
10122 buildUseMask(NumElts, InsertMask, UseMask::UndefsAsMask);
10123 SmallBitVector IsFirstUndef =
10124 isUndefVector(FirstInsert->getOperand(0), UseMask);
10125 if ((!IsIdentity || Offset != 0 || !IsFirstUndef.all()) &&
10126 NumElts != NumScalars) {
10127 if (IsFirstUndef.all()) {
10128 if (!ShuffleVectorInst::isIdentityMask(InsertMask)) {
10129 SmallBitVector IsFirstPoison =
10130 isUndefVector<true>(FirstInsert->getOperand(0), UseMask);
10131 if (!IsFirstPoison.all()) {
10132 for (unsigned I = 0; I < NumElts; I++) {
10133 if (InsertMask[I] == PoisonMaskElem && !IsFirstPoison.test(I))
10134 InsertMask[I] = I + NumElts;
10135 }
10136 }
10137 V = Builder.CreateShuffleVector(
10138 V,
10139 IsFirstPoison.all() ? PoisonValue::get(V->getType())
10140 : FirstInsert->getOperand(0),
10141 InsertMask, cast<Instruction>(E->Scalars.back())->getName());
10142 if (auto *I = dyn_cast<Instruction>(V)) {
10143 GatherShuffleExtractSeq.insert(I);
10144 CSEBlocks.insert(I->getParent());
10145 }
10146 }
10147 } else {
10148 SmallBitVector IsFirstPoison =
10149 isUndefVector<true>(FirstInsert->getOperand(0), UseMask);
10150 for (unsigned I = 0; I < NumElts; I++) {
10151 if (InsertMask[I] == PoisonMaskElem)
10152 InsertMask[I] = IsFirstPoison.test(I) ? PoisonMaskElem : I;
10153 else
10154 InsertMask[I] += NumElts;
10155 }
10156 V = Builder.CreateShuffleVector(
10157 FirstInsert->getOperand(0), V, InsertMask,
10158 cast<Instruction>(E->Scalars.back())->getName());
10159 if (auto *I = dyn_cast<Instruction>(V)) {
10160 GatherShuffleExtractSeq.insert(I);
10161 CSEBlocks.insert(I->getParent());
10162 }
10163 }
10164 }
10165
10166 ++NumVectorInstructions;
10167 E->VectorizedValue = V;
10168 return V;
10169 }
10170 case Instruction::ZExt:
10171 case Instruction::SExt:
10172 case Instruction::FPToUI:
10173 case Instruction::FPToSI:
10174 case Instruction::FPExt:
10175 case Instruction::PtrToInt:
10176 case Instruction::IntToPtr:
10177 case Instruction::SIToFP:
10178 case Instruction::UIToFP:
10179 case Instruction::Trunc:
10180 case Instruction::FPTrunc:
10181 case Instruction::BitCast: {
10182 setInsertPointAfterBundle(E);
10183
10184 Value *InVec = vectorizeOperand(E, 0);
10185 if (E->VectorizedValue) {
10186 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Diamond merged for " <<
*VL0 << ".\n"; } } while (false)
;
10187 return E->VectorizedValue;
10188 }
10189
10190 auto *CI = cast<CastInst>(VL0);
10191 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
10192 V = FinalShuffle(V, E);
10193
10194 E->VectorizedValue = V;
10195 ++NumVectorInstructions;
10196 return V;
10197 }
10198 case Instruction::FCmp:
10199 case Instruction::ICmp: {
10200 setInsertPointAfterBundle(E);
10201
10202 Value *L = vectorizeOperand(E, 0);
10203 if (E->VectorizedValue) {
10204 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Diamond merged for " <<
*VL0 << ".\n"; } } while (false)
;
10205 return E->VectorizedValue;
10206 }
10207 Value *R = vectorizeOperand(E, 1);
10208 if (E->VectorizedValue) {
10209 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Diamond merged for " <<
*VL0 << ".\n"; } } while (false)
;
10210 return E->VectorizedValue;
10211 }
10212
10213 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
10214 Value *V = Builder.CreateCmp(P0, L, R);
10215 propagateIRFlags(V, E->Scalars, VL0);
10216 V = FinalShuffle(V, E);
10217
10218 E->VectorizedValue = V;
10219 ++NumVectorInstructions;
10220 return V;
10221 }
10222 case Instruction::Select: {
10223 setInsertPointAfterBundle(E);
10224
10225 Value *Cond = vectorizeOperand(E, 0);
10226 if (E->VectorizedValue) {
10227 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Diamond merged for " <<
*VL0 << ".\n"; } } while (false)
;
10228 return E->VectorizedValue;
10229 }
10230 Value *True = vectorizeOperand(E, 1);
10231 if (E->VectorizedValue) {
10232 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Diamond merged for " <<
*VL0 << ".\n"; } } while (false)
;
10233 return E->VectorizedValue;
10234 }
10235 Value *False = vectorizeOperand(E, 2);
10236 if (E->VectorizedValue) {
10237 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Diamond merged for " <<
*VL0 << ".\n"; } } while (false)
;
10238 return E->VectorizedValue;
10239 }
10240
10241 Value *V = Builder.CreateSelect(Cond, True, False);
10242 V = FinalShuffle(V, E);
10243
10244 E->VectorizedValue = V;
10245 ++NumVectorInstructions;
10246 return V;
10247 }
10248 case Instruction::FNeg: {
10249 setInsertPointAfterBundle(E);
10250
10251 Value *Op = vectorizeOperand(E, 0);
10252
10253 if (E->VectorizedValue) {
10254 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Diamond merged for " <<
*VL0 << ".\n"; } } while (false)
;
10255 return E->VectorizedValue;
10256 }
10257
10258 Value *V = Builder.CreateUnOp(
10259 static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
10260 propagateIRFlags(V, E->Scalars, VL0);
10261 if (auto *I = dyn_cast<Instruction>(V))
10262 V = propagateMetadata(I, E->Scalars);
10263
10264 V = FinalShuffle(V, E);
10265
10266 E->VectorizedValue = V;
10267 ++NumVectorInstructions;
10268
10269 return V;
10270 }
10271 case Instruction::Add:
10272 case Instruction::FAdd:
10273 case Instruction::Sub:
10274 case Instruction::FSub:
10275 case Instruction::Mul:
10276 case Instruction::FMul:
10277 case Instruction::UDiv:
10278 case Instruction::SDiv:
10279 case Instruction::FDiv:
10280 case Instruction::URem:
10281 case Instruction::SRem:
10282 case Instruction::FRem:
10283 case Instruction::Shl:
10284 case Instruction::LShr:
10285 case Instruction::AShr:
10286 case Instruction::And:
10287 case Instruction::Or:
10288 case Instruction::Xor: {
10289 setInsertPointAfterBundle(E);
10290
10291 Value *LHS = vectorizeOperand(E, 0);
10292 if (E->VectorizedValue) {
10293 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Diamond merged for " <<
*VL0 << ".\n"; } } while (false)
;
10294 return E->VectorizedValue;
10295 }
10296 Value *RHS = vectorizeOperand(E, 1);
10297 if (E->VectorizedValue) {
10298 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Diamond merged for " <<
*VL0 << ".\n"; } } while (false)
;
10299 return E->VectorizedValue;
10300 }
10301
10302 Value *V = Builder.CreateBinOp(
10303 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
10304 RHS);
10305 propagateIRFlags(V, E->Scalars, VL0);
10306 if (auto *I = dyn_cast<Instruction>(V))
10307 V = propagateMetadata(I, E->Scalars);
10308
10309 V = FinalShuffle(V, E);
10310
10311 E->VectorizedValue = V;
10312 ++NumVectorInstructions;
10313
10314 return V;
10315 }
10316 case Instruction::Load: {
10317 // Loads are inserted at the head of the tree because we don't want to
10318 // sink them all the way down past store instructions.
10319 setInsertPointAfterBundle(E);
10320
10321 LoadInst *LI = cast<LoadInst>(VL0);
10322 Instruction *NewLI;
10323 unsigned AS = LI->getPointerAddressSpace();
10324 Value *PO = LI->getPointerOperand();
10325 if (E->State == TreeEntry::Vectorize) {
10326 Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
10327 NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
10328
10329 // The pointer operand uses an in-tree scalar so we add the new BitCast
10330 // or LoadInst to ExternalUses list to make sure that an extract will
10331 // be generated in the future.
10332 if (TreeEntry *Entry = getTreeEntry(PO)) {
10333 // Find which lane we need to extract.
10334 unsigned FoundLane = Entry->findLaneForValue(PO);
10335 ExternalUses.emplace_back(
10336 PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
10337 }
10338 } else {
10339 assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state")(static_cast <bool> (E->State == TreeEntry::ScatterVectorize
&& "Unhandled state") ? void (0) : __assert_fail ("E->State == TreeEntry::ScatterVectorize && \"Unhandled state\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10339, __extension__
__PRETTY_FUNCTION__))
;
10340 Value *VecPtr = vectorizeOperand(E, 0);
10341 if (E->VectorizedValue) {
10342 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Diamond merged for " <<
*VL0 << ".\n"; } } while (false)
;
10343 return E->VectorizedValue;
10344 }
10345 // Use the minimum alignment of the gathered loads.
10346 Align CommonAlignment = LI->getAlign();
10347 for (Value *V : E->Scalars)
10348 CommonAlignment =
10349 std::min(CommonAlignment, cast<LoadInst>(V)->getAlign());
10350 NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
10351 }
10352 Value *V = propagateMetadata(NewLI, E->Scalars);
10353
10354 V = FinalShuffle(V, E);
10355 E->VectorizedValue = V;
10356 ++NumVectorInstructions;
10357 return V;
10358 }
10359 case Instruction::Store: {
10360 auto *SI = cast<StoreInst>(VL0);
10361 unsigned AS = SI->getPointerAddressSpace();
10362
10363 setInsertPointAfterBundle(E);
10364
10365 Value *VecValue = vectorizeOperand(E, 0);
10366 VecValue = FinalShuffle(VecValue, E);
10367
10368 Value *ScalarPtr = SI->getPointerOperand();
10369 Value *VecPtr = Builder.CreateBitCast(
10370 ScalarPtr, VecValue->getType()->getPointerTo(AS));
10371 StoreInst *ST =
10372 Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
10373
10374 // The pointer operand uses an in-tree scalar, so add the new BitCast or
10375 // StoreInst to ExternalUses to make sure that an extract will be
10376 // generated in the future.
10377 if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
10378 // Find which lane we need to extract.
10379 unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
10380 ExternalUses.push_back(ExternalUser(
10381 ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
10382 FoundLane));
10383 }
10384
10385 Value *V = propagateMetadata(ST, E->Scalars);
10386
10387 E->VectorizedValue = V;
10388 ++NumVectorInstructions;
10389 return V;
10390 }
10391 case Instruction::GetElementPtr: {
10392 auto *GEP0 = cast<GetElementPtrInst>(VL0);
10393 setInsertPointAfterBundle(E);
10394
10395 Value *Op0 = vectorizeOperand(E, 0);
10396 if (E->VectorizedValue) {
10397 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Diamond merged for " <<
*VL0 << ".\n"; } } while (false)
;
10398 return E->VectorizedValue;
10399 }
10400
10401 SmallVector<Value *> OpVecs;
10402 for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
10403 Value *OpVec = vectorizeOperand(E, J);
10404 if (E->VectorizedValue) {
10405 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Diamond merged for " <<
*VL0 << ".\n"; } } while (false)
;
10406 return E->VectorizedValue;
10407 }
10408 OpVecs.push_back(OpVec);
10409 }
10410
10411 Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
10412 if (Instruction *I = dyn_cast<GetElementPtrInst>(V)) {
10413 SmallVector<Value *> GEPs;
10414 for (Value *V : E->Scalars) {
10415 if (isa<GetElementPtrInst>(V))
10416 GEPs.push_back(V);
10417 }
10418 V = propagateMetadata(I, GEPs);
10419 }
10420
10421 V = FinalShuffle(V, E);
10422
10423 E->VectorizedValue = V;
10424 ++NumVectorInstructions;
10425
10426 return V;
10427 }
10428 case Instruction::Call: {
10429 CallInst *CI = cast<CallInst>(VL0);
10430 setInsertPointAfterBundle(E);
10431
10432 Intrinsic::ID IID = Intrinsic::not_intrinsic;
10433 if (Function *FI = CI->getCalledFunction())
10434 IID = FI->getIntrinsicID();
10435
10436 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
10437
10438 auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
10439 bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
10440 VecCallCosts.first <= VecCallCosts.second;
10441
10442 Value *ScalarArg = nullptr;
10443 std::vector<Value *> OpVecs;
10444 SmallVector<Type *, 2> TysForDecl;
10445 // Add return type if intrinsic is overloaded on it.
10446 if (isVectorIntrinsicWithOverloadTypeAtArg(IID, -1))
10447 TysForDecl.push_back(
10448 FixedVectorType::get(CI->getType(), E->Scalars.size()));
10449 for (int j = 0, e = CI->arg_size(); j < e; ++j) {
10450 ValueList OpVL;
10451 // Some intrinsics have scalar arguments. This argument should not be
10452 // vectorized.
10453 if (UseIntrinsic && isVectorIntrinsicWithScalarOpAtArg(IID, j)) {
10454 CallInst *CEI = cast<CallInst>(VL0);
10455 ScalarArg = CEI->getArgOperand(j);
10456 OpVecs.push_back(CEI->getArgOperand(j));
10457 if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
10458 TysForDecl.push_back(ScalarArg->getType());
10459 continue;
10460 }
10461
10462 Value *OpVec = vectorizeOperand(E, j);
10463 if (E->VectorizedValue) {
10464 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Diamond merged for " <<
*VL0 << ".\n"; } } while (false)
;
10465 return E->VectorizedValue;
10466 }
10467 LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: OpVec[" << j << "]: "
<< *OpVec << "\n"; } } while (false)
;
10468 OpVecs.push_back(OpVec);
10469 if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
10470 TysForDecl.push_back(OpVec->getType());
10471 }
10472
10473 Function *CF;
10474 if (!UseIntrinsic) {
10475 VFShape Shape =
10476 VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
10477 VecTy->getNumElements())),
10478 false /*HasGlobalPred*/);
10479 CF = VFDatabase(*CI).getVectorizedFunction(Shape);
10480 } else {
10481 CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
10482 }
10483
10484 SmallVector<OperandBundleDef, 1> OpBundles;
10485 CI->getOperandBundlesAsDefs(OpBundles);
10486 Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
10487
10488 // The scalar argument uses an in-tree scalar so we add the new vectorized
10489 // call to ExternalUses list to make sure that an extract will be
10490 // generated in the future.
10491 if (ScalarArg) {
10492 if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
10493 // Find which lane we need to extract.
10494 unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
10495 ExternalUses.push_back(
10496 ExternalUser(ScalarArg, cast<User>(V), FoundLane));
10497 }
10498 }
10499
10500 propagateIRFlags(V, E->Scalars, VL0);
10501 V = FinalShuffle(V, E);
10502
10503 E->VectorizedValue = V;
10504 ++NumVectorInstructions;
10505 return V;
10506 }
10507 case Instruction::ShuffleVector: {
10508 assert(E->isAltShuffle() &&(static_cast <bool> (E->isAltShuffle() && ((
Instruction::isBinaryOp(E->getOpcode()) && Instruction
::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E
->getOpcode()) && Instruction::isCast(E->getAltOpcode
())) || (isa<CmpInst>(VL0) && isa<CmpInst>
(E->getAltOp()))) && "Invalid Shuffle Vector Operand"
) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10514, __extension__
__PRETTY_FUNCTION__))
10509 ((Instruction::isBinaryOp(E->getOpcode()) &&(static_cast <bool> (E->isAltShuffle() && ((
Instruction::isBinaryOp(E->getOpcode()) && Instruction
::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E
->getOpcode()) && Instruction::isCast(E->getAltOpcode
())) || (isa<CmpInst>(VL0) && isa<CmpInst>
(E->getAltOp()))) && "Invalid Shuffle Vector Operand"
) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10514, __extension__
__PRETTY_FUNCTION__))
10510 Instruction::isBinaryOp(E->getAltOpcode())) ||(static_cast <bool> (E->isAltShuffle() && ((
Instruction::isBinaryOp(E->getOpcode()) && Instruction
::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E
->getOpcode()) && Instruction::isCast(E->getAltOpcode
())) || (isa<CmpInst>(VL0) && isa<CmpInst>
(E->getAltOp()))) && "Invalid Shuffle Vector Operand"
) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10514, __extension__
__PRETTY_FUNCTION__))
10511 (Instruction::isCast(E->getOpcode()) &&(static_cast <bool> (E->isAltShuffle() && ((
Instruction::isBinaryOp(E->getOpcode()) && Instruction
::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E
->getOpcode()) && Instruction::isCast(E->getAltOpcode
())) || (isa<CmpInst>(VL0) && isa<CmpInst>
(E->getAltOp()))) && "Invalid Shuffle Vector Operand"
) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10514, __extension__
__PRETTY_FUNCTION__))
10512 Instruction::isCast(E->getAltOpcode())) ||(static_cast <bool> (E->isAltShuffle() && ((
Instruction::isBinaryOp(E->getOpcode()) && Instruction
::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E
->getOpcode()) && Instruction::isCast(E->getAltOpcode
())) || (isa<CmpInst>(VL0) && isa<CmpInst>
(E->getAltOp()))) && "Invalid Shuffle Vector Operand"
) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10514, __extension__
__PRETTY_FUNCTION__))
10513 (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&(static_cast <bool> (E->isAltShuffle() && ((
Instruction::isBinaryOp(E->getOpcode()) && Instruction
::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E
->getOpcode()) && Instruction::isCast(E->getAltOpcode
())) || (isa<CmpInst>(VL0) && isa<CmpInst>
(E->getAltOp()))) && "Invalid Shuffle Vector Operand"
) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10514, __extension__
__PRETTY_FUNCTION__))
10514 "Invalid Shuffle Vector Operand")(static_cast <bool> (E->isAltShuffle() && ((
Instruction::isBinaryOp(E->getOpcode()) && Instruction
::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E
->getOpcode()) && Instruction::isCast(E->getAltOpcode
())) || (isa<CmpInst>(VL0) && isa<CmpInst>
(E->getAltOp()))) && "Invalid Shuffle Vector Operand"
) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10514, __extension__
__PRETTY_FUNCTION__))
;
10515
10516 Value *LHS = nullptr, *RHS = nullptr;
10517 if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
10518 setInsertPointAfterBundle(E);
10519 LHS = vectorizeOperand(E, 0);
10520 if (E->VectorizedValue) {
10521 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Diamond merged for " <<
*VL0 << ".\n"; } } while (false)
;
10522 return E->VectorizedValue;
10523 }
10524 RHS = vectorizeOperand(E, 1);
10525 } else {
10526 setInsertPointAfterBundle(E);
10527 LHS = vectorizeOperand(E, 0);
10528 }
10529 if (E->VectorizedValue) {
10530 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Diamond merged for " <<
*VL0 << ".\n"; } } while (false)
;
10531 return E->VectorizedValue;
10532 }
10533
10534 Value *V0, *V1;
10535 if (Instruction::isBinaryOp(E->getOpcode())) {
10536 V0 = Builder.CreateBinOp(
10537 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
10538 V1 = Builder.CreateBinOp(
10539 static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
10540 } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
10541 V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
10542 auto *AltCI = cast<CmpInst>(E->getAltOp());
10543 CmpInst::Predicate AltPred = AltCI->getPredicate();
10544 V1 = Builder.CreateCmp(AltPred, LHS, RHS);
10545 } else {
10546 V0 = Builder.CreateCast(
10547 static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
10548 V1 = Builder.CreateCast(
10549 static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
10550 }
10551 // Add V0 and V1 to later analysis to try to find and remove matching
10552 // instruction, if any.
10553 for (Value *V : {V0, V1}) {
10554 if (auto *I = dyn_cast<Instruction>(V)) {
10555 GatherShuffleExtractSeq.insert(I);
10556 CSEBlocks.insert(I->getParent());
10557 }
10558 }
10559
10560 // Create shuffle to take alternate operations from the vector.
10561 // Also, gather up main and alt scalar ops to propagate IR flags to
10562 // each vector operation.
10563 ValueList OpScalars, AltScalars;
10564 SmallVector<int> Mask;
10565 buildShuffleEntryMask(
10566 E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
10567 [E, this](Instruction *I) {
10568 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode")(static_cast <bool> (E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"
) ? void (0) : __assert_fail ("E->isOpcodeOrAlt(I) && \"Unexpected main/alternate opcode\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10568, __extension__
__PRETTY_FUNCTION__))
;
10569 return isAlternateInstruction(I, E->getMainOp(), E->getAltOp(),
10570 *TLI);
10571 },
10572 Mask, &OpScalars, &AltScalars);
10573
10574 propagateIRFlags(V0, OpScalars);
10575 propagateIRFlags(V1, AltScalars);
10576
10577 Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
10578 if (auto *I = dyn_cast<Instruction>(V)) {
10579 V = propagateMetadata(I, E->Scalars);
10580 GatherShuffleExtractSeq.insert(I);
10581 CSEBlocks.insert(I->getParent());
10582 }
10583
10584 E->VectorizedValue = V;
10585 ++NumVectorInstructions;
10586
10587 return V;
10588 }
10589 default:
10590 llvm_unreachable("unknown inst")::llvm::llvm_unreachable_internal("unknown inst", "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 10590)
;
10591 }
10592 return nullptr;
10593}
10594
10595Value *BoUpSLP::vectorizeTree() {
10596 ExtraValueToDebugLocsMap ExternallyUsedValues;
10597 SmallVector<std::pair<Value *, Value *>> ReplacedExternals;
10598 return vectorizeTree(ExternallyUsedValues, ReplacedExternals);
10599}
10600
10601namespace {
10602/// Data type for handling buildvector sequences with the reused scalars from
10603/// other tree entries.
10604struct ShuffledInsertData {
10605 /// List of insertelements to be replaced by shuffles.
10606 SmallVector<InsertElementInst *> InsertElements;
10607 /// The parent vectors and shuffle mask for the given list of inserts.
10608 MapVector<Value *, SmallVector<int>> ValueMasks;
10609};
10610} // namespace
10611
10612Value *BoUpSLP::vectorizeTree(
10613 const ExtraValueToDebugLocsMap &ExternallyUsedValues,
10614 SmallVectorImpl<std::pair<Value *, Value *>> &ReplacedExternals,
10615 Instruction *ReductionRoot) {
10616 // All blocks must be scheduled before any instructions are inserted.
10617 for (auto &BSIter : BlocksSchedules) {
10618 scheduleBlock(BSIter.second.get());
10619 }
10620
10621 // Pre-gather last instructions.
10622 for (const std::unique_ptr<TreeEntry> &E : VectorizableTree) {
10623 if ((E->State == TreeEntry::NeedToGather &&
10624 (!E->getMainOp() || E->Idx > 0)) ||
10625 (E->State != TreeEntry::NeedToGather &&
10626 E->getOpcode() == Instruction::ExtractValue) ||
10627 E->getOpcode() == Instruction::InsertElement)
10628 continue;
10629 Instruction *LastInst = &getLastInstructionInBundle(E.get());
10630 EntryToLastInstruction.try_emplace(E.get(), LastInst);
10631 }
10632
10633 Builder.SetInsertPoint(ReductionRoot ? ReductionRoot
10634 : &F->getEntryBlock().front());
10635 auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
10636 // Run through the list of postponed gathers and emit them, replacing the temp
10637 // emitted allocas with actual vector instructions.
10638 ArrayRef<const TreeEntry *> PostponedNodes = PostponedGathers.getArrayRef();
10639 DenseMap<Value *, SmallVector<TreeEntry *>> PostponedValues;
10640 for (const TreeEntry *E : PostponedNodes) {
10641 auto *TE = const_cast<TreeEntry *>(E);
10642 if (auto *VecTE = getTreeEntry(TE->Scalars.front()))
10643 if (VecTE->isSame(TE->UserTreeIndices.front().UserTE->getOperand(
10644 TE->UserTreeIndices.front().EdgeIdx)))
10645 // Found gather node which is absolutely the same as one of the
10646 // vectorized nodes. It may happen after reordering.
10647 continue;
10648 auto *PrevVec = cast<Instruction>(TE->VectorizedValue);
10649 TE->VectorizedValue = nullptr;
10650 auto *UserI =
10651 cast<Instruction>(TE->UserTreeIndices.front().UserTE->VectorizedValue);
10652 Builder.SetInsertPoint(PrevVec);
10653 Builder.SetCurrentDebugLocation(UserI->getDebugLoc());
10654 Value *Vec = vectorizeTree(TE);
10655 PrevVec->replaceAllUsesWith(Vec);
10656 PostponedValues.try_emplace(Vec).first->second.push_back(TE);
10657 // Replace the stub vector node, if it was used before for one of the
10658 // buildvector nodes already.
10659 auto It = PostponedValues.find(PrevVec);
10660 if (It != PostponedValues.end()) {
10661 for (TreeEntry *VTE : It->getSecond())
10662 VTE->VectorizedValue = Vec;
10663 }
10664 eraseInstruction(PrevVec);
10665 }
10666
10667 // If the vectorized tree can be rewritten in a smaller type, we truncate the
10668 // vectorized root. InstCombine will then rewrite the entire expression. We
10669 // sign extend the extracted values below.
10670 auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
10671 if (MinBWs.count(ScalarRoot)) {
10672 if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
10673 // If current instr is a phi and not the last phi, insert it after the
10674 // last phi node.
10675 if (isa<PHINode>(I))
10676 Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
10677 else
10678 Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
10679 }
10680 auto BundleWidth = VectorizableTree[0]->Scalars.size();
10681 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
10682 auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
10683 auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
10684 VectorizableTree[0]->VectorizedValue = Trunc;
10685 }
10686
10687 LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Extracting " << ExternalUses
.size() << " values .\n"; } } while (false)
10688 << " values .\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Extracting " << ExternalUses
.size() << " values .\n"; } } while (false)
;
10689
10690 SmallVector<ShuffledInsertData> ShuffledInserts;
10691 // Maps vector instruction to original insertelement instruction
10692 DenseMap<Value *, InsertElementInst *> VectorToInsertElement;
10693 // Maps extract Scalar to the corresponding extractelement instruction in the
10694 // basic block. Only one extractelement per block should be emitted.
10695 DenseMap<Value *, DenseMap<BasicBlock *, Instruction *>> ScalarToEEs;
10696 // Extract all of the elements with the external uses.
10697 for (const auto &ExternalUse : ExternalUses) {
10698 Value *Scalar = ExternalUse.Scalar;
10699 llvm::User *User = ExternalUse.User;
10700
10701 // Skip users that we already RAUW. This happens when one instruction
10702 // has multiple uses of the same value.
10703 if (User && !is_contained(Scalar->users(), User))
10704 continue;
10705 TreeEntry *E = getTreeEntry(Scalar);
10706 assert(E && "Invalid scalar")(static_cast <bool> (E && "Invalid scalar") ? void
(0) : __assert_fail ("E && \"Invalid scalar\"", "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 10706, __extension__ __PRETTY_FUNCTION__))
;
10707 assert(E->State != TreeEntry::NeedToGather &&(static_cast <bool> (E->State != TreeEntry::NeedToGather
&& "Extracting from a gather list") ? void (0) : __assert_fail
("E->State != TreeEntry::NeedToGather && \"Extracting from a gather list\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10708, __extension__
__PRETTY_FUNCTION__))
10708 "Extracting from a gather list")(static_cast <bool> (E->State != TreeEntry::NeedToGather
&& "Extracting from a gather list") ? void (0) : __assert_fail
("E->State != TreeEntry::NeedToGather && \"Extracting from a gather list\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10708, __extension__
__PRETTY_FUNCTION__))
;
10709 // Non-instruction pointers are not deleted, just skip them.
10710 if (E->getOpcode() == Instruction::GetElementPtr &&
10711 !isa<GetElementPtrInst>(Scalar))
10712 continue;
10713
10714 Value *Vec = E->VectorizedValue;
10715 assert(Vec && "Can't find vectorizable value")(static_cast <bool> (Vec && "Can't find vectorizable value"
) ? void (0) : __assert_fail ("Vec && \"Can't find vectorizable value\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10715, __extension__
__PRETTY_FUNCTION__))
;
10716
10717 Value *Lane = Builder.getInt32(ExternalUse.Lane);
10718 auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
10719 if (Scalar->getType() != Vec->getType()) {
10720 Value *Ex = nullptr;
10721 auto It = ScalarToEEs.find(Scalar);
10722 if (It != ScalarToEEs.end()) {
10723 // No need to emit many extracts, just move the only one in the
10724 // current block.
10725 auto EEIt = It->second.find(Builder.GetInsertBlock());
10726 if (EEIt != It->second.end()) {
10727 Instruction *I = EEIt->second;
10728 if (Builder.GetInsertPoint() != Builder.GetInsertBlock()->end() &&
10729 Builder.GetInsertPoint()->comesBefore(I))
10730 I->moveBefore(&*Builder.GetInsertPoint());
10731 Ex = I;
10732 }
10733 }
10734 if (!Ex) {
10735 // "Reuse" the existing extract to improve final codegen.
10736 if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
10737 Ex = Builder.CreateExtractElement(ES->getOperand(0),
10738 ES->getOperand(1));
10739 } else {
10740 Ex = Builder.CreateExtractElement(Vec, Lane);
10741 }
10742 if (auto *I = dyn_cast<Instruction>(Ex))
10743 ScalarToEEs[Scalar].try_emplace(Builder.GetInsertBlock(), I);
10744 }
10745 // The then branch of the previous if may produce constants, since 0
10746 // operand might be a constant.
10747 if (auto *ExI = dyn_cast<Instruction>(Ex)) {
10748 GatherShuffleExtractSeq.insert(ExI);
10749 CSEBlocks.insert(ExI->getParent());
10750 }
10751 // If necessary, sign-extend or zero-extend ScalarRoot
10752 // to the larger type.
10753 if (!MinBWs.count(ScalarRoot))
10754 return Ex;
10755 if (MinBWs[ScalarRoot].second)
10756 return Builder.CreateSExt(Ex, Scalar->getType());
10757 return Builder.CreateZExt(Ex, Scalar->getType());
10758 }
10759 assert(isa<FixedVectorType>(Scalar->getType()) &&(static_cast <bool> (isa<FixedVectorType>(Scalar->
getType()) && isa<InsertElementInst>(Scalar) &&
"In-tree scalar of vector type is not insertelement?") ? void
(0) : __assert_fail ("isa<FixedVectorType>(Scalar->getType()) && isa<InsertElementInst>(Scalar) && \"In-tree scalar of vector type is not insertelement?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10761, __extension__
__PRETTY_FUNCTION__))
10760 isa<InsertElementInst>(Scalar) &&(static_cast <bool> (isa<FixedVectorType>(Scalar->
getType()) && isa<InsertElementInst>(Scalar) &&
"In-tree scalar of vector type is not insertelement?") ? void
(0) : __assert_fail ("isa<FixedVectorType>(Scalar->getType()) && isa<InsertElementInst>(Scalar) && \"In-tree scalar of vector type is not insertelement?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10761, __extension__
__PRETTY_FUNCTION__))
10761 "In-tree scalar of vector type is not insertelement?")(static_cast <bool> (isa<FixedVectorType>(Scalar->
getType()) && isa<InsertElementInst>(Scalar) &&
"In-tree scalar of vector type is not insertelement?") ? void
(0) : __assert_fail ("isa<FixedVectorType>(Scalar->getType()) && isa<InsertElementInst>(Scalar) && \"In-tree scalar of vector type is not insertelement?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10761, __extension__
__PRETTY_FUNCTION__))
;
10762 auto *IE = cast<InsertElementInst>(Scalar);
10763 VectorToInsertElement.try_emplace(Vec, IE);
10764 return Vec;
10765 };
10766 // If User == nullptr, the Scalar is used as extra arg. Generate
10767 // ExtractElement instruction and update the record for this scalar in
10768 // ExternallyUsedValues.
10769 if (!User) {
10770 assert(ExternallyUsedValues.count(Scalar) &&(static_cast <bool> (ExternallyUsedValues.count(Scalar)
&& "Scalar with nullptr as an external user must be registered in "
"ExternallyUsedValues map") ? void (0) : __assert_fail ("ExternallyUsedValues.count(Scalar) && \"Scalar with nullptr as an external user must be registered in \" \"ExternallyUsedValues map\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10772, __extension__
__PRETTY_FUNCTION__))
10771 "Scalar with nullptr as an external user must be registered in "(static_cast <bool> (ExternallyUsedValues.count(Scalar)
&& "Scalar with nullptr as an external user must be registered in "
"ExternallyUsedValues map") ? void (0) : __assert_fail ("ExternallyUsedValues.count(Scalar) && \"Scalar with nullptr as an external user must be registered in \" \"ExternallyUsedValues map\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10772, __extension__
__PRETTY_FUNCTION__))
10772 "ExternallyUsedValues map")(static_cast <bool> (ExternallyUsedValues.count(Scalar)
&& "Scalar with nullptr as an external user must be registered in "
"ExternallyUsedValues map") ? void (0) : __assert_fail ("ExternallyUsedValues.count(Scalar) && \"Scalar with nullptr as an external user must be registered in \" \"ExternallyUsedValues map\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10772, __extension__
__PRETTY_FUNCTION__))
;
10773 if (auto *VecI = dyn_cast<Instruction>(Vec)) {
10774 if (auto *PHI = dyn_cast<PHINode>(VecI))
10775 Builder.SetInsertPoint(PHI->getParent()->getFirstNonPHI());
10776 else
10777 Builder.SetInsertPoint(VecI->getParent(),
10778 std::next(VecI->getIterator()));
10779 } else {
10780 Builder.SetInsertPoint(&F->getEntryBlock().front());
10781 }
10782 Value *NewInst = ExtractAndExtendIfNeeded(Vec);
10783 // Required to update internally referenced instructions.
10784 Scalar->replaceAllUsesWith(NewInst);
10785 ReplacedExternals.emplace_back(Scalar, NewInst);
10786 continue;
10787 }
10788
10789 if (auto *VU = dyn_cast<InsertElementInst>(User)) {
10790 // Skip if the scalar is another vector op or Vec is not an instruction.
10791 if (!Scalar->getType()->isVectorTy() && isa<Instruction>(Vec)) {
10792 if (auto *FTy = dyn_cast<FixedVectorType>(User->getType())) {
10793 std::optional<unsigned> InsertIdx = getInsertIndex(VU);
10794 if (InsertIdx) {
10795 // Need to use original vector, if the root is truncated.
10796 if (MinBWs.count(Scalar) &&
10797 VectorizableTree[0]->VectorizedValue == Vec)
10798 Vec = VectorRoot;
10799 auto *It =
10800 find_if(ShuffledInserts, [VU](const ShuffledInsertData &Data) {
10801 // Checks if 2 insertelements are from the same buildvector.
10802 InsertElementInst *VecInsert = Data.InsertElements.front();
10803 return areTwoInsertFromSameBuildVector(
10804 VU, VecInsert,
10805 [](InsertElementInst *II) { return II->getOperand(0); });
10806 });
10807 unsigned Idx = *InsertIdx;
10808 if (It == ShuffledInserts.end()) {
10809 (void)ShuffledInserts.emplace_back();
10810 It = std::next(ShuffledInserts.begin(),
10811 ShuffledInserts.size() - 1);
10812 SmallVectorImpl<int> &Mask = It->ValueMasks[Vec];
10813 if (Mask.empty())
10814 Mask.assign(FTy->getNumElements(), PoisonMaskElem);
10815 // Find the insertvector, vectorized in tree, if any.
10816 Value *Base = VU;
10817 while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) {
10818 if (IEBase != User &&
10819 (!IEBase->hasOneUse() ||
10820 getInsertIndex(IEBase).value_or(Idx) == Idx))
10821 break;
10822 // Build the mask for the vectorized insertelement instructions.
10823 if (const TreeEntry *E = getTreeEntry(IEBase)) {
10824 do {
10825 IEBase = cast<InsertElementInst>(Base);
10826 int IEIdx = *getInsertIndex(IEBase);
10827 assert(Mask[Idx] == PoisonMaskElem &&(static_cast <bool> (Mask[Idx] == PoisonMaskElem &&
"InsertElementInstruction used already.") ? void (0) : __assert_fail
("Mask[Idx] == PoisonMaskElem && \"InsertElementInstruction used already.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10828, __extension__
__PRETTY_FUNCTION__))
10828 "InsertElementInstruction used already.")(static_cast <bool> (Mask[Idx] == PoisonMaskElem &&
"InsertElementInstruction used already.") ? void (0) : __assert_fail
("Mask[Idx] == PoisonMaskElem && \"InsertElementInstruction used already.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10828, __extension__
__PRETTY_FUNCTION__))
;
10829 Mask[IEIdx] = IEIdx;
10830 Base = IEBase->getOperand(0);
10831 } while (E == getTreeEntry(Base));
10832 break;
10833 }
10834 Base = cast<InsertElementInst>(Base)->getOperand(0);
10835 // After the vectorization the def-use chain has changed, need
10836 // to look through original insertelement instructions, if they
10837 // get replaced by vector instructions.
10838 auto It = VectorToInsertElement.find(Base);
10839 if (It != VectorToInsertElement.end())
10840 Base = It->second;
10841 }
10842 }
10843 SmallVectorImpl<int> &Mask = It->ValueMasks[Vec];
10844 if (Mask.empty())
10845 Mask.assign(FTy->getNumElements(), PoisonMaskElem);
10846 Mask[Idx] = ExternalUse.Lane;
10847 It->InsertElements.push_back(cast<InsertElementInst>(User));
10848 continue;
10849 }
10850 }
10851 }
10852 }
10853
10854 // Generate extracts for out-of-tree users.
10855 // Find the insertion point for the extractelement lane.
10856 if (auto *VecI = dyn_cast<Instruction>(Vec)) {
10857 if (PHINode *PH = dyn_cast<PHINode>(User)) {
10858 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
10859 if (PH->getIncomingValue(i) == Scalar) {
10860 Instruction *IncomingTerminator =
10861 PH->getIncomingBlock(i)->getTerminator();
10862 if (isa<CatchSwitchInst>(IncomingTerminator)) {
10863 Builder.SetInsertPoint(VecI->getParent(),
10864 std::next(VecI->getIterator()));
10865 } else {
10866 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
10867 }
10868 Value *NewInst = ExtractAndExtendIfNeeded(Vec);
10869 PH->setOperand(i, NewInst);
10870 }
10871 }
10872 } else {
10873 Builder.SetInsertPoint(cast<Instruction>(User));
10874 Value *NewInst = ExtractAndExtendIfNeeded(Vec);
10875 User->replaceUsesOfWith(Scalar, NewInst);
10876 }
10877 } else {
10878 Builder.SetInsertPoint(&F->getEntryBlock().front());
10879 Value *NewInst = ExtractAndExtendIfNeeded(Vec);
10880 User->replaceUsesOfWith(Scalar, NewInst);
10881 }
10882
10883 LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Replaced:" << *User <<
".\n"; } } while (false)
;
10884 }
10885
10886 auto CreateShuffle = [&](Value *V1, Value *V2, ArrayRef<int> Mask) {
10887 SmallVector<int> CombinedMask1(Mask.size(), PoisonMaskElem);
10888 SmallVector<int> CombinedMask2(Mask.size(), PoisonMaskElem);
10889 int VF = cast<FixedVectorType>(V1->getType())->getNumElements();
10890 for (int I = 0, E = Mask.size(); I < E; ++I) {
10891 if (Mask[I] < VF)
10892 CombinedMask1[I] = Mask[I];
10893 else
10894 CombinedMask2[I] = Mask[I] - VF;
10895 }
10896 ShuffleInstructionBuilder ShuffleBuilder(Builder, *this);
10897 ShuffleBuilder.add(V1, CombinedMask1);
10898 if (V2)
10899 ShuffleBuilder.add(V2, CombinedMask2);
10900 return ShuffleBuilder.finalize(std::nullopt);
10901 };
10902
10903 auto &&ResizeToVF = [&CreateShuffle](Value *Vec, ArrayRef<int> Mask,
10904 bool ForSingleMask) {
10905 unsigned VF = Mask.size();
10906 unsigned VecVF = cast<FixedVectorType>(Vec->getType())->getNumElements();
10907 if (VF != VecVF) {
10908 if (any_of(Mask, [VF](int Idx) { return Idx >= static_cast<int>(VF); })) {
10909 Vec = CreateShuffle(Vec, nullptr, Mask);
10910 return std::make_pair(Vec, true);
10911 }
10912 if (!ForSingleMask) {
10913 SmallVector<int> ResizeMask(VF, PoisonMaskElem);
10914 for (unsigned I = 0; I < VF; ++I) {
10915 if (Mask[I] != PoisonMaskElem)
10916 ResizeMask[Mask[I]] = Mask[I];
10917 }
10918 Vec = CreateShuffle(Vec, nullptr, ResizeMask);
10919 }
10920 }
10921
10922 return std::make_pair(Vec, false);
10923 };
10924 // Perform shuffling of the vectorize tree entries for better handling of
10925 // external extracts.
10926 for (int I = 0, E = ShuffledInserts.size(); I < E; ++I) {
10927 // Find the first and the last instruction in the list of insertelements.
10928 sort(ShuffledInserts[I].InsertElements, isFirstInsertElement);
10929 InsertElementInst *FirstInsert = ShuffledInserts[I].InsertElements.front();
10930 InsertElementInst *LastInsert = ShuffledInserts[I].InsertElements.back();
10931 Builder.SetInsertPoint(LastInsert);
10932 auto Vector = ShuffledInserts[I].ValueMasks.takeVector();
10933 Value *NewInst = performExtractsShuffleAction<Value>(
10934 MutableArrayRef(Vector.data(), Vector.size()),
10935 FirstInsert->getOperand(0),
10936 [](Value *Vec) {
10937 return cast<VectorType>(Vec->getType())
10938 ->getElementCount()
10939 .getKnownMinValue();
10940 },
10941 ResizeToVF,
10942 [FirstInsert, &CreateShuffle](ArrayRef<int> Mask,
10943 ArrayRef<Value *> Vals) {
10944 assert((Vals.size() == 1 || Vals.size() == 2) &&(static_cast <bool> ((Vals.size() == 1 || Vals.size() ==
2) && "Expected exactly 1 or 2 input values.") ? void
(0) : __assert_fail ("(Vals.size() == 1 || Vals.size() == 2) && \"Expected exactly 1 or 2 input values.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10945, __extension__
__PRETTY_FUNCTION__))
10945 "Expected exactly 1 or 2 input values.")(static_cast <bool> ((Vals.size() == 1 || Vals.size() ==
2) && "Expected exactly 1 or 2 input values.") ? void
(0) : __assert_fail ("(Vals.size() == 1 || Vals.size() == 2) && \"Expected exactly 1 or 2 input values.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10945, __extension__
__PRETTY_FUNCTION__))
;
10946 if (Vals.size() == 1) {
10947 // Do not create shuffle if the mask is a simple identity
10948 // non-resizing mask.
10949 if (Mask.size() != cast<FixedVectorType>(Vals.front()->getType())
10950 ->getNumElements() ||
10951 !ShuffleVectorInst::isIdentityMask(Mask))
10952 return CreateShuffle(Vals.front(), nullptr, Mask);
10953 return Vals.front();
10954 }
10955 return CreateShuffle(Vals.front() ? Vals.front()
10956 : FirstInsert->getOperand(0),
10957 Vals.back(), Mask);
10958 });
10959 auto It = ShuffledInserts[I].InsertElements.rbegin();
10960 // Rebuild buildvector chain.
10961 InsertElementInst *II = nullptr;
10962 if (It != ShuffledInserts[I].InsertElements.rend())
10963 II = *It;
10964 SmallVector<Instruction *> Inserts;
10965 while (It != ShuffledInserts[I].InsertElements.rend()) {
10966 assert(II && "Must be an insertelement instruction.")(static_cast <bool> (II && "Must be an insertelement instruction."
) ? void (0) : __assert_fail ("II && \"Must be an insertelement instruction.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10966, __extension__
__PRETTY_FUNCTION__))
;
10967 if (*It == II)
10968 ++It;
10969 else
10970 Inserts.push_back(cast<Instruction>(II));
10971 II = dyn_cast<InsertElementInst>(II->getOperand(0));
10972 }
10973 for (Instruction *II : reverse(Inserts)) {
10974 II->replaceUsesOfWith(II->getOperand(0), NewInst);
10975 if (auto *NewI = dyn_cast<Instruction>(NewInst))
10976 if (II->getParent() == NewI->getParent() && II->comesBefore(NewI))
10977 II->moveAfter(NewI);
10978 NewInst = II;
10979 }
10980 LastInsert->replaceAllUsesWith(NewInst);
10981 for (InsertElementInst *IE : reverse(ShuffledInserts[I].InsertElements)) {
10982 IE->replaceUsesOfWith(IE->getOperand(0),
10983 PoisonValue::get(IE->getOperand(0)->getType()));
10984 IE->replaceUsesOfWith(IE->getOperand(1),
10985 PoisonValue::get(IE->getOperand(1)->getType()));
10986 eraseInstruction(IE);
10987 }
10988 CSEBlocks.insert(LastInsert->getParent());
10989 }
10990
10991 SmallVector<Instruction *> RemovedInsts;
10992 // For each vectorized value:
10993 for (auto &TEPtr : VectorizableTree) {
10994 TreeEntry *Entry = TEPtr.get();
10995
10996 // No need to handle users of gathered values.
10997 if (Entry->State == TreeEntry::NeedToGather)
10998 continue;
10999
11000 assert(Entry->VectorizedValue && "Can't find vectorizable value")(static_cast <bool> (Entry->VectorizedValue &&
"Can't find vectorizable value") ? void (0) : __assert_fail (
"Entry->VectorizedValue && \"Can't find vectorizable value\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11000, __extension__
__PRETTY_FUNCTION__))
;
11001
11002 // For each lane:
11003 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
11004 Value *Scalar = Entry->Scalars[Lane];
11005
11006 if (Entry->getOpcode() == Instruction::GetElementPtr &&
11007 !isa<GetElementPtrInst>(Scalar))
11008 continue;
11009#ifndef NDEBUG
11010 Type *Ty = Scalar->getType();
11011 if (!Ty->isVoidTy()) {
11012 for (User *U : Scalar->users()) {
11013 LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: \tvalidating user:" <<
*U << ".\n"; } } while (false)
;
11014
11015 // It is legal to delete users in the ignorelist.
11016 assert((getTreeEntry(U) ||(static_cast <bool> ((getTreeEntry(U) || (UserIgnoreList
&& UserIgnoreList->contains(U)) || (isa_and_nonnull
<Instruction>(U) && isDeleted(cast<Instruction
>(U)))) && "Deleting out-of-tree value") ? void (0
) : __assert_fail ("(getTreeEntry(U) || (UserIgnoreList && UserIgnoreList->contains(U)) || (isa_and_nonnull<Instruction>(U) && isDeleted(cast<Instruction>(U)))) && \"Deleting out-of-tree value\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11020, __extension__
__PRETTY_FUNCTION__))
11017 (UserIgnoreList && UserIgnoreList->contains(U)) ||(static_cast <bool> ((getTreeEntry(U) || (UserIgnoreList
&& UserIgnoreList->contains(U)) || (isa_and_nonnull
<Instruction>(U) && isDeleted(cast<Instruction
>(U)))) && "Deleting out-of-tree value") ? void (0
) : __assert_fail ("(getTreeEntry(U) || (UserIgnoreList && UserIgnoreList->contains(U)) || (isa_and_nonnull<Instruction>(U) && isDeleted(cast<Instruction>(U)))) && \"Deleting out-of-tree value\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11020, __extension__
__PRETTY_FUNCTION__))
11018 (isa_and_nonnull<Instruction>(U) &&(static_cast <bool> ((getTreeEntry(U) || (UserIgnoreList
&& UserIgnoreList->contains(U)) || (isa_and_nonnull
<Instruction>(U) && isDeleted(cast<Instruction
>(U)))) && "Deleting out-of-tree value") ? void (0
) : __assert_fail ("(getTreeEntry(U) || (UserIgnoreList && UserIgnoreList->contains(U)) || (isa_and_nonnull<Instruction>(U) && isDeleted(cast<Instruction>(U)))) && \"Deleting out-of-tree value\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11020, __extension__
__PRETTY_FUNCTION__))
11019 isDeleted(cast<Instruction>(U)))) &&(static_cast <bool> ((getTreeEntry(U) || (UserIgnoreList
&& UserIgnoreList->contains(U)) || (isa_and_nonnull
<Instruction>(U) && isDeleted(cast<Instruction
>(U)))) && "Deleting out-of-tree value") ? void (0
) : __assert_fail ("(getTreeEntry(U) || (UserIgnoreList && UserIgnoreList->contains(U)) || (isa_and_nonnull<Instruction>(U) && isDeleted(cast<Instruction>(U)))) && \"Deleting out-of-tree value\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11020, __extension__
__PRETTY_FUNCTION__))
11020 "Deleting out-of-tree value")(static_cast <bool> ((getTreeEntry(U) || (UserIgnoreList
&& UserIgnoreList->contains(U)) || (isa_and_nonnull
<Instruction>(U) && isDeleted(cast<Instruction
>(U)))) && "Deleting out-of-tree value") ? void (0
) : __assert_fail ("(getTreeEntry(U) || (UserIgnoreList && UserIgnoreList->contains(U)) || (isa_and_nonnull<Instruction>(U) && isDeleted(cast<Instruction>(U)))) && \"Deleting out-of-tree value\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11020, __extension__
__PRETTY_FUNCTION__))
;
11021 }
11022 }
11023#endif
11024 LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: \tErasing scalar:" << *
Scalar << ".\n"; } } while (false)
;
11025 eraseInstruction(cast<Instruction>(Scalar));
11026 // Retain to-be-deleted instructions for some debug-info
11027 // bookkeeping. NOTE: eraseInstruction only marks the instruction for
11028 // deletion - instructions are not deleted until later.
11029 RemovedInsts.push_back(cast<Instruction>(Scalar));
11030 }
11031 }
11032
11033 // Merge the DIAssignIDs from the about-to-be-deleted instructions into the
11034 // new vector instruction.
11035 if (auto *V = dyn_cast<Instruction>(VectorizableTree[0]->VectorizedValue))
11036 V->mergeDIAssignID(RemovedInsts);
11037
11038 Builder.ClearInsertionPoint();
11039 InstrElementSize.clear();
11040
11041 return VectorizableTree[0]->VectorizedValue;
11042}
11043
11044void BoUpSLP::optimizeGatherSequence() {
11045 LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleExtractSeq.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Optimizing " << GatherShuffleExtractSeq
.size() << " gather sequences instructions.\n"; } } while
(false)
11046 << " gather sequences instructions.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Optimizing " << GatherShuffleExtractSeq
.size() << " gather sequences instructions.\n"; } } while
(false)
;
11047 // LICM InsertElementInst sequences.
11048 for (Instruction *I : GatherShuffleExtractSeq) {
11049 if (isDeleted(I))
11050 continue;
11051
11052 // Check if this block is inside a loop.
11053 Loop *L = LI->getLoopFor(I->getParent());
11054 if (!L)
11055 continue;
11056
11057 // Check if it has a preheader.
11058 BasicBlock *PreHeader = L->getLoopPreheader();
11059 if (!PreHeader)
11060 continue;
11061
11062 // If the vector or the element that we insert into it are
11063 // instructions that are defined in this basic block then we can't
11064 // hoist this instruction.
11065 if (any_of(I->operands(), [L](Value *V) {
11066 auto *OpI = dyn_cast<Instruction>(V);
11067 return OpI && L->contains(OpI);
11068 }))
11069 continue;
11070
11071 // We can hoist this instruction. Move it to the pre-header.
11072 I->moveBefore(PreHeader->getTerminator());
11073 CSEBlocks.insert(PreHeader);
11074 }
11075
11076 // Make a list of all reachable blocks in our CSE queue.
11077 SmallVector<const DomTreeNode *, 8> CSEWorkList;
11078 CSEWorkList.reserve(CSEBlocks.size());
11079 for (BasicBlock *BB : CSEBlocks)
11080 if (DomTreeNode *N = DT->getNode(BB)) {
11081 assert(DT->isReachableFromEntry(N))(static_cast <bool> (DT->isReachableFromEntry(N)) ? void
(0) : __assert_fail ("DT->isReachableFromEntry(N)", "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 11081, __extension__ __PRETTY_FUNCTION__))
;
11082 CSEWorkList.push_back(N);
11083 }
11084
11085 // Sort blocks by domination. This ensures we visit a block after all blocks
11086 // dominating it are visited.
11087 llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
11088 assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&(static_cast <bool> ((A == B) == (A->getDFSNumIn() ==
B->getDFSNumIn()) && "Different nodes should have different DFS numbers"
) ? void (0) : __assert_fail ("(A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) && \"Different nodes should have different DFS numbers\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11089, __extension__
__PRETTY_FUNCTION__))
11089 "Different nodes should have different DFS numbers")(static_cast <bool> ((A == B) == (A->getDFSNumIn() ==
B->getDFSNumIn()) && "Different nodes should have different DFS numbers"
) ? void (0) : __assert_fail ("(A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) && \"Different nodes should have different DFS numbers\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11089, __extension__
__PRETTY_FUNCTION__))
;
11090 return A->getDFSNumIn() < B->getDFSNumIn();
11091 });
11092
11093 // Less defined shuffles can be replaced by the more defined copies.
11094 // Between two shuffles one is less defined if it has the same vector operands
11095 // and its mask indeces are the same as in the first one or undefs. E.g.
11096 // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
11097 // poison, <0, 0, 0, 0>.
11098 auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
11099 SmallVectorImpl<int> &NewMask) {
11100 if (I1->getType() != I2->getType())
11101 return false;
11102 auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
11103 auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
11104 if (!SI1 || !SI2)
11105 return I1->isIdenticalTo(I2);
11106 if (SI1->isIdenticalTo(SI2))
11107 return true;
11108 for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
11109 if (SI1->getOperand(I) != SI2->getOperand(I))
11110 return false;
11111 // Check if the second instruction is more defined than the first one.
11112 NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
11113 ArrayRef<int> SM1 = SI1->getShuffleMask();
11114 // Count trailing undefs in the mask to check the final number of used
11115 // registers.
11116 unsigned LastUndefsCnt = 0;
11117 for (int I = 0, E = NewMask.size(); I < E; ++I) {
11118 if (SM1[I] == PoisonMaskElem)
11119 ++LastUndefsCnt;
11120 else
11121 LastUndefsCnt = 0;
11122 if (NewMask[I] != PoisonMaskElem && SM1[I] != PoisonMaskElem &&
11123 NewMask[I] != SM1[I])
11124 return false;
11125 if (NewMask[I] == PoisonMaskElem)
11126 NewMask[I] = SM1[I];
11127 }
11128 // Check if the last undefs actually change the final number of used vector
11129 // registers.
11130 return SM1.size() - LastUndefsCnt > 1 &&
11131 TTI->getNumberOfParts(SI1->getType()) ==
11132 TTI->getNumberOfParts(
11133 FixedVectorType::get(SI1->getType()->getElementType(),
11134 SM1.size() - LastUndefsCnt));
11135 };
11136 // Perform O(N^2) search over the gather/shuffle sequences and merge identical
11137 // instructions. TODO: We can further optimize this scan if we split the
11138 // instructions into different buckets based on the insert lane.
11139 SmallVector<Instruction *, 16> Visited;
11140 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
11141 assert(*I &&(static_cast <bool> (*I && (I == CSEWorkList.begin
() || !DT->dominates(*I, *std::prev(I))) && "Worklist not sorted properly!"
) ? void (0) : __assert_fail ("*I && (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) && \"Worklist not sorted properly!\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11143, __extension__
__PRETTY_FUNCTION__))
11142 (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&(static_cast <bool> (*I && (I == CSEWorkList.begin
() || !DT->dominates(*I, *std::prev(I))) && "Worklist not sorted properly!"
) ? void (0) : __assert_fail ("*I && (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) && \"Worklist not sorted properly!\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11143, __extension__
__PRETTY_FUNCTION__))
11143 "Worklist not sorted properly!")(static_cast <bool> (*I && (I == CSEWorkList.begin
() || !DT->dominates(*I, *std::prev(I))) && "Worklist not sorted properly!"
) ? void (0) : __assert_fail ("*I && (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) && \"Worklist not sorted properly!\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11143, __extension__
__PRETTY_FUNCTION__))
;
11144 BasicBlock *BB = (*I)->getBlock();
11145 // For all instructions in blocks containing gather sequences:
11146 for (Instruction &In : llvm::make_early_inc_range(*BB)) {
11147 if (isDeleted(&In))
11148 continue;
11149 if (!isa<InsertElementInst, ExtractElementInst, ShuffleVectorInst>(&In) &&
11150 !GatherShuffleExtractSeq.contains(&In))
11151 continue;
11152
11153 // Check if we can replace this instruction with any of the
11154 // visited instructions.
11155 bool Replaced = false;
11156 for (Instruction *&V : Visited) {
11157 SmallVector<int> NewMask;
11158 if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
11159 DT->dominates(V->getParent(), In.getParent())) {
11160 In.replaceAllUsesWith(V);
11161 eraseInstruction(&In);
11162 if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
11163 if (!NewMask.empty())
11164 SI->setShuffleMask(NewMask);
11165 Replaced = true;
11166 break;
11167 }
11168 if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
11169 GatherShuffleExtractSeq.contains(V) &&
11170 IsIdenticalOrLessDefined(V, &In, NewMask) &&
11171 DT->dominates(In.getParent(), V->getParent())) {
11172 In.moveAfter(V);
11173 V->replaceAllUsesWith(&In);
11174 eraseInstruction(V);
11175 if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
11176 if (!NewMask.empty())
11177 SI->setShuffleMask(NewMask);
11178 V = &In;
11179 Replaced = true;
11180 break;
11181 }
11182 }
11183 if (!Replaced) {
11184 assert(!is_contained(Visited, &In))(static_cast <bool> (!is_contained(Visited, &In)) ?
void (0) : __assert_fail ("!is_contained(Visited, &In)",
"llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11184, __extension__
__PRETTY_FUNCTION__))
;
11185 Visited.push_back(&In);
11186 }
11187 }
11188 }
11189 CSEBlocks.clear();
11190 GatherShuffleExtractSeq.clear();
11191}
11192
11193BoUpSLP::ScheduleData *
11194BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
11195 ScheduleData *Bundle = nullptr;
11196 ScheduleData *PrevInBundle = nullptr;
11197 for (Value *V : VL) {
11198 if (doesNotNeedToBeScheduled(V))
11199 continue;
11200 ScheduleData *BundleMember = getScheduleData(V);
11201 assert(BundleMember &&(static_cast <bool> (BundleMember && "no ScheduleData for bundle member "
"(maybe not in same basic block)") ? void (0) : __assert_fail
("BundleMember && \"no ScheduleData for bundle member \" \"(maybe not in same basic block)\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11203, __extension__
__PRETTY_FUNCTION__))
11202 "no ScheduleData for bundle member "(static_cast <bool> (BundleMember && "no ScheduleData for bundle member "
"(maybe not in same basic block)") ? void (0) : __assert_fail
("BundleMember && \"no ScheduleData for bundle member \" \"(maybe not in same basic block)\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11203, __extension__
__PRETTY_FUNCTION__))
11203 "(maybe not in same basic block)")(static_cast <bool> (BundleMember && "no ScheduleData for bundle member "
"(maybe not in same basic block)") ? void (0) : __assert_fail
("BundleMember && \"no ScheduleData for bundle member \" \"(maybe not in same basic block)\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11203, __extension__
__PRETTY_FUNCTION__))
;
11204 assert(BundleMember->isSchedulingEntity() &&(static_cast <bool> (BundleMember->isSchedulingEntity
() && "bundle member already part of other bundle") ?
void (0) : __assert_fail ("BundleMember->isSchedulingEntity() && \"bundle member already part of other bundle\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11205, __extension__
__PRETTY_FUNCTION__))
11205 "bundle member already part of other bundle")(static_cast <bool> (BundleMember->isSchedulingEntity
() && "bundle member already part of other bundle") ?
void (0) : __assert_fail ("BundleMember->isSchedulingEntity() && \"bundle member already part of other bundle\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11205, __extension__
__PRETTY_FUNCTION__))
;
11206 if (PrevInBundle) {
11207 PrevInBundle->NextInBundle = BundleMember;
11208 } else {
11209 Bundle = BundleMember;
11210 }
11211
11212 // Group the instructions to a bundle.
11213 BundleMember->FirstInBundle = Bundle;
11214 PrevInBundle = BundleMember;
11215 }
11216 assert(Bundle && "Failed to find schedule bundle")(static_cast <bool> (Bundle && "Failed to find schedule bundle"
) ? void (0) : __assert_fail ("Bundle && \"Failed to find schedule bundle\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11216, __extension__
__PRETTY_FUNCTION__))
;
11217 return Bundle;
11218}
11219
11220// Groups the instructions to a bundle (which is then a single scheduling entity)
11221// and schedules instructions until the bundle gets ready.
11222std::optional<BoUpSLP::ScheduleData *>
11223BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
11224 const InstructionsState &S) {
11225 // No need to schedule PHIs, insertelement, extractelement and extractvalue
11226 // instructions.
11227 if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
11228 doesNotNeedToSchedule(VL))
11229 return nullptr;
11230
11231 // Initialize the instruction bundle.
11232 Instruction *OldScheduleEnd = ScheduleEnd;
11233 LLVM_DEBUG(dbgs() << "SLP: bundle: " << *S.OpValue << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: bundle: " << *S.OpValue
<< "\n"; } } while (false)
;
11234
11235 auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
11236 ScheduleData *Bundle) {
11237 // The scheduling region got new instructions at the lower end (or it is a
11238 // new region for the first bundle). This makes it necessary to
11239 // recalculate all dependencies.
11240 // It is seldom that this needs to be done a second time after adding the
11241 // initial bundle to the region.
11242 if (ScheduleEnd != OldScheduleEnd) {
11243 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
11244 doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
11245 ReSchedule = true;
11246 }
11247 if (Bundle) {
11248 LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundledo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: try schedule bundle " <<
*Bundle << " in block " << BB->getName() <<
"\n"; } } while (false)
11249 << " in block " << BB->getName() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: try schedule bundle " <<
*Bundle << " in block " << BB->getName() <<
"\n"; } } while (false)
;
11250 calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
11251 }
11252
11253 if (ReSchedule) {
11254 resetSchedule();
11255 initialFillReadyList(ReadyInsts);
11256 }
11257
11258 // Now try to schedule the new bundle or (if no bundle) just calculate
11259 // dependencies. As soon as the bundle is "ready" it means that there are no
11260 // cyclic dependencies and we can schedule it. Note that's important that we
11261 // don't "schedule" the bundle yet (see cancelScheduling).
11262 while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
11263 !ReadyInsts.empty()) {
11264 ScheduleData *Picked = ReadyInsts.pop_back_val();
11265 assert(Picked->isSchedulingEntity() && Picked->isReady() &&(static_cast <bool> (Picked->isSchedulingEntity() &&
Picked->isReady() && "must be ready to schedule")
? void (0) : __assert_fail ("Picked->isSchedulingEntity() && Picked->isReady() && \"must be ready to schedule\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11266, __extension__
__PRETTY_FUNCTION__))
11266 "must be ready to schedule")(static_cast <bool> (Picked->isSchedulingEntity() &&
Picked->isReady() && "must be ready to schedule")
? void (0) : __assert_fail ("Picked->isSchedulingEntity() && Picked->isReady() && \"must be ready to schedule\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11266, __extension__
__PRETTY_FUNCTION__))
;
11267 schedule(Picked, ReadyInsts);
11268 }
11269 };
11270
11271 // Make sure that the scheduling region contains all
11272 // instructions of the bundle.
11273 for (Value *V : VL) {
11274 if (doesNotNeedToBeScheduled(V))
11275 continue;
11276 if (!extendSchedulingRegion(V, S)) {
11277 // If the scheduling region got new instructions at the lower end (or it
11278 // is a new region for the first bundle). This makes it necessary to
11279 // recalculate all dependencies.
11280 // Otherwise the compiler may crash trying to incorrectly calculate
11281 // dependencies and emit instruction in the wrong order at the actual
11282 // scheduling.
11283 TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
11284 return std::nullopt;
11285 }
11286 }
11287
11288 bool ReSchedule = false;
11289 for (Value *V : VL) {
11290 if (doesNotNeedToBeScheduled(V))
11291 continue;
11292 ScheduleData *BundleMember = getScheduleData(V);
11293 assert(BundleMember &&(static_cast <bool> (BundleMember && "no ScheduleData for bundle member (maybe not in same basic block)"
) ? void (0) : __assert_fail ("BundleMember && \"no ScheduleData for bundle member (maybe not in same basic block)\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11294, __extension__
__PRETTY_FUNCTION__))
11294 "no ScheduleData for bundle member (maybe not in same basic block)")(static_cast <bool> (BundleMember && "no ScheduleData for bundle member (maybe not in same basic block)"
) ? void (0) : __assert_fail ("BundleMember && \"no ScheduleData for bundle member (maybe not in same basic block)\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11294, __extension__
__PRETTY_FUNCTION__))
;
11295
11296 // Make sure we don't leave the pieces of the bundle in the ready list when
11297 // whole bundle might not be ready.
11298 ReadyInsts.remove(BundleMember);
11299
11300 if (!BundleMember->IsScheduled)
11301 continue;
11302 // A bundle member was scheduled as single instruction before and now
11303 // needs to be scheduled as part of the bundle. We just get rid of the
11304 // existing schedule.
11305 LLVM_DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMemberdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: reset schedule because " <<
*BundleMember << " was already scheduled\n"; } } while
(false)
11306 << " was already scheduled\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: reset schedule because " <<
*BundleMember << " was already scheduled\n"; } } while
(false)
;
11307 ReSchedule = true;
11308 }
11309
11310 auto *Bundle = buildBundle(VL);
11311 TryScheduleBundleImpl(ReSchedule, Bundle);
11312 if (!Bundle->isReady()) {
11313 cancelScheduling(VL, S.OpValue);
11314 return std::nullopt;
11315 }
11316 return Bundle;
11317}
11318
11319void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
11320 Value *OpValue) {
11321 if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
11322 doesNotNeedToSchedule(VL))
11323 return;
11324
11325 if (doesNotNeedToBeScheduled(OpValue))
11326 OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
11327 ScheduleData *Bundle = getScheduleData(OpValue);
11328 LLVM_DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: cancel scheduling of " <<
*Bundle << "\n"; } } while (false)
;
11329 assert(!Bundle->IsScheduled &&(static_cast <bool> (!Bundle->IsScheduled &&
"Can't cancel bundle which is already scheduled") ? void (0)
: __assert_fail ("!Bundle->IsScheduled && \"Can't cancel bundle which is already scheduled\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11330, __extension__
__PRETTY_FUNCTION__))
11330 "Can't cancel bundle which is already scheduled")(static_cast <bool> (!Bundle->IsScheduled &&
"Can't cancel bundle which is already scheduled") ? void (0)
: __assert_fail ("!Bundle->IsScheduled && \"Can't cancel bundle which is already scheduled\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11330, __extension__
__PRETTY_FUNCTION__))
;
11331 assert(Bundle->isSchedulingEntity() &&(static_cast <bool> (Bundle->isSchedulingEntity() &&
(Bundle->isPartOfBundle() || needToScheduleSingleInstruction
(VL)) && "tried to unbundle something which is not a bundle"
) ? void (0) : __assert_fail ("Bundle->isSchedulingEntity() && (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) && \"tried to unbundle something which is not a bundle\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11333, __extension__
__PRETTY_FUNCTION__))
11332 (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&(static_cast <bool> (Bundle->isSchedulingEntity() &&
(Bundle->isPartOfBundle() || needToScheduleSingleInstruction
(VL)) && "tried to unbundle something which is not a bundle"
) ? void (0) : __assert_fail ("Bundle->isSchedulingEntity() && (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) && \"tried to unbundle something which is not a bundle\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11333, __extension__
__PRETTY_FUNCTION__))
11333 "tried to unbundle something which is not a bundle")(static_cast <bool> (Bundle->isSchedulingEntity() &&
(Bundle->isPartOfBundle() || needToScheduleSingleInstruction
(VL)) && "tried to unbundle something which is not a bundle"
) ? void (0) : __assert_fail ("Bundle->isSchedulingEntity() && (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) && \"tried to unbundle something which is not a bundle\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11333, __extension__
__PRETTY_FUNCTION__))
;
11334
11335 // Remove the bundle from the ready list.
11336 if (Bundle->isReady())
11337 ReadyInsts.remove(Bundle);
11338
11339 // Un-bundle: make single instructions out of the bundle.
11340 ScheduleData *BundleMember = Bundle;
11341 while (BundleMember) {
11342 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links")(static_cast <bool> (BundleMember->FirstInBundle == Bundle
&& "corrupt bundle links") ? void (0) : __assert_fail
("BundleMember->FirstInBundle == Bundle && \"corrupt bundle links\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11342, __extension__
__PRETTY_FUNCTION__))
;
11343 BundleMember->FirstInBundle = BundleMember;
11344 ScheduleData *Next = BundleMember->NextInBundle;
11345 BundleMember->NextInBundle = nullptr;
11346 BundleMember->TE = nullptr;
11347 if (BundleMember->unscheduledDepsInBundle() == 0) {
11348 ReadyInsts.insert(BundleMember);
11349 }
11350 BundleMember = Next;
11351 }
11352}
11353
11354BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
11355 // Allocate a new ScheduleData for the instruction.
11356 if (ChunkPos >= ChunkSize) {
11357 ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
11358 ChunkPos = 0;
11359 }
11360 return &(ScheduleDataChunks.back()[ChunkPos++]);
11361}
11362
11363bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
11364 const InstructionsState &S) {
11365 if (getScheduleData(V, isOneOf(S, V)))
11366 return true;
11367 Instruction *I = dyn_cast<Instruction>(V);
11368 assert(I && "bundle member must be an instruction")(static_cast <bool> (I && "bundle member must be an instruction"
) ? void (0) : __assert_fail ("I && \"bundle member must be an instruction\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11368, __extension__
__PRETTY_FUNCTION__))
;
11369 assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&(static_cast <bool> (!isa<PHINode>(I) && !
isVectorLikeInstWithConstOps(I) && !doesNotNeedToBeScheduled
(I) && "phi nodes/insertelements/extractelements/extractvalues don't need to "
"be scheduled") ? void (0) : __assert_fail ("!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) && !doesNotNeedToBeScheduled(I) && \"phi nodes/insertelements/extractelements/extractvalues don't need to \" \"be scheduled\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11372, __extension__
__PRETTY_FUNCTION__))
11370 !doesNotNeedToBeScheduled(I) &&(static_cast <bool> (!isa<PHINode>(I) && !
isVectorLikeInstWithConstOps(I) && !doesNotNeedToBeScheduled
(I) && "phi nodes/insertelements/extractelements/extractvalues don't need to "
"be scheduled") ? void (0) : __assert_fail ("!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) && !doesNotNeedToBeScheduled(I) && \"phi nodes/insertelements/extractelements/extractvalues don't need to \" \"be scheduled\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11372, __extension__
__PRETTY_FUNCTION__))
11371 "phi nodes/insertelements/extractelements/extractvalues don't need to "(static_cast <bool> (!isa<PHINode>(I) && !
isVectorLikeInstWithConstOps(I) && !doesNotNeedToBeScheduled
(I) && "phi nodes/insertelements/extractelements/extractvalues don't need to "
"be scheduled") ? void (0) : __assert_fail ("!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) && !doesNotNeedToBeScheduled(I) && \"phi nodes/insertelements/extractelements/extractvalues don't need to \" \"be scheduled\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11372, __extension__
__PRETTY_FUNCTION__))
11372 "be scheduled")(static_cast <bool> (!isa<PHINode>(I) && !
isVectorLikeInstWithConstOps(I) && !doesNotNeedToBeScheduled
(I) && "phi nodes/insertelements/extractelements/extractvalues don't need to "
"be scheduled") ? void (0) : __assert_fail ("!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) && !doesNotNeedToBeScheduled(I) && \"phi nodes/insertelements/extractelements/extractvalues don't need to \" \"be scheduled\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11372, __extension__
__PRETTY_FUNCTION__))
;
11373 auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
11374 ScheduleData *ISD = getScheduleData(I);
11375 if (!ISD)
11376 return false;
11377 assert(isInSchedulingRegion(ISD) &&(static_cast <bool> (isInSchedulingRegion(ISD) &&
"ScheduleData not in scheduling region") ? void (0) : __assert_fail
("isInSchedulingRegion(ISD) && \"ScheduleData not in scheduling region\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11378, __extension__
__PRETTY_FUNCTION__))
11378 "ScheduleData not in scheduling region")(static_cast <bool> (isInSchedulingRegion(ISD) &&
"ScheduleData not in scheduling region") ? void (0) : __assert_fail
("isInSchedulingRegion(ISD) && \"ScheduleData not in scheduling region\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11378, __extension__
__PRETTY_FUNCTION__))
;
11379 ScheduleData *SD = allocateScheduleDataChunks();
11380 SD->Inst = I;
11381 SD->init(SchedulingRegionID, S.OpValue);
11382 ExtraScheduleDataMap[I][S.OpValue] = SD;
11383 return true;
11384 };
11385 if (CheckScheduleForI(I))
11386 return true;
11387 if (!ScheduleStart) {
11388 // It's the first instruction in the new region.
11389 initScheduleData(I, I->getNextNode(), nullptr, nullptr);
11390 ScheduleStart = I;
11391 ScheduleEnd = I->getNextNode();
11392 if (isOneOf(S, I) != I)
11393 CheckScheduleForI(I);
11394 assert(ScheduleEnd && "tried to vectorize a terminator?")(static_cast <bool> (ScheduleEnd && "tried to vectorize a terminator?"
) ? void (0) : __assert_fail ("ScheduleEnd && \"tried to vectorize a terminator?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11394, __extension__
__PRETTY_FUNCTION__))
;
11395 LLVM_DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: initialize schedule region to "
<< *I << "\n"; } } while (false)
;
11396 return true;
11397 }
11398 // Search up and down at the same time, because we don't know if the new
11399 // instruction is above or below the existing scheduling region.
11400 BasicBlock::reverse_iterator UpIter =
11401 ++ScheduleStart->getIterator().getReverse();
11402 BasicBlock::reverse_iterator UpperEnd = BB->rend();
11403 BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
11404 BasicBlock::iterator LowerEnd = BB->end();
11405 while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
11406 &*DownIter != I) {
11407 if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
11408 LLVM_DEBUG(dbgs() << "SLP: exceeded schedule region size limit\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: exceeded schedule region size limit\n"
; } } while (false)
;
11409 return false;
11410 }
11411
11412 ++UpIter;
11413 ++DownIter;
11414 }
11415 if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
11416 assert(I->getParent() == ScheduleStart->getParent() &&(static_cast <bool> (I->getParent() == ScheduleStart
->getParent() && "Instruction is in wrong basic block."
) ? void (0) : __assert_fail ("I->getParent() == ScheduleStart->getParent() && \"Instruction is in wrong basic block.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11417, __extension__
__PRETTY_FUNCTION__))
11417 "Instruction is in wrong basic block.")(static_cast <bool> (I->getParent() == ScheduleStart
->getParent() && "Instruction is in wrong basic block."
) ? void (0) : __assert_fail ("I->getParent() == ScheduleStart->getParent() && \"Instruction is in wrong basic block.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11417, __extension__
__PRETTY_FUNCTION__))
;
11418 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
11419 ScheduleStart = I;
11420 if (isOneOf(S, I) != I)
11421 CheckScheduleForI(I);
11422 LLVM_DEBUG(dbgs() << "SLP: extend schedule region start to " << *Ido { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: extend schedule region start to "
<< *I << "\n"; } } while (false)
11423 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: extend schedule region start to "
<< *I << "\n"; } } while (false)
;
11424 return true;
11425 }
11426 assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&(static_cast <bool> ((UpIter == UpperEnd || (DownIter !=
LowerEnd && &*DownIter == I)) && "Expected to reach top of the basic block or instruction down the "
"lower end.") ? void (0) : __assert_fail ("(UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) && \"Expected to reach top of the basic block or instruction down the \" \"lower end.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11428, __extension__
__PRETTY_FUNCTION__))
11427 "Expected to reach top of the basic block or instruction down the "(static_cast <bool> ((UpIter == UpperEnd || (DownIter !=
LowerEnd && &*DownIter == I)) && "Expected to reach top of the basic block or instruction down the "
"lower end.") ? void (0) : __assert_fail ("(UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) && \"Expected to reach top of the basic block or instruction down the \" \"lower end.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11428, __extension__
__PRETTY_FUNCTION__))
11428 "lower end.")(static_cast <bool> ((UpIter == UpperEnd || (DownIter !=
LowerEnd && &*DownIter == I)) && "Expected to reach top of the basic block or instruction down the "
"lower end.") ? void (0) : __assert_fail ("(UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) && \"Expected to reach top of the basic block or instruction down the \" \"lower end.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11428, __extension__
__PRETTY_FUNCTION__))
;
11429 assert(I->getParent() == ScheduleEnd->getParent() &&(static_cast <bool> (I->getParent() == ScheduleEnd->
getParent() && "Instruction is in wrong basic block."
) ? void (0) : __assert_fail ("I->getParent() == ScheduleEnd->getParent() && \"Instruction is in wrong basic block.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11430, __extension__
__PRETTY_FUNCTION__))
11430 "Instruction is in wrong basic block.")(static_cast <bool> (I->getParent() == ScheduleEnd->
getParent() && "Instruction is in wrong basic block."
) ? void (0) : __assert_fail ("I->getParent() == ScheduleEnd->getParent() && \"Instruction is in wrong basic block.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11430, __extension__
__PRETTY_FUNCTION__))
;
11431 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
11432 nullptr);
11433 ScheduleEnd = I->getNextNode();
11434 if (isOneOf(S, I) != I)
11435 CheckScheduleForI(I);
11436 assert(ScheduleEnd && "tried to vectorize a terminator?")(static_cast <bool> (ScheduleEnd && "tried to vectorize a terminator?"
) ? void (0) : __assert_fail ("ScheduleEnd && \"tried to vectorize a terminator?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11436, __extension__
__PRETTY_FUNCTION__))
;
11437 LLVM_DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: extend schedule region end to "
<< *I << "\n"; } } while (false)
;
11438 return true;
11439}
11440
11441void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
11442 Instruction *ToI,
11443 ScheduleData *PrevLoadStore,
11444 ScheduleData *NextLoadStore) {
11445 ScheduleData *CurrentLoadStore = PrevLoadStore;
11446 for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
11447 // No need to allocate data for non-schedulable instructions.
11448 if (doesNotNeedToBeScheduled(I))
11449 continue;
11450 ScheduleData *SD = ScheduleDataMap.lookup(I);
11451 if (!SD) {
11452 SD = allocateScheduleDataChunks();
11453 ScheduleDataMap[I] = SD;
11454 SD->Inst = I;
11455 }
11456 assert(!isInSchedulingRegion(SD) &&(static_cast <bool> (!isInSchedulingRegion(SD) &&
"new ScheduleData already in scheduling region") ? void (0) :
__assert_fail ("!isInSchedulingRegion(SD) && \"new ScheduleData already in scheduling region\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11457, __extension__
__PRETTY_FUNCTION__))
11457 "new ScheduleData already in scheduling region")(static_cast <bool> (!isInSchedulingRegion(SD) &&
"new ScheduleData already in scheduling region") ? void (0) :
__assert_fail ("!isInSchedulingRegion(SD) && \"new ScheduleData already in scheduling region\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11457, __extension__
__PRETTY_FUNCTION__))
;
11458 SD->init(SchedulingRegionID, I);
11459
11460 if (I->mayReadOrWriteMemory() &&
11461 (!isa<IntrinsicInst>(I) ||
11462 (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
11463 cast<IntrinsicInst>(I)->getIntrinsicID() !=
11464 Intrinsic::pseudoprobe))) {
11465 // Update the linked list of memory accessing instructions.
11466 if (CurrentLoadStore) {
11467 CurrentLoadStore->NextLoadStore = SD;
11468 } else {
11469 FirstLoadStoreInRegion = SD;
11470 }
11471 CurrentLoadStore = SD;
11472 }
11473
11474 if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
11475 match(I, m_Intrinsic<Intrinsic::stackrestore>()))
11476 RegionHasStackSave = true;
11477 }
11478 if (NextLoadStore) {
11479 if (CurrentLoadStore)
11480 CurrentLoadStore->NextLoadStore = NextLoadStore;
11481 } else {
11482 LastLoadStoreInRegion = CurrentLoadStore;
11483 }
11484}
11485
11486void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
11487 bool InsertInReadyList,
11488 BoUpSLP *SLP) {
11489 assert(SD->isSchedulingEntity())(static_cast <bool> (SD->isSchedulingEntity()) ? void
(0) : __assert_fail ("SD->isSchedulingEntity()", "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 11489, __extension__ __PRETTY_FUNCTION__))
;
1
'?' condition is true
11490
11491 SmallVector<ScheduleData *, 10> WorkList;
11492 WorkList.push_back(SD);
11493
11494 while (!WorkList.empty()) {
2
Loop condition is true. Entering loop body
11495 ScheduleData *SD = WorkList.pop_back_val();
3
'SD' initialized here
11496 for (ScheduleData *BundleMember = SD; BundleMember;
4
Assuming pointer value is null
11497 BundleMember = BundleMember->NextInBundle) {
11498 assert(isInSchedulingRegion(BundleMember))(static_cast <bool> (isInSchedulingRegion(BundleMember)
) ? void (0) : __assert_fail ("isInSchedulingRegion(BundleMember)"
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11498, __extension__
__PRETTY_FUNCTION__))
;
11499 if (BundleMember->hasValidDependencies())
11500 continue;
11501
11502 LLVM_DEBUG(dbgs() << "SLP: update deps of " << *BundleMemberdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: update deps of " <<
*BundleMember << "\n"; } } while (false)
11503 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: update deps of " <<
*BundleMember << "\n"; } } while (false)
;
11504 BundleMember->Dependencies = 0;
11505 BundleMember->resetUnscheduledDeps();
11506
11507 // Handle def-use chain dependencies.
11508 if (BundleMember->OpValue != BundleMember->Inst) {
11509 if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
11510 BundleMember->Dependencies++;
11511 ScheduleData *DestBundle = UseSD->FirstInBundle;
11512 if (!DestBundle->IsScheduled)
11513 BundleMember->incrementUnscheduledDeps(1);
11514 if (!DestBundle->hasValidDependencies())
11515 WorkList.push_back(DestBundle);
11516 }
11517 } else {
11518 for (User *U : BundleMember->Inst->users()) {
11519 if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
11520 BundleMember->Dependencies++;
11521 ScheduleData *DestBundle = UseSD->FirstInBundle;
11522 if (!DestBundle->IsScheduled)
11523 BundleMember->incrementUnscheduledDeps(1);
11524 if (!DestBundle->hasValidDependencies())
11525 WorkList.push_back(DestBundle);
11526 }
11527 }
11528 }
11529
11530 auto makeControlDependent = [&](Instruction *I) {
11531 auto *DepDest = getScheduleData(I);
11532 assert(DepDest && "must be in schedule window")(static_cast <bool> (DepDest && "must be in schedule window"
) ? void (0) : __assert_fail ("DepDest && \"must be in schedule window\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11532, __extension__
__PRETTY_FUNCTION__))
;
11533 DepDest->ControlDependencies.push_back(BundleMember);
11534 BundleMember->Dependencies++;
11535 ScheduleData *DestBundle = DepDest->FirstInBundle;
11536 if (!DestBundle->IsScheduled)
11537 BundleMember->incrementUnscheduledDeps(1);
11538 if (!DestBundle->hasValidDependencies())
11539 WorkList.push_back(DestBundle);
11540 };
11541
11542 // Any instruction which isn't safe to speculate at the beginning of the
11543 // block is control dependend on any early exit or non-willreturn call
11544 // which proceeds it.
11545 if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
11546 for (Instruction *I = BundleMember->Inst->getNextNode();
11547 I != ScheduleEnd; I = I->getNextNode()) {
11548 if (isSafeToSpeculativelyExecute(I, &*BB->begin(), SLP->AC))
11549 continue;
11550
11551 // Add the dependency
11552 makeControlDependent(I);
11553
11554 if (!isGuaranteedToTransferExecutionToSuccessor(I))
11555 // Everything past here must be control dependent on I.
11556 break;
11557 }
11558 }
11559
11560 if (RegionHasStackSave) {
11561 // If we have an inalloc alloca instruction, it needs to be scheduled
11562 // after any preceeding stacksave. We also need to prevent any alloca
11563 // from reordering above a preceeding stackrestore.
11564 if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) ||
11565 match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) {
11566 for (Instruction *I = BundleMember->Inst->getNextNode();
11567 I != ScheduleEnd; I = I->getNextNode()) {
11568 if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
11569 match(I, m_Intrinsic<Intrinsic::stackrestore>()))
11570 // Any allocas past here must be control dependent on I, and I
11571 // must be memory dependend on BundleMember->Inst.
11572 break;
11573
11574 if (!isa<AllocaInst>(I))
11575 continue;
11576
11577 // Add the dependency
11578 makeControlDependent(I);
11579 }
11580 }
11581
11582 // In addition to the cases handle just above, we need to prevent
11583 // allocas and loads/stores from moving below a stacksave or a
11584 // stackrestore. Avoiding moving allocas below stackrestore is currently
11585 // thought to be conservatism. Moving loads/stores below a stackrestore
11586 // can lead to incorrect code.
11587 if (isa<AllocaInst>(BundleMember->Inst) ||
11588 BundleMember->Inst->mayReadOrWriteMemory()) {
11589 for (Instruction *I = BundleMember->Inst->getNextNode();
11590 I != ScheduleEnd; I = I->getNextNode()) {
11591 if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) &&
11592 !match(I, m_Intrinsic<Intrinsic::stackrestore>()))
11593 continue;
11594
11595 // Add the dependency
11596 makeControlDependent(I);
11597 break;
11598 }
11599 }
11600 }
11601
11602 // Handle the memory dependencies (if any).
11603 ScheduleData *DepDest = BundleMember->NextLoadStore;
11604 if (!DepDest)
11605 continue;
11606 Instruction *SrcInst = BundleMember->Inst;
11607 assert(SrcInst->mayReadOrWriteMemory() &&(static_cast <bool> (SrcInst->mayReadOrWriteMemory()
&& "NextLoadStore list for non memory effecting bundle?"
) ? void (0) : __assert_fail ("SrcInst->mayReadOrWriteMemory() && \"NextLoadStore list for non memory effecting bundle?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11608, __extension__
__PRETTY_FUNCTION__))
11608 "NextLoadStore list for non memory effecting bundle?")(static_cast <bool> (SrcInst->mayReadOrWriteMemory()
&& "NextLoadStore list for non memory effecting bundle?"
) ? void (0) : __assert_fail ("SrcInst->mayReadOrWriteMemory() && \"NextLoadStore list for non memory effecting bundle?\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11608, __extension__
__PRETTY_FUNCTION__))
;
11609 MemoryLocation SrcLoc = getLocation(SrcInst);
11610 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
11611 unsigned numAliased = 0;
11612 unsigned DistToSrc = 1;
11613
11614 for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
11615 assert(isInSchedulingRegion(DepDest))(static_cast <bool> (isInSchedulingRegion(DepDest)) ? void
(0) : __assert_fail ("isInSchedulingRegion(DepDest)", "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp"
, 11615, __extension__ __PRETTY_FUNCTION__))
;
11616
11617 // We have two limits to reduce the complexity:
11618 // 1) AliasedCheckLimit: It's a small limit to reduce calls to
11619 // SLP->isAliased (which is the expensive part in this loop).
11620 // 2) MaxMemDepDistance: It's for very large blocks and it aborts
11621 // the whole loop (even if the loop is fast, it's quadratic).
11622 // It's important for the loop break condition (see below) to
11623 // check this limit even between two read-only instructions.
11624 if (DistToSrc >= MaxMemDepDistance ||
11625 ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
11626 (numAliased >= AliasedCheckLimit ||
11627 SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
11628
11629 // We increment the counter only if the locations are aliased
11630 // (instead of counting all alias checks). This gives a better
11631 // balance between reduced runtime and accurate dependencies.
11632 numAliased++;
11633
11634 DepDest->MemoryDependencies.push_back(BundleMember);
11635 BundleMember->Dependencies++;
11636 ScheduleData *DestBundle = DepDest->FirstInBundle;
11637 if (!DestBundle->IsScheduled) {
11638 BundleMember->incrementUnscheduledDeps(1);
11639 }
11640 if (!DestBundle->hasValidDependencies()) {
11641 WorkList.push_back(DestBundle);
11642 }
11643 }
11644
11645 // Example, explaining the loop break condition: Let's assume our
11646 // starting instruction is i0 and MaxMemDepDistance = 3.
11647 //
11648 // +--------v--v--v
11649 // i0,i1,i2,i3,i4,i5,i6,i7,i8
11650 // +--------^--^--^
11651 //
11652 // MaxMemDepDistance let us stop alias-checking at i3 and we add
11653 // dependencies from i0 to i3,i4,.. (even if they are not aliased).
11654 // Previously we already added dependencies from i3 to i6,i7,i8
11655 // (because of MaxMemDepDistance). As we added a dependency from
11656 // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
11657 // and we can abort this loop at i6.
11658 if (DistToSrc >= 2 * MaxMemDepDistance)
11659 break;
11660 DistToSrc++;
11661 }
11662 }
11663 if (InsertInReadyList && SD->isReady()) {
5
Assuming 'InsertInReadyList' is true
6
Called C++ object pointer is null
11664 ReadyInsts.insert(SD);
11665 LLVM_DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Instdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: gets ready on update: " <<
*SD->Inst << "\n"; } } while (false)
11666 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: gets ready on update: " <<
*SD->Inst << "\n"; } } while (false)
;
11667 }
11668 }
11669}
11670
11671void BoUpSLP::BlockScheduling::resetSchedule() {
11672 assert(ScheduleStart &&(static_cast <bool> (ScheduleStart && "tried to reset schedule on block which has not been scheduled"
) ? void (0) : __assert_fail ("ScheduleStart && \"tried to reset schedule on block which has not been scheduled\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11673, __extension__
__PRETTY_FUNCTION__))
11673 "tried to reset schedule on block which has not been scheduled")(static_cast <bool> (ScheduleStart && "tried to reset schedule on block which has not been scheduled"
) ? void (0) : __assert_fail ("ScheduleStart && \"tried to reset schedule on block which has not been scheduled\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11673, __extension__
__PRETTY_FUNCTION__))
;
11674 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
11675 doForAllOpcodes(I, [&](ScheduleData *SD) {
11676 assert(isInSchedulingRegion(SD) &&(static_cast <bool> (isInSchedulingRegion(SD) &&
"ScheduleData not in scheduling region") ? void (0) : __assert_fail
("isInSchedulingRegion(SD) && \"ScheduleData not in scheduling region\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11677, __extension__
__PRETTY_FUNCTION__))
11677 "ScheduleData not in scheduling region")(static_cast <bool> (isInSchedulingRegion(SD) &&
"ScheduleData not in scheduling region") ? void (0) : __assert_fail
("isInSchedulingRegion(SD) && \"ScheduleData not in scheduling region\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11677, __extension__
__PRETTY_FUNCTION__))
;
11678 SD->IsScheduled = false;
11679 SD->resetUnscheduledDeps();
11680 });
11681 }
11682 ReadyInsts.clear();
11683}
11684
11685void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
11686 if (!BS->ScheduleStart)
11687 return;
11688
11689 LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: schedule block " << BS
->BB->getName() << "\n"; } } while (false)
;
11690
11691 // A key point - if we got here, pre-scheduling was able to find a valid
11692 // scheduling of the sub-graph of the scheduling window which consists
11693 // of all vector bundles and their transitive users. As such, we do not
11694 // need to reschedule anything *outside of* that subgraph.
11695
11696 BS->resetSchedule();
11697
11698 // For the real scheduling we use a more sophisticated ready-list: it is
11699 // sorted by the original instruction location. This lets the final schedule
11700 // be as close as possible to the original instruction order.
11701 // WARNING: If changing this order causes a correctness issue, that means
11702 // there is some missing dependence edge in the schedule data graph.
11703 struct ScheduleDataCompare {
11704 bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
11705 return SD2->SchedulingPriority < SD1->SchedulingPriority;
11706 }
11707 };
11708 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
11709
11710 // Ensure that all dependency data is updated (for nodes in the sub-graph)
11711 // and fill the ready-list with initial instructions.
11712 int Idx = 0;
11713 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
11714 I = I->getNextNode()) {
11715 BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) {
11716 TreeEntry *SDTE = getTreeEntry(SD->Inst);
11717 (void)SDTE;
11718 assert((isVectorLikeInstWithConstOps(SD->Inst) ||(static_cast <bool> ((isVectorLikeInstWithConstOps(SD->
Inst) || SD->isPartOfBundle() == (SDTE && !doesNotNeedToSchedule
(SDTE->Scalars))) && "scheduler and vectorizer bundle mismatch"
) ? void (0) : __assert_fail ("(isVectorLikeInstWithConstOps(SD->Inst) || SD->isPartOfBundle() == (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) && \"scheduler and vectorizer bundle mismatch\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11721, __extension__
__PRETTY_FUNCTION__))
11719 SD->isPartOfBundle() ==(static_cast <bool> ((isVectorLikeInstWithConstOps(SD->
Inst) || SD->isPartOfBundle() == (SDTE && !doesNotNeedToSchedule
(SDTE->Scalars))) && "scheduler and vectorizer bundle mismatch"
) ? void (0) : __assert_fail ("(isVectorLikeInstWithConstOps(SD->Inst) || SD->isPartOfBundle() == (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) && \"scheduler and vectorizer bundle mismatch\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11721, __extension__
__PRETTY_FUNCTION__))
11720 (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&(static_cast <bool> ((isVectorLikeInstWithConstOps(SD->
Inst) || SD->isPartOfBundle() == (SDTE && !doesNotNeedToSchedule
(SDTE->Scalars))) && "scheduler and vectorizer bundle mismatch"
) ? void (0) : __assert_fail ("(isVectorLikeInstWithConstOps(SD->Inst) || SD->isPartOfBundle() == (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) && \"scheduler and vectorizer bundle mismatch\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11721, __extension__
__PRETTY_FUNCTION__))
11721 "scheduler and vectorizer bundle mismatch")(static_cast <bool> ((isVectorLikeInstWithConstOps(SD->
Inst) || SD->isPartOfBundle() == (SDTE && !doesNotNeedToSchedule
(SDTE->Scalars))) && "scheduler and vectorizer bundle mismatch"
) ? void (0) : __assert_fail ("(isVectorLikeInstWithConstOps(SD->Inst) || SD->isPartOfBundle() == (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) && \"scheduler and vectorizer bundle mismatch\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11721, __extension__
__PRETTY_FUNCTION__))
;
11722 SD->FirstInBundle->SchedulingPriority = Idx++;
11723
11724 if (SD->isSchedulingEntity() && SD->isPartOfBundle())
11725 BS->calculateDependencies(SD, false, this);
11726 });
11727 }
11728 BS->initialFillReadyList(ReadyInsts);
11729
11730 Instruction *LastScheduledInst = BS->ScheduleEnd;
11731
11732 // Do the "real" scheduling.
11733 while (!ReadyInsts.empty()) {
11734 ScheduleData *picked = *ReadyInsts.begin();
11735 ReadyInsts.erase(ReadyInsts.begin());
11736
11737 // Move the scheduled instruction(s) to their dedicated places, if not
11738 // there yet.
11739 for (ScheduleData *BundleMember = picked; BundleMember;
11740 BundleMember = BundleMember->NextInBundle) {
11741 Instruction *pickedInst = BundleMember->Inst;
11742 if (pickedInst->getNextNode() != LastScheduledInst)
11743 pickedInst->moveBefore(LastScheduledInst);
11744 LastScheduledInst = pickedInst;
11745 }
11746
11747 BS->schedule(picked, ReadyInsts);
11748 }
11749
11750 // Check that we didn't break any of our invariants.
11751#ifdef EXPENSIVE_CHECKS
11752 BS->verify();
11753#endif
11754
11755#if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
11756 // Check that all schedulable entities got scheduled
11757 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
11758 BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
11759 if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
11760 assert(SD->IsScheduled && "must be scheduled at this point")(static_cast <bool> (SD->IsScheduled && "must be scheduled at this point"
) ? void (0) : __assert_fail ("SD->IsScheduled && \"must be scheduled at this point\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11760, __extension__
__PRETTY_FUNCTION__))
;
11761 }
11762 });
11763 }
11764#endif
11765
11766 // Avoid duplicate scheduling of the block.
11767 BS->ScheduleStart = nullptr;
11768}
11769
11770unsigned BoUpSLP::getVectorElementSize(Value *V) {
11771 // If V is a store, just return the width of the stored value (or value
11772 // truncated just before storing) without traversing the expression tree.
11773 // This is the common case.
11774 if (auto *Store = dyn_cast<StoreInst>(V))
11775 return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
11776
11777 if (auto *IEI = dyn_cast<InsertElementInst>(V))
11778 return getVectorElementSize(IEI->getOperand(1));
11779
11780 auto E = InstrElementSize.find(V);
11781 if (E != InstrElementSize.end())
11782 return E->second;
11783
11784 // If V is not a store, we can traverse the expression tree to find loads
11785 // that feed it. The type of the loaded value may indicate a more suitable
11786 // width than V's type. We want to base the vector element size on the width
11787 // of memory operations where possible.
11788 SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
11789 SmallPtrSet<Instruction *, 16> Visited;
11790 if (auto *I = dyn_cast<Instruction>(V)) {
11791 Worklist.emplace_back(I, I->getParent());
11792 Visited.insert(I);
11793 }
11794
11795 // Traverse the expression tree in bottom-up order looking for loads. If we
11796 // encounter an instruction we don't yet handle, we give up.
11797 auto Width = 0u;
11798 while (!Worklist.empty()) {
11799 Instruction *I;
11800 BasicBlock *Parent;
11801 std::tie(I, Parent) = Worklist.pop_back_val();
11802
11803 // We should only be looking at scalar instructions here. If the current
11804 // instruction has a vector type, skip.
11805 auto *Ty = I->getType();
11806 if (isa<VectorType>(Ty))
11807 continue;
11808
11809 // If the current instruction is a load, update MaxWidth to reflect the
11810 // width of the loaded value.
11811 if (isa<LoadInst, ExtractElementInst, ExtractValueInst>(I))
11812 Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
11813
11814 // Otherwise, we need to visit the operands of the instruction. We only
11815 // handle the interesting cases from buildTree here. If an operand is an
11816 // instruction we haven't yet visited and from the same basic block as the
11817 // user or the use is a PHI node, we add it to the worklist.
11818 else if (isa<PHINode, CastInst, GetElementPtrInst, CmpInst, SelectInst,
11819 BinaryOperator, UnaryOperator>(I)) {
11820 for (Use &U : I->operands())
11821 if (auto *J = dyn_cast<Instruction>(U.get()))
11822 if (Visited.insert(J).second &&
11823 (isa<PHINode>(I) || J->getParent() == Parent))
11824 Worklist.emplace_back(J, J->getParent());
11825 } else {
11826 break;
11827 }
11828 }
11829
11830 // If we didn't encounter a memory access in the expression tree, or if we
11831 // gave up for some reason, just return the width of V. Otherwise, return the
11832 // maximum width we found.
11833 if (!Width) {
11834 if (auto *CI = dyn_cast<CmpInst>(V))
11835 V = CI->getOperand(0);
11836 Width = DL->getTypeSizeInBits(V->getType());
11837 }
11838
11839 for (Instruction *I : Visited)
11840 InstrElementSize[I] = Width;
11841
11842 return Width;
11843}
11844
11845// Determine if a value V in a vectorizable expression Expr can be demoted to a
11846// smaller type with a truncation. We collect the values that will be demoted
11847// in ToDemote and additional roots that require investigating in Roots.
11848static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
11849 SmallVectorImpl<Value *> &ToDemote,
11850 SmallVectorImpl<Value *> &Roots) {
11851 // We can always demote constants.
11852 if (isa<Constant>(V)) {
11853 ToDemote.push_back(V);
11854 return true;
11855 }
11856
11857 // If the value is not an instruction in the expression with only one use, it
11858 // cannot be demoted.
11859 auto *I = dyn_cast<Instruction>(V);
11860 if (!I || !I->hasOneUse() || !Expr.count(I))
11861 return false;
11862
11863 switch (I->getOpcode()) {
11864
11865 // We can always demote truncations and extensions. Since truncations can
11866 // seed additional demotion, we save the truncated value.
11867 case Instruction::Trunc:
11868 Roots.push_back(I->getOperand(0));
11869 break;
11870 case Instruction::ZExt:
11871 case Instruction::SExt:
11872 if (isa<ExtractElementInst, InsertElementInst>(I->getOperand(0)))
11873 return false;
11874 break;
11875
11876 // We can demote certain binary operations if we can demote both of their
11877 // operands.
11878 case Instruction::Add:
11879 case Instruction::Sub:
11880 case Instruction::Mul:
11881 case Instruction::And:
11882 case Instruction::Or:
11883 case Instruction::Xor:
11884 if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
11885 !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
11886 return false;
11887 break;
11888
11889 // We can demote selects if we can demote their true and false values.
11890 case Instruction::Select: {
11891 SelectInst *SI = cast<SelectInst>(I);
11892 if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
11893 !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
11894 return false;
11895 break;
11896 }
11897
11898 // We can demote phis if we can demote all their incoming operands. Note that
11899 // we don't need to worry about cycles since we ensure single use above.
11900 case Instruction::PHI: {
11901 PHINode *PN = cast<PHINode>(I);
11902 for (Value *IncValue : PN->incoming_values())
11903 if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
11904 return false;
11905 break;
11906 }
11907
11908 // Otherwise, conservatively give up.
11909 default:
11910 return false;
11911 }
11912
11913 // Record the value that we can demote.
11914 ToDemote.push_back(V);
11915 return true;
11916}
11917
11918void BoUpSLP::computeMinimumValueSizes() {
11919 // If there are no external uses, the expression tree must be rooted by a
11920 // store. We can't demote in-memory values, so there is nothing to do here.
11921 if (ExternalUses.empty())
11922 return;
11923
11924 // We only attempt to truncate integer expressions.
11925 auto &TreeRoot = VectorizableTree[0]->Scalars;
11926 auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
11927 if (!TreeRootIT)
11928 return;
11929
11930 // If the expression is not rooted by a store, these roots should have
11931 // external uses. We will rely on InstCombine to rewrite the expression in
11932 // the narrower type. However, InstCombine only rewrites single-use values.
11933 // This means that if a tree entry other than a root is used externally, it
11934 // must have multiple uses and InstCombine will not rewrite it. The code
11935 // below ensures that only the roots are used externally.
11936 SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
11937 for (auto &EU : ExternalUses)
11938 if (!Expr.erase(EU.Scalar))
11939 return;
11940 if (!Expr.empty())
11941 return;
11942
11943 // Collect the scalar values of the vectorizable expression. We will use this
11944 // context to determine which values can be demoted. If we see a truncation,
11945 // we mark it as seeding another demotion.
11946 for (auto &EntryPtr : VectorizableTree)
11947 Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
11948
11949 // Ensure the roots of the vectorizable tree don't form a cycle. They must
11950 // have a single external user that is not in the vectorizable tree.
11951 for (auto *Root : TreeRoot)
11952 if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
11953 return;
11954
11955 // Conservatively determine if we can actually truncate the roots of the
11956 // expression. Collect the values that can be demoted in ToDemote and
11957 // additional roots that require investigating in Roots.
11958 SmallVector<Value *, 32> ToDemote;
11959 SmallVector<Value *, 4> Roots;
11960 for (auto *Root : TreeRoot)
11961 if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
11962 return;
11963
11964 // The maximum bit width required to represent all the values that can be
11965 // demoted without loss of precision. It would be safe to truncate the roots
11966 // of the expression to this width.
11967 auto MaxBitWidth = 8u;
11968
11969 // We first check if all the bits of the roots are demanded. If they're not,
11970 // we can truncate the roots to this narrower type.
11971 for (auto *Root : TreeRoot) {
11972 auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
11973 MaxBitWidth = std::max<unsigned>(Mask.getBitWidth() - Mask.countl_zero(),
11974 MaxBitWidth);
11975 }
11976
11977 // True if the roots can be zero-extended back to their original type, rather
11978 // than sign-extended. We know that if the leading bits are not demanded, we
11979 // can safely zero-extend. So we initialize IsKnownPositive to True.
11980 bool IsKnownPositive = true;
11981
11982 // If all the bits of the roots are demanded, we can try a little harder to
11983 // compute a narrower type. This can happen, for example, if the roots are
11984 // getelementptr indices. InstCombine promotes these indices to the pointer
11985 // width. Thus, all their bits are technically demanded even though the
11986 // address computation might be vectorized in a smaller type.
11987 //
11988 // We start by looking at each entry that can be demoted. We compute the
11989 // maximum bit width required to store the scalar by using ValueTracking to
11990 // compute the number of high-order bits we can truncate.
11991 if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
11992 llvm::all_of(TreeRoot, [](Value *R) {
11993 assert(R->hasOneUse() && "Root should have only one use!")(static_cast <bool> (R->hasOneUse() && "Root should have only one use!"
) ? void (0) : __assert_fail ("R->hasOneUse() && \"Root should have only one use!\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11993, __extension__
__PRETTY_FUNCTION__))
;
11994 return isa<GetElementPtrInst>(R->user_back());
11995 })) {
11996 MaxBitWidth = 8u;
11997
11998 // Determine if the sign bit of all the roots is known to be zero. If not,
11999 // IsKnownPositive is set to False.
12000 IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
12001 KnownBits Known = computeKnownBits(R, *DL);
12002 return Known.isNonNegative();
12003 });
12004
12005 // Determine the maximum number of bits required to store the scalar
12006 // values.
12007 for (auto *Scalar : ToDemote) {
12008 auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
12009 auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
12010 MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
12011 }
12012
12013 // If we can't prove that the sign bit is zero, we must add one to the
12014 // maximum bit width to account for the unknown sign bit. This preserves
12015 // the existing sign bit so we can safely sign-extend the root back to the
12016 // original type. Otherwise, if we know the sign bit is zero, we will
12017 // zero-extend the root instead.
12018 //
12019 // FIXME: This is somewhat suboptimal, as there will be cases where adding
12020 // one to the maximum bit width will yield a larger-than-necessary
12021 // type. In general, we need to add an extra bit only if we can't
12022 // prove that the upper bit of the original type is equal to the
12023 // upper bit of the proposed smaller type. If these two bits are the
12024 // same (either zero or one) we know that sign-extending from the
12025 // smaller type will result in the same value. Here, since we can't
12026 // yet prove this, we are just making the proposed smaller type
12027 // larger to ensure correctness.
12028 if (!IsKnownPositive)
12029 ++MaxBitWidth;
12030 }
12031
12032 // Round MaxBitWidth up to the next power-of-two.
12033 MaxBitWidth = llvm::bit_ceil(MaxBitWidth);
12034
12035 // If the maximum bit width we compute is less than the with of the roots'
12036 // type, we can proceed with the narrowing. Otherwise, do nothing.
12037 if (MaxBitWidth >= TreeRootIT->getBitWidth())
12038 return;
12039
12040 // If we can truncate the root, we must collect additional values that might
12041 // be demoted as a result. That is, those seeded by truncations we will
12042 // modify.
12043 while (!Roots.empty())
12044 collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
12045
12046 // Finally, map the values we can demote to the maximum bit with we computed.
12047 for (auto *Scalar : ToDemote)
12048 MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
12049}
12050
12051PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
12052 auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
12053 auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
12054 auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
12055 auto *AA = &AM.getResult<AAManager>(F);
12056 auto *LI = &AM.getResult<LoopAnalysis>(F);
12057 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
12058 auto *AC = &AM.getResult<AssumptionAnalysis>(F);
12059 auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
12060 auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
12061
12062 bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
12063 if (!Changed)
12064 return PreservedAnalyses::all();
12065
12066 PreservedAnalyses PA;
12067 PA.preserveSet<CFGAnalyses>();
12068 return PA;
12069}
12070
12071bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
12072 TargetTransformInfo *TTI_,
12073 TargetLibraryInfo *TLI_, AAResults *AA_,
12074 LoopInfo *LI_, DominatorTree *DT_,
12075 AssumptionCache *AC_, DemandedBits *DB_,
12076 OptimizationRemarkEmitter *ORE_) {
12077 if (!RunSLPVectorization)
12078 return false;
12079 SE = SE_;
12080 TTI = TTI_;
12081 TLI = TLI_;
12082 AA = AA_;
12083 LI = LI_;
12084 DT = DT_;
12085 AC = AC_;
12086 DB = DB_;
12087 DL = &F.getParent()->getDataLayout();
12088
12089 Stores.clear();
12090 GEPs.clear();
12091 bool Changed = false;
12092
12093 // If the target claims to have no vector registers don't attempt
12094 // vectorization.
12095 if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
12096 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Didn't find any vector registers for target, abort.\n"
; } } while (false)
12097 dbgs() << "SLP: Didn't find any vector registers for target, abort.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Didn't find any vector registers for target, abort.\n"
; } } while (false)
;
12098 return false;
12099 }
12100
12101 // Don't vectorize when the attribute NoImplicitFloat is used.
12102 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
12103 return false;
12104
12105 LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Analyzing blocks in " <<
F.getName() << ".\n"; } } while (false)
;
12106
12107 // Use the bottom up slp vectorizer to construct chains that start with
12108 // store instructions.
12109 BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
12110
12111 // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
12112 // delete instructions.
12113
12114 // Update DFS numbers now so that we can use them for ordering.
12115 DT->updateDFSNumbers();
12116
12117 // Scan the blocks in the function in post order.
12118 for (auto *BB : post_order(&F.getEntryBlock())) {
12119 // Start new block - clear the list of reduction roots.
12120 R.clearReductionData();
12121 collectSeedInstructions(BB);
12122
12123 // Vectorize trees that end at stores.
12124 if (!Stores.empty()) {
12125 LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Found stores for " << Stores
.size() << " underlying objects.\n"; } } while (false)
12126 << " underlying objects.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Found stores for " << Stores
.size() << " underlying objects.\n"; } } while (false)
;
12127 Changed |= vectorizeStoreChains(R);
12128 }
12129
12130 // Vectorize trees that end at reductions.
12131 Changed |= vectorizeChainsInBlock(BB, R);
12132
12133 // Vectorize the index computations of getelementptr instructions. This
12134 // is primarily intended to catch gather-like idioms ending at
12135 // non-consecutive loads.
12136 if (!GEPs.empty()) {
12137 LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Found GEPs for " << GEPs
.size() << " underlying objects.\n"; } } while (false)
12138 << " underlying objects.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Found GEPs for " << GEPs
.size() << " underlying objects.\n"; } } while (false)
;
12139 Changed |= vectorizeGEPIndices(BB, R);
12140 }
12141 }
12142
12143 if (Changed) {
12144 R.optimizeGatherSequence();
12145 LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: vectorized \"" << F.getName
() << "\"\n"; } } while (false)
;
12146 }
12147 return Changed;
12148}
12149
12150bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
12151 unsigned Idx, unsigned MinVF) {
12152 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Analyzing a store chain of length "
<< Chain.size() << "\n"; } } while (false)
12153 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Analyzing a store chain of length "
<< Chain.size() << "\n"; } } while (false)
;
12154 const unsigned Sz = R.getVectorElementSize(Chain[0]);
12155 unsigned VF = Chain.size();
12156
12157 if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
12158 return false;
12159
12160 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idxdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Analyzing " << VF <<
" stores at offset " << Idx << "\n"; } } while (
false)
12161 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Analyzing " << VF <<
" stores at offset " << Idx << "\n"; } } while (
false)
;
12162
12163 R.buildTree(Chain);
12164 if (R.isTreeTinyAndNotFullyVectorizable())
12165 return false;
12166 if (R.isLoadCombineCandidate())
12167 return false;
12168 R.reorderTopToBottom();
12169 R.reorderBottomToTop();
12170 R.buildExternalUses();
12171
12172 R.computeMinimumValueSizes();
12173
12174 InstructionCost Cost = R.getTreeCost();
12175
12176 LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF=" << VF << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Found cost = " << Cost
<< " for VF=" << VF << "\n"; } } while (false
)
;
12177 if (Cost < -SLPCostThreshold) {
12178 LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Decided to vectorize cost = "
<< Cost << "\n"; } } while (false)
;
12179
12180 using namespace ore;
12181
12182 R.getORE()->emit(OptimizationRemark(SV_NAME"slp-vectorizer", "StoresVectorized",
12183 cast<StoreInst>(Chain[0]))
12184 << "Stores SLP vectorized with cost " << NV("Cost", Cost)
12185 << " and with tree size "
12186 << NV("TreeSize", R.getTreeSize()));
12187
12188 R.vectorizeTree();
12189 return true;
12190 }
12191
12192 return false;
12193}
12194
12195bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
12196 BoUpSLP &R) {
12197 // We may run into multiple chains that merge into a single chain. We mark the
12198 // stores that we vectorized so that we don't visit the same store twice.
12199 BoUpSLP::ValueSet VectorizedStores;
12200 bool Changed = false;
12201
12202 int E = Stores.size();
12203 SmallBitVector Tails(E, false);
12204 int MaxIter = MaxStoreLookup.getValue();
12205 SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
12206 E, std::make_pair(E, INT_MAX2147483647));
12207 SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
12208 int IterCnt;
12209 auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
12210 &CheckedPairs,
12211 &ConsecutiveChain](int K, int Idx) {
12212 if (IterCnt >= MaxIter)
12213 return true;
12214 if (CheckedPairs[Idx].test(K))
12215 return ConsecutiveChain[K].second == 1 &&
12216 ConsecutiveChain[K].first == Idx;
12217 ++IterCnt;
12218 CheckedPairs[Idx].set(K);
12219 CheckedPairs[K].set(Idx);
12220 std::optional<int> Diff = getPointersDiff(
12221 Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
12222 Stores[Idx]->getValueOperand()->getType(),
12223 Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
12224 if (!Diff || *Diff == 0)
12225 return false;
12226 int Val = *Diff;
12227 if (Val < 0) {
12228 if (ConsecutiveChain[Idx].second > -Val) {
12229 Tails.set(K);
12230 ConsecutiveChain[Idx] = std::make_pair(K, -Val);
12231 }
12232 return false;
12233 }
12234 if (ConsecutiveChain[K].second <= Val)
12235 return false;
12236
12237 Tails.set(Idx);
12238 ConsecutiveChain[K] = std::make_pair(Idx, Val);
12239 return Val == 1;
12240 };
12241 // Do a quadratic search on all of the given stores in reverse order and find
12242 // all of the pairs of stores that follow each other.
12243 for (int Idx = E - 1; Idx >= 0; --Idx) {
12244 // If a store has multiple consecutive store candidates, search according
12245 // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
12246 // This is because usually pairing with immediate succeeding or preceding
12247 // candidate create the best chance to find slp vectorization opportunity.
12248 const int MaxLookDepth = std::max(E - Idx, Idx + 1);
12249 IterCnt = 0;
12250 for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
12251 if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
12252 (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
12253 break;
12254 }
12255
12256 // Tracks if we tried to vectorize stores starting from the given tail
12257 // already.
12258 SmallBitVector TriedTails(E, false);
12259 // For stores that start but don't end a link in the chain:
12260 for (int Cnt = E; Cnt > 0; --Cnt) {
12261 int I = Cnt - 1;
12262 if (ConsecutiveChain[I].first == E || Tails.test(I))
12263 continue;
12264 // We found a store instr that starts a chain. Now follow the chain and try
12265 // to vectorize it.
12266 BoUpSLP::ValueList Operands;
12267 // Collect the chain into a list.
12268 while (I != E && !VectorizedStores.count(Stores[I])) {
12269 Operands.push_back(Stores[I]);
12270 Tails.set(I);
12271 if (ConsecutiveChain[I].second != 1) {
12272 // Mark the new end in the chain and go back, if required. It might be
12273 // required if the original stores come in reversed order, for example.
12274 if (ConsecutiveChain[I].first != E &&
12275 Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
12276 !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
12277 TriedTails.set(I);
12278 Tails.reset(ConsecutiveChain[I].first);
12279 if (Cnt < ConsecutiveChain[I].first + 2)
12280 Cnt = ConsecutiveChain[I].first + 2;
12281 }
12282 break;
12283 }
12284 // Move to the next value in the chain.
12285 I = ConsecutiveChain[I].first;
12286 }
12287 assert(!Operands.empty() && "Expected non-empty list of stores.")(static_cast <bool> (!Operands.empty() && "Expected non-empty list of stores."
) ? void (0) : __assert_fail ("!Operands.empty() && \"Expected non-empty list of stores.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12287, __extension__
__PRETTY_FUNCTION__))
;
12288
12289 unsigned MaxVecRegSize = R.getMaxVecRegSize();
12290 unsigned EltSize = R.getVectorElementSize(Operands[0]);
12291 unsigned MaxElts = llvm::bit_floor(MaxVecRegSize / EltSize);
12292
12293 unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
12294 MaxElts);
12295 auto *Store = cast<StoreInst>(Operands[0]);
12296 Type *StoreTy = Store->getValueOperand()->getType();
12297 Type *ValueTy = StoreTy;
12298 if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
12299 ValueTy = Trunc->getSrcTy();
12300 unsigned MinVF = TTI->getStoreMinimumVF(
12301 R.getMinVF(DL->getTypeSizeInBits(ValueTy)), StoreTy, ValueTy);
12302
12303 if (MaxVF <= MinVF) {
12304 LLVM_DEBUG(dbgs() << "SLP: Vectorization infeasible as MaxVF (" << MaxVF << ") <= "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Vectorization infeasible as MaxVF ("
<< MaxVF << ") <= " << "MinVF (" <<
MinVF << ")\n"; } } while (false)
12305 << "MinVF (" << MinVF << ")\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Vectorization infeasible as MaxVF ("
<< MaxVF << ") <= " << "MinVF (" <<
MinVF << ")\n"; } } while (false)
;
12306 }
12307
12308 // FIXME: Is division-by-2 the correct step? Should we assert that the
12309 // register size is a power-of-2?
12310 unsigned StartIdx = 0;
12311 for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
12312 for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
12313 ArrayRef<Value *> Slice = ArrayRef(Operands).slice(Cnt, Size);
12314 if (!VectorizedStores.count(Slice.front()) &&
12315 !VectorizedStores.count(Slice.back()) &&
12316 vectorizeStoreChain(Slice, R, Cnt, MinVF)) {
12317 // Mark the vectorized stores so that we don't vectorize them again.
12318 VectorizedStores.insert(Slice.begin(), Slice.end());
12319 Changed = true;
12320 // If we vectorized initial block, no need to try to vectorize it
12321 // again.
12322 if (Cnt == StartIdx)
12323 StartIdx += Size;
12324 Cnt += Size;
12325 continue;
12326 }
12327 ++Cnt;
12328 }
12329 // Check if the whole array was vectorized already - exit.
12330 if (StartIdx >= Operands.size())
12331 break;
12332 }
12333 }
12334
12335 return Changed;
12336}
12337
12338void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
12339 // Initialize the collections. We will make a single pass over the block.
12340 Stores.clear();
12341 GEPs.clear();
12342
12343 // Visit the store and getelementptr instructions in BB and organize them in
12344 // Stores and GEPs according to the underlying objects of their pointer
12345 // operands.
12346 for (Instruction &I : *BB) {
12347 // Ignore store instructions that are volatile or have a pointer operand
12348 // that doesn't point to a scalar type.
12349 if (auto *SI = dyn_cast<StoreInst>(&I)) {
12350 if (!SI->isSimple())
12351 continue;
12352 if (!isValidElementType(SI->getValueOperand()->getType()))
12353 continue;
12354 Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
12355 }
12356
12357 // Ignore getelementptr instructions that have more than one index, a
12358 // constant index, or a pointer operand that doesn't point to a scalar
12359 // type.
12360 else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
12361 auto Idx = GEP->idx_begin()->get();
12362 if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
12363 continue;
12364 if (!isValidElementType(Idx->getType()))
12365 continue;
12366 if (GEP->getType()->isVectorTy())
12367 continue;
12368 GEPs[GEP->getPointerOperand()].push_back(GEP);
12369 }
12370 }
12371}
12372
12373bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
12374 if (!A || !B)
12375 return false;
12376 if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
12377 return false;
12378 Value *VL[] = {A, B};
12379 return tryToVectorizeList(VL, R);
12380}
12381
12382bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
12383 bool LimitForRegisterSize) {
12384 if (VL.size() < 2)
12385 return false;
12386
12387 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Trying to vectorize a list of length = "
<< VL.size() << ".\n"; } } while (false)
12388 << VL.size() << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Trying to vectorize a list of length = "
<< VL.size() << ".\n"; } } while (false)
;
12389
12390 // Check that all of the parts are instructions of the same type,
12391 // we permit an alternate opcode via InstructionsState.
12392 InstructionsState S = getSameOpcode(VL, *TLI);
12393 if (!S.getOpcode())
12394 return false;
12395
12396 Instruction *I0 = cast<Instruction>(S.OpValue);
12397 // Make sure invalid types (including vector type) are rejected before
12398 // determining vectorization factor for scalar instructions.
12399 for (Value *V : VL) {
12400 Type *Ty = V->getType();
12401 if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
12402 // NOTE: the following will give user internal llvm type name, which may
12403 // not be useful.
12404 R.getORE()->emit([&]() {
12405 std::string type_str;
12406 llvm::raw_string_ostream rso(type_str);
12407 Ty->print(rso);
12408 return OptimizationRemarkMissed(SV_NAME"slp-vectorizer", "UnsupportedType", I0)
12409 << "Cannot SLP vectorize list: type "
12410 << rso.str() + " is unsupported by vectorizer";
12411 });
12412 return false;
12413 }
12414 }
12415
12416 unsigned Sz = R.getVectorElementSize(I0);
12417 unsigned MinVF = R.getMinVF(Sz);
12418 unsigned MaxVF = std::max<unsigned>(llvm::bit_floor(VL.size()), MinVF);
12419 MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
12420 if (MaxVF < 2) {
12421 R.getORE()->emit([&]() {
12422 return OptimizationRemarkMissed(SV_NAME"slp-vectorizer", "SmallVF", I0)
12423 << "Cannot SLP vectorize list: vectorization factor "
12424 << "less than 2 is not supported";
12425 });
12426 return false;
12427 }
12428
12429 bool Changed = false;
12430 bool CandidateFound = false;
12431 InstructionCost MinCost = SLPCostThreshold.getValue();
12432 Type *ScalarTy = VL[0]->getType();
12433 if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
12434 ScalarTy = IE->getOperand(1)->getType();
12435
12436 unsigned NextInst = 0, MaxInst = VL.size();
12437 for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
12438 // No actual vectorization should happen, if number of parts is the same as
12439 // provided vectorization factor (i.e. the scalar type is used for vector
12440 // code during codegen).
12441 auto *VecTy = FixedVectorType::get(ScalarTy, VF);
12442 if (TTI->getNumberOfParts(VecTy) == VF)
12443 continue;
12444 for (unsigned I = NextInst; I < MaxInst; ++I) {
12445 unsigned OpsWidth = 0;
12446
12447 if (I + VF > MaxInst)
12448 OpsWidth = MaxInst - I;
12449 else
12450 OpsWidth = VF;
12451
12452 if (!isPowerOf2_32(OpsWidth))
12453 continue;
12454
12455 if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
12456 (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
12457 break;
12458
12459 ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
12460 // Check that a previous iteration of this loop did not delete the Value.
12461 if (llvm::any_of(Ops, [&R](Value *V) {
12462 auto *I = dyn_cast<Instruction>(V);
12463 return I && R.isDeleted(I);
12464 }))
12465 continue;
12466
12467 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Analyzing " << OpsWidth
<< " operations " << "\n"; } } while (false)
12468 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Analyzing " << OpsWidth
<< " operations " << "\n"; } } while (false)
;
12469
12470 R.buildTree(Ops);
12471 if (R.isTreeTinyAndNotFullyVectorizable())
12472 continue;
12473 R.reorderTopToBottom();
12474 R.reorderBottomToTop(
12475 /*IgnoreReorder=*/!isa<InsertElementInst>(Ops.front()) &&
12476 !R.doesRootHaveInTreeUses());
12477 R.buildExternalUses();
12478
12479 R.computeMinimumValueSizes();
12480 InstructionCost Cost = R.getTreeCost();
12481 CandidateFound = true;
12482 MinCost = std::min(MinCost, Cost);
12483
12484 LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Costdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Found cost = " << Cost
<< " for VF=" << OpsWidth << "\n"; } } while
(false)
12485 << " for VF=" << OpsWidth << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Found cost = " << Cost
<< " for VF=" << OpsWidth << "\n"; } } while
(false)
;
12486 if (Cost < -SLPCostThreshold) {
12487 LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Vectorizing list at cost:" <<
Cost << ".\n"; } } while (false)
;
12488 R.getORE()->emit(OptimizationRemark(SV_NAME"slp-vectorizer", "VectorizedList",
12489 cast<Instruction>(Ops[0]))
12490 << "SLP vectorized with cost " << ore::NV("Cost", Cost)
12491 << " and with tree size "
12492 << ore::NV("TreeSize", R.getTreeSize()));
12493
12494 R.vectorizeTree();
12495 // Move to the next bundle.
12496 I += VF - 1;
12497 NextInst = I + 1;
12498 Changed = true;
12499 }
12500 }
12501 }
12502
12503 if (!Changed && CandidateFound) {
12504 R.getORE()->emit([&]() {
12505 return OptimizationRemarkMissed(SV_NAME"slp-vectorizer", "NotBeneficial", I0)
12506 << "List vectorization was possible but not beneficial with cost "
12507 << ore::NV("Cost", MinCost) << " >= "
12508 << ore::NV("Treshold", -SLPCostThreshold);
12509 });
12510 } else if (!Changed) {
12511 R.getORE()->emit([&]() {
12512 return OptimizationRemarkMissed(SV_NAME"slp-vectorizer", "NotPossible", I0)
12513 << "Cannot SLP vectorize list: vectorization was impossible"
12514 << " with available vectorization factors";
12515 });
12516 }
12517 return Changed;
12518}
12519
12520bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
12521 if (!I)
12522 return false;
12523
12524 if (!isa<BinaryOperator, CmpInst>(I) || isa<VectorType>(I->getType()))
12525 return false;
12526
12527 Value *P = I->getParent();
12528
12529 // Vectorize in current basic block only.
12530 auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
12531 auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
12532 if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
12533 return false;
12534
12535 // First collect all possible candidates
12536 SmallVector<std::pair<Value *, Value *>, 4> Candidates;
12537 Candidates.emplace_back(Op0, Op1);
12538
12539 auto *A = dyn_cast<BinaryOperator>(Op0);
12540 auto *B = dyn_cast<BinaryOperator>(Op1);
12541 // Try to skip B.
12542 if (A && B && B->hasOneUse()) {
12543 auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
12544 auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
12545 if (B0 && B0->getParent() == P)
12546 Candidates.emplace_back(A, B0);
12547 if (B1 && B1->getParent() == P)
12548 Candidates.emplace_back(A, B1);
12549 }
12550 // Try to skip A.
12551 if (B && A && A->hasOneUse()) {
12552 auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
12553 auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
12554 if (A0 && A0->getParent() == P)
12555 Candidates.emplace_back(A0, B);
12556 if (A1 && A1->getParent() == P)
12557 Candidates.emplace_back(A1, B);
12558 }
12559
12560 if (Candidates.size() == 1)
12561 return tryToVectorizePair(Op0, Op1, R);
12562
12563 // We have multiple options. Try to pick the single best.
12564 std::optional<int> BestCandidate = R.findBestRootPair(Candidates);
12565 if (!BestCandidate)
12566 return false;
12567 return tryToVectorizePair(Candidates[*BestCandidate].first,
12568 Candidates[*BestCandidate].second, R);
12569}
12570
12571namespace {
12572
12573/// Model horizontal reductions.
12574///
12575/// A horizontal reduction is a tree of reduction instructions that has values
12576/// that can be put into a vector as its leaves. For example:
12577///
12578/// mul mul mul mul
12579/// \ / \ /
12580/// + +
12581/// \ /
12582/// +
12583/// This tree has "mul" as its leaf values and "+" as its reduction
12584/// instructions. A reduction can feed into a store or a binary operation
12585/// feeding a phi.
12586/// ...
12587/// \ /
12588/// +
12589/// |
12590/// phi +=
12591///
12592/// Or:
12593/// ...
12594/// \ /
12595/// +
12596/// |
12597/// *p =
12598///
12599class HorizontalReduction {
12600 using ReductionOpsType = SmallVector<Value *, 16>;
12601 using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
12602 ReductionOpsListType ReductionOps;
12603 /// List of possibly reduced values.
12604 SmallVector<SmallVector<Value *>> ReducedVals;
12605 /// Maps reduced value to the corresponding reduction operation.
12606 DenseMap<Value *, SmallVector<Instruction *>> ReducedValsToOps;
12607 // Use map vector to make stable output.
12608 MapVector<Instruction *, Value *> ExtraArgs;
12609 WeakTrackingVH ReductionRoot;
12610 /// The type of reduction operation.
12611 RecurKind RdxKind;
12612 /// Checks if the optimization of original scalar identity operations on
12613 /// matched horizontal reductions is enabled and allowed.
12614 bool IsSupportedHorRdxIdentityOp = false;
12615
12616 static bool isCmpSelMinMax(Instruction *I) {
12617 return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
12618 RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
12619 }
12620
12621 // And/or are potentially poison-safe logical patterns like:
12622 // select x, y, false
12623 // select x, true, y
12624 static bool isBoolLogicOp(Instruction *I) {
12625 return isa<SelectInst>(I) &&
12626 (match(I, m_LogicalAnd()) || match(I, m_LogicalOr()));
12627 }
12628
12629 /// Checks if instruction is associative and can be vectorized.
12630 static bool isVectorizable(RecurKind Kind, Instruction *I) {
12631 if (Kind == RecurKind::None)
12632 return false;
12633
12634 // Integer ops that map to select instructions or intrinsics are fine.
12635 if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
12636 isBoolLogicOp(I))
12637 return true;
12638
12639 if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
12640 // FP min/max are associative except for NaN and -0.0. We do not
12641 // have to rule out -0.0 here because the intrinsic semantics do not
12642 // specify a fixed result for it.
12643 return I->getFastMathFlags().noNaNs();
12644 }
12645
12646 return I->isAssociative();
12647 }
12648
12649 static Value *getRdxOperand(Instruction *I, unsigned Index) {
12650 // Poison-safe 'or' takes the form: select X, true, Y
12651 // To make that work with the normal operand processing, we skip the
12652 // true value operand.
12653 // TODO: Change the code and data structures to handle this without a hack.
12654 if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
12655 return I->getOperand(2);
12656 return I->getOperand(Index);
12657 }
12658
12659 /// Creates reduction operation with the current opcode.
12660 static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
12661 Value *RHS, const Twine &Name, bool UseSelect) {
12662 unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
12663 bool IsConstant = isConstant(LHS) && isConstant(RHS);
12664 switch (Kind) {
12665 case RecurKind::Or:
12666 if (UseSelect &&
12667 LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
12668 return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
12669 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
12670 Name);
12671 case RecurKind::And:
12672 if (UseSelect &&
12673 LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
12674 return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
12675 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
12676 Name);
12677 case RecurKind::Add:
12678 case RecurKind::Mul:
12679 case RecurKind::Xor:
12680 case RecurKind::FAdd:
12681 case RecurKind::FMul:
12682 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
12683 Name);
12684 case RecurKind::FMax:
12685 if (IsConstant)
12686 return ConstantFP::get(LHS->getType(),
12687 maxnum(cast<ConstantFP>(LHS)->getValueAPF(),
12688 cast<ConstantFP>(RHS)->getValueAPF()));
12689 return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
12690 case RecurKind::FMin:
12691 if (IsConstant)
12692 return ConstantFP::get(LHS->getType(),
12693 minnum(cast<ConstantFP>(LHS)->getValueAPF(),
12694 cast<ConstantFP>(RHS)->getValueAPF()));
12695 return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
12696 case RecurKind::SMax:
12697 if (IsConstant || UseSelect) {
12698 Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
12699 return Builder.CreateSelect(Cmp, LHS, RHS, Name);
12700 }
12701 return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
12702 case RecurKind::SMin:
12703 if (IsConstant || UseSelect) {
12704 Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
12705 return Builder.CreateSelect(Cmp, LHS, RHS, Name);
12706 }
12707 return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
12708 case RecurKind::UMax:
12709 if (IsConstant || UseSelect) {
12710 Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
12711 return Builder.CreateSelect(Cmp, LHS, RHS, Name);
12712 }
12713 return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
12714 case RecurKind::UMin:
12715 if (IsConstant || UseSelect) {
12716 Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
12717 return Builder.CreateSelect(Cmp, LHS, RHS, Name);
12718 }
12719 return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
12720 default:
12721 llvm_unreachable("Unknown reduction operation.")::llvm::llvm_unreachable_internal("Unknown reduction operation."
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12721)
;
12722 }
12723 }
12724
12725 /// Creates reduction operation with the current opcode with the IR flags
12726 /// from \p ReductionOps, dropping nuw/nsw flags.
12727 static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
12728 Value *RHS, const Twine &Name,
12729 const ReductionOpsListType &ReductionOps) {
12730 bool UseSelect = ReductionOps.size() == 2 ||
12731 // Logical or/and.
12732 (ReductionOps.size() == 1 &&
12733 isa<SelectInst>(ReductionOps.front().front()));
12734 assert((!UseSelect || ReductionOps.size() != 2 ||(static_cast <bool> ((!UseSelect || ReductionOps.size()
!= 2 || isa<SelectInst>(ReductionOps[1][0])) &&
"Expected cmp + select pairs for reduction") ? void (0) : __assert_fail
("(!UseSelect || ReductionOps.size() != 2 || isa<SelectInst>(ReductionOps[1][0])) && \"Expected cmp + select pairs for reduction\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12736, __extension__
__PRETTY_FUNCTION__))
12735 isa<SelectInst>(ReductionOps[1][0])) &&(static_cast <bool> ((!UseSelect || ReductionOps.size()
!= 2 || isa<SelectInst>(ReductionOps[1][0])) &&
"Expected cmp + select pairs for reduction") ? void (0) : __assert_fail
("(!UseSelect || ReductionOps.size() != 2 || isa<SelectInst>(ReductionOps[1][0])) && \"Expected cmp + select pairs for reduction\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12736, __extension__
__PRETTY_FUNCTION__))
12736 "Expected cmp + select pairs for reduction")(static_cast <bool> ((!UseSelect || ReductionOps.size()
!= 2 || isa<SelectInst>(ReductionOps[1][0])) &&
"Expected cmp + select pairs for reduction") ? void (0) : __assert_fail
("(!UseSelect || ReductionOps.size() != 2 || isa<SelectInst>(ReductionOps[1][0])) && \"Expected cmp + select pairs for reduction\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12736, __extension__
__PRETTY_FUNCTION__))
;
12737 Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
12738 if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
12739 if (auto *Sel = dyn_cast<SelectInst>(Op)) {
12740 propagateIRFlags(Sel->getCondition(), ReductionOps[0], nullptr,
12741 /*IncludeWrapFlags=*/false);
12742 propagateIRFlags(Op, ReductionOps[1], nullptr,
12743 /*IncludeWrapFlags=*/false);
12744 return Op;
12745 }
12746 }
12747 propagateIRFlags(Op, ReductionOps[0], nullptr, /*IncludeWrapFlags=*/false);
12748 return Op;
12749 }
12750
12751public:
12752 static RecurKind getRdxKind(Value *V) {
12753 auto *I = dyn_cast<Instruction>(V);
12754 if (!I)
12755 return RecurKind::None;
12756 if (match(I, m_Add(m_Value(), m_Value())))
12757 return RecurKind::Add;
12758 if (match(I, m_Mul(m_Value(), m_Value())))
12759 return RecurKind::Mul;
12760 if (match(I, m_And(m_Value(), m_Value())) ||
12761 match(I, m_LogicalAnd(m_Value(), m_Value())))
12762 return RecurKind::And;
12763 if (match(I, m_Or(m_Value(), m_Value())) ||
12764 match(I, m_LogicalOr(m_Value(), m_Value())))
12765 return RecurKind::Or;
12766 if (match(I, m_Xor(m_Value(), m_Value())))
12767 return RecurKind::Xor;
12768 if (match(I, m_FAdd(m_Value(), m_Value())))
12769 return RecurKind::FAdd;
12770 if (match(I, m_FMul(m_Value(), m_Value())))
12771 return RecurKind::FMul;
12772
12773 if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
12774 return RecurKind::FMax;
12775 if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
12776 return RecurKind::FMin;
12777
12778 // This matches either cmp+select or intrinsics. SLP is expected to handle
12779 // either form.
12780 // TODO: If we are canonicalizing to intrinsics, we can remove several
12781 // special-case paths that deal with selects.
12782 if (match(I, m_SMax(m_Value(), m_Value())))
12783 return RecurKind::SMax;
12784 if (match(I, m_SMin(m_Value(), m_Value())))
12785 return RecurKind::SMin;
12786 if (match(I, m_UMax(m_Value(), m_Value())))
12787 return RecurKind::UMax;
12788 if (match(I, m_UMin(m_Value(), m_Value())))
12789 return RecurKind::UMin;
12790
12791 if (auto *Select = dyn_cast<SelectInst>(I)) {
12792 // Try harder: look for min/max pattern based on instructions producing
12793 // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
12794 // During the intermediate stages of SLP, it's very common to have
12795 // pattern like this (since optimizeGatherSequence is run only once
12796 // at the end):
12797 // %1 = extractelement <2 x i32> %a, i32 0
12798 // %2 = extractelement <2 x i32> %a, i32 1
12799 // %cond = icmp sgt i32 %1, %2
12800 // %3 = extractelement <2 x i32> %a, i32 0
12801 // %4 = extractelement <2 x i32> %a, i32 1
12802 // %select = select i1 %cond, i32 %3, i32 %4
12803 CmpInst::Predicate Pred;
12804 Instruction *L1;
12805 Instruction *L2;
12806
12807 Value *LHS = Select->getTrueValue();
12808 Value *RHS = Select->getFalseValue();
12809 Value *Cond = Select->getCondition();
12810
12811 // TODO: Support inverse predicates.
12812 if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
12813 if (!isa<ExtractElementInst>(RHS) ||
12814 !L2->isIdenticalTo(cast<Instruction>(RHS)))
12815 return RecurKind::None;
12816 } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
12817 if (!isa<ExtractElementInst>(LHS) ||
12818 !L1->isIdenticalTo(cast<Instruction>(LHS)))
12819 return RecurKind::None;
12820 } else {
12821 if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
12822 return RecurKind::None;
12823 if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
12824 !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
12825 !L2->isIdenticalTo(cast<Instruction>(RHS)))
12826 return RecurKind::None;
12827 }
12828
12829 switch (Pred) {
12830 default:
12831 return RecurKind::None;
12832 case CmpInst::ICMP_SGT:
12833 case CmpInst::ICMP_SGE:
12834 return RecurKind::SMax;
12835 case CmpInst::ICMP_SLT:
12836 case CmpInst::ICMP_SLE:
12837 return RecurKind::SMin;
12838 case CmpInst::ICMP_UGT:
12839 case CmpInst::ICMP_UGE:
12840 return RecurKind::UMax;
12841 case CmpInst::ICMP_ULT:
12842 case CmpInst::ICMP_ULE:
12843 return RecurKind::UMin;
12844 }
12845 }
12846 return RecurKind::None;
12847 }
12848
12849 /// Get the index of the first operand.
12850 static unsigned getFirstOperandIndex(Instruction *I) {
12851 return isCmpSelMinMax(I) ? 1 : 0;
12852 }
12853
12854private:
12855 /// Total number of operands in the reduction operation.
12856 static unsigned getNumberOfOperands(Instruction *I) {
12857 return isCmpSelMinMax(I) ? 3 : 2;
12858 }
12859
12860 /// Checks if the instruction is in basic block \p BB.
12861 /// For a cmp+sel min/max reduction check that both ops are in \p BB.
12862 static bool hasSameParent(Instruction *I, BasicBlock *BB) {
12863 if (isCmpSelMinMax(I) || isBoolLogicOp(I)) {
12864 auto *Sel = cast<SelectInst>(I);
12865 auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
12866 return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
12867 }
12868 return I->getParent() == BB;
12869 }
12870
12871 /// Expected number of uses for reduction operations/reduced values.
12872 static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
12873 if (IsCmpSelMinMax) {
12874 // SelectInst must be used twice while the condition op must have single
12875 // use only.
12876 if (auto *Sel = dyn_cast<SelectInst>(I))
12877 return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
12878 return I->hasNUses(2);
12879 }
12880
12881 // Arithmetic reduction operation must be used once only.
12882 return I->hasOneUse();
12883 }
12884
12885 /// Initializes the list of reduction operations.
12886 void initReductionOps(Instruction *I) {
12887 if (isCmpSelMinMax(I))
12888 ReductionOps.assign(2, ReductionOpsType());
12889 else
12890 ReductionOps.assign(1, ReductionOpsType());
12891 }
12892
12893 /// Add all reduction operations for the reduction instruction \p I.
12894 void addReductionOps(Instruction *I) {
12895 if (isCmpSelMinMax(I)) {
12896 ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
12897 ReductionOps[1].emplace_back(I);
12898 } else {
12899 ReductionOps[0].emplace_back(I);
12900 }
12901 }
12902
12903 static bool isGoodForReduction(ArrayRef<Value *> Data) {
12904 int Sz = Data.size();
12905 auto *I = dyn_cast<Instruction>(Data.front());
12906 return Sz > 1 || isConstant(Data.front()) ||
12907 (I && !isa<LoadInst>(I) && isValidForAlternation(I->getOpcode()));
12908 }
12909
12910public:
12911 HorizontalReduction() = default;
12912
12913 /// Try to find a reduction tree.
12914 bool matchAssociativeReduction(BoUpSLP &R, Instruction *Root,
12915 ScalarEvolution &SE, const DataLayout &DL,
12916 const TargetLibraryInfo &TLI) {
12917 RdxKind = HorizontalReduction::getRdxKind(Root);
12918 if (!isVectorizable(RdxKind, Root))
12919 return false;
12920
12921 // Analyze "regular" integer/FP types for reductions - no target-specific
12922 // types or pointers.
12923 Type *Ty = Root->getType();
12924 if (!isValidElementType(Ty) || Ty->isPointerTy())
12925 return false;
12926
12927 // Though the ultimate reduction may have multiple uses, its condition must
12928 // have only single use.
12929 if (auto *Sel = dyn_cast<SelectInst>(Root))
12930 if (!Sel->getCondition()->hasOneUse())
12931 return false;
12932
12933 ReductionRoot = Root;
12934
12935 // Iterate through all the operands of the possible reduction tree and
12936 // gather all the reduced values, sorting them by their value id.
12937 BasicBlock *BB = Root->getParent();
12938 bool IsCmpSelMinMax = isCmpSelMinMax(Root);
12939 SmallVector<Instruction *> Worklist(1, Root);
12940 // Checks if the operands of the \p TreeN instruction are also reduction
12941 // operations or should be treated as reduced values or an extra argument,
12942 // which is not part of the reduction.
12943 auto CheckOperands = [&](Instruction *TreeN,
12944 SmallVectorImpl<Value *> &ExtraArgs,
12945 SmallVectorImpl<Value *> &PossibleReducedVals,
12946 SmallVectorImpl<Instruction *> &ReductionOps) {
12947 for (int I = getFirstOperandIndex(TreeN),
12948 End = getNumberOfOperands(TreeN);
12949 I < End; ++I) {
12950 Value *EdgeVal = getRdxOperand(TreeN, I);
12951 ReducedValsToOps[EdgeVal].push_back(TreeN);
12952 auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
12953 // Edge has wrong parent - mark as an extra argument.
12954 if (EdgeInst && !isVectorLikeInstWithConstOps(EdgeInst) &&
12955 !hasSameParent(EdgeInst, BB)) {
12956 ExtraArgs.push_back(EdgeVal);
12957 continue;
12958 }
12959 // If the edge is not an instruction, or it is different from the main
12960 // reduction opcode or has too many uses - possible reduced value.
12961 // Also, do not try to reduce const values, if the operation is not
12962 // foldable.
12963 if (!EdgeInst || getRdxKind(EdgeInst) != RdxKind ||
12964 IsCmpSelMinMax != isCmpSelMinMax(EdgeInst) ||
12965 !hasRequiredNumberOfUses(IsCmpSelMinMax, EdgeInst) ||
12966 !isVectorizable(RdxKind, EdgeInst) ||
12967 (R.isAnalyzedReductionRoot(EdgeInst) &&
12968 all_of(EdgeInst->operands(), Constant::classof))) {
12969 PossibleReducedVals.push_back(EdgeVal);
12970 continue;
12971 }
12972 ReductionOps.push_back(EdgeInst);
12973 }
12974 };
12975 // Try to regroup reduced values so that it gets more profitable to try to
12976 // reduce them. Values are grouped by their value ids, instructions - by
12977 // instruction op id and/or alternate op id, plus do extra analysis for
12978 // loads (grouping them by the distabce between pointers) and cmp
12979 // instructions (grouping them by the predicate).
12980 MapVector<size_t, MapVector<size_t, MapVector<Value *, unsigned>>>
12981 PossibleReducedVals;
12982 initReductionOps(Root);
12983 DenseMap<Value *, SmallVector<LoadInst *>> LoadsMap;
12984 SmallSet<size_t, 2> LoadKeyUsed;
12985 SmallPtrSet<Value *, 4> DoNotReverseVals;
12986
12987 auto GenerateLoadsSubkey = [&](size_t Key, LoadInst *LI) {
12988 Value *Ptr = getUnderlyingObject(LI->getPointerOperand());
12989 if (LoadKeyUsed.contains(Key)) {
12990 auto LIt = LoadsMap.find(Ptr);
12991 if (LIt != LoadsMap.end()) {
12992 for (LoadInst *RLI : LIt->second) {
12993 if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
12994 LI->getType(), LI->getPointerOperand(), DL, SE,
12995 /*StrictCheck=*/true))
12996 return hash_value(RLI->getPointerOperand());
12997 }
12998 for (LoadInst *RLI : LIt->second) {
12999 if (arePointersCompatible(RLI->getPointerOperand(),
13000 LI->getPointerOperand(), TLI)) {
13001 hash_code SubKey = hash_value(RLI->getPointerOperand());
13002 DoNotReverseVals.insert(RLI);
13003 return SubKey;
13004 }
13005 }
13006 if (LIt->second.size() > 2) {
13007 hash_code SubKey =
13008 hash_value(LIt->second.back()->getPointerOperand());
13009 DoNotReverseVals.insert(LIt->second.back());
13010 return SubKey;
13011 }
13012 }
13013 }
13014 LoadKeyUsed.insert(Key);
13015 LoadsMap.try_emplace(Ptr).first->second.push_back(LI);
13016 return hash_value(LI->getPointerOperand());
13017 };
13018
13019 while (!Worklist.empty()) {
13020 Instruction *TreeN = Worklist.pop_back_val();
13021 SmallVector<Value *> Args;
13022 SmallVector<Value *> PossibleRedVals;
13023 SmallVector<Instruction *> PossibleReductionOps;
13024 CheckOperands(TreeN, Args, PossibleRedVals, PossibleReductionOps);
13025 // If too many extra args - mark the instruction itself as a reduction
13026 // value, not a reduction operation.
13027 if (Args.size() < 2) {
13028 addReductionOps(TreeN);
13029 // Add extra args.
13030 if (!Args.empty()) {
13031 assert(Args.size() == 1 && "Expected only single argument.")(static_cast <bool> (Args.size() == 1 && "Expected only single argument."
) ? void (0) : __assert_fail ("Args.size() == 1 && \"Expected only single argument.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 13031, __extension__
__PRETTY_FUNCTION__))
;
13032 ExtraArgs[TreeN] = Args.front();
13033 }
13034 // Add reduction values. The values are sorted for better vectorization
13035 // results.
13036 for (Value *V : PossibleRedVals) {
13037 size_t Key, Idx;
13038 std::tie(Key, Idx) = generateKeySubkey(V, &TLI, GenerateLoadsSubkey,
13039 /*AllowAlternate=*/false);
13040 ++PossibleReducedVals[Key][Idx]
13041 .insert(std::make_pair(V, 0))
13042 .first->second;
13043 }
13044 Worklist.append(PossibleReductionOps.rbegin(),
13045 PossibleReductionOps.rend());
13046 } else {
13047 size_t Key, Idx;
13048 std::tie(Key, Idx) = generateKeySubkey(TreeN, &TLI, GenerateLoadsSubkey,
13049 /*AllowAlternate=*/false);
13050 ++PossibleReducedVals[Key][Idx]
13051 .insert(std::make_pair(TreeN, 0))
13052 .first->second;
13053 }
13054 }
13055 auto PossibleReducedValsVect = PossibleReducedVals.takeVector();
13056 // Sort values by the total number of values kinds to start the reduction
13057 // from the longest possible reduced values sequences.
13058 for (auto &PossibleReducedVals : PossibleReducedValsVect) {
13059 auto PossibleRedVals = PossibleReducedVals.second.takeVector();
13060 SmallVector<SmallVector<Value *>> PossibleRedValsVect;
13061 for (auto It = PossibleRedVals.begin(), E = PossibleRedVals.end();
13062 It != E; ++It) {
13063 PossibleRedValsVect.emplace_back();
13064 auto RedValsVect = It->second.takeVector();
13065 stable_sort(RedValsVect, llvm::less_second());
13066 for (const std::pair<Value *, unsigned> &Data : RedValsVect)
13067 PossibleRedValsVect.back().append(Data.second, Data.first);
13068 }
13069 stable_sort(PossibleRedValsVect, [](const auto &P1, const auto &P2) {
13070 return P1.size() > P2.size();
13071 });
13072 int NewIdx = -1;
13073 for (ArrayRef<Value *> Data : PossibleRedValsVect) {
13074 if (isGoodForReduction(Data) ||
13075 (isa<LoadInst>(Data.front()) && NewIdx >= 0 &&
13076 isa<LoadInst>(ReducedVals[NewIdx].front()) &&
13077 getUnderlyingObject(
13078 cast<LoadInst>(Data.front())->getPointerOperand()) ==
13079 getUnderlyingObject(cast<LoadInst>(ReducedVals[NewIdx].front())
13080 ->getPointerOperand()))) {
13081 if (NewIdx < 0) {
13082 NewIdx = ReducedVals.size();
13083 ReducedVals.emplace_back();
13084 }
13085 if (DoNotReverseVals.contains(Data.front()))
13086 ReducedVals[NewIdx].append(Data.begin(), Data.end());
13087 else
13088 ReducedVals[NewIdx].append(Data.rbegin(), Data.rend());
13089 } else {
13090 ReducedVals.emplace_back().append(Data.rbegin(), Data.rend());
13091 }
13092 }
13093 }
13094 // Sort the reduced values by number of same/alternate opcode and/or pointer
13095 // operand.
13096 stable_sort(ReducedVals, [](ArrayRef<Value *> P1, ArrayRef<Value *> P2) {
13097 return P1.size() > P2.size();
13098 });
13099 return true;
13100 }
13101
13102 /// Attempt to vectorize the tree found by matchAssociativeReduction.
13103 Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI,
13104 const TargetLibraryInfo &TLI) {
13105 constexpr int ReductionLimit = 4;
13106 constexpr unsigned RegMaxNumber = 4;
13107 constexpr unsigned RedValsMaxNumber = 128;
13108 // If there are a sufficient number of reduction values, reduce
13109 // to a nearby power-of-2. We can safely generate oversized
13110 // vectors and rely on the backend to split them to legal sizes.
13111 unsigned NumReducedVals =
13112 std::accumulate(ReducedVals.begin(), ReducedVals.end(), 0,
13113 [](unsigned Num, ArrayRef<Value *> Vals) -> unsigned {
13114 if (!isGoodForReduction(Vals))
13115 return Num;
13116 return Num + Vals.size();
13117 });
13118 if (NumReducedVals < ReductionLimit &&
13119 (!AllowHorRdxIdenityOptimization ||
13120 all_of(ReducedVals, [](ArrayRef<Value *> RedV) {
13121 return RedV.size() < 2 || !allConstant(RedV) || !isSplat(RedV);
13122 }))) {
13123 for (ReductionOpsType &RdxOps : ReductionOps)
13124 for (Value *RdxOp : RdxOps)
13125 V.analyzedReductionRoot(cast<Instruction>(RdxOp));
13126 return nullptr;
13127 }
13128
13129 IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
13130
13131 // Track the reduced values in case if they are replaced by extractelement
13132 // because of the vectorization.
13133 DenseMap<Value *, WeakTrackingVH> TrackedVals(
13134 ReducedVals.size() * ReducedVals.front().size() + ExtraArgs.size());
13135 BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
13136 SmallVector<std::pair<Value *, Value *>> ReplacedExternals;
13137 ExternallyUsedValues.reserve(ExtraArgs.size() + 1);
13138 // The same extra argument may be used several times, so log each attempt
13139 // to use it.
13140 for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
13141 assert(Pair.first && "DebugLoc must be set.")(static_cast <bool> (Pair.first && "DebugLoc must be set."
) ? void (0) : __assert_fail ("Pair.first && \"DebugLoc must be set.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 13141, __extension__
__PRETTY_FUNCTION__))
;
13142 ExternallyUsedValues[Pair.second].push_back(Pair.first);
13143 TrackedVals.try_emplace(Pair.second, Pair.second);
13144 }
13145
13146 // The compare instruction of a min/max is the insertion point for new
13147 // instructions and may be replaced with a new compare instruction.
13148 auto &&GetCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
13149 assert(isa<SelectInst>(RdxRootInst) &&(static_cast <bool> (isa<SelectInst>(RdxRootInst)
&& "Expected min/max reduction to have select root instruction"
) ? void (0) : __assert_fail ("isa<SelectInst>(RdxRootInst) && \"Expected min/max reduction to have select root instruction\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 13150, __extension__
__PRETTY_FUNCTION__))
13150 "Expected min/max reduction to have select root instruction")(static_cast <bool> (isa<SelectInst>(RdxRootInst)
&& "Expected min/max reduction to have select root instruction"
) ? void (0) : __assert_fail ("isa<SelectInst>(RdxRootInst) && \"Expected min/max reduction to have select root instruction\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 13150, __extension__
__PRETTY_FUNCTION__))
;
13151 Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
13152 assert(isa<Instruction>(ScalarCond) &&(static_cast <bool> (isa<Instruction>(ScalarCond)
&& "Expected min/max reduction to have compare condition"
) ? void (0) : __assert_fail ("isa<Instruction>(ScalarCond) && \"Expected min/max reduction to have compare condition\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 13153, __extension__
__PRETTY_FUNCTION__))
13153 "Expected min/max reduction to have compare condition")(static_cast <bool> (isa<Instruction>(ScalarCond)
&& "Expected min/max reduction to have compare condition"
) ? void (0) : __assert_fail ("isa<Instruction>(ScalarCond) && \"Expected min/max reduction to have compare condition\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 13153, __extension__
__PRETTY_FUNCTION__))
;
13154 return cast<Instruction>(ScalarCond);
13155 };
13156
13157 // Return new VectorizedTree, based on previous value.
13158 auto GetNewVectorizedTree = [&](Value *VectorizedTree, Value *Res) {
13159 if (VectorizedTree) {
13160 // Update the final value in the reduction.
13161 Builder.SetCurrentDebugLocation(
13162 cast<Instruction>(ReductionOps.front().front())->getDebugLoc());
13163 return createOp(Builder, RdxKind, VectorizedTree, Res, "op.rdx",
13164 ReductionOps);
13165 }
13166 // Initialize the final value in the reduction.
13167 return Res;
13168 };
13169 // The reduction root is used as the insertion point for new instructions,
13170 // so set it as externally used to prevent it from being deleted.
13171 ExternallyUsedValues[ReductionRoot];
13172 SmallDenseSet<Value *> IgnoreList(ReductionOps.size() *
13173 ReductionOps.front().size());
13174 for (ReductionOpsType &RdxOps : ReductionOps)
13175 for (Value *RdxOp : RdxOps) {
13176 if (!RdxOp)
13177 continue;
13178 IgnoreList.insert(RdxOp);
13179 }
13180 // Intersect the fast-math-flags from all reduction operations.
13181 FastMathFlags RdxFMF;
13182 RdxFMF.set();
13183 for (Value *U : IgnoreList)
13184 if (auto *FPMO = dyn_cast<FPMathOperator>(U))
13185 RdxFMF &= FPMO->getFastMathFlags();
13186 bool IsCmpSelMinMax = isCmpSelMinMax(cast<Instruction>(ReductionRoot));
13187
13188 // Need to track reduced vals, they may be changed during vectorization of
13189 // subvectors.
13190 for (ArrayRef<Value *> Candidates : ReducedVals)
13191 for (Value *V : Candidates)
13192 TrackedVals.try_emplace(V, V);
13193
13194 DenseMap<Value *, unsigned> VectorizedVals(ReducedVals.size());
13195 // List of the values that were reduced in other trees as part of gather
13196 // nodes and thus requiring extract if fully vectorized in other trees.
13197 SmallPtrSet<Value *, 4> RequiredExtract;
13198 Value *VectorizedTree = nullptr;
13199 bool CheckForReusedReductionOps = false;
13200 // Try to vectorize elements based on their type.
13201 for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
13202 ArrayRef<Value *> OrigReducedVals = ReducedVals[I];
13203 InstructionsState S = getSameOpcode(OrigReducedVals, TLI);
13204 SmallVector<Value *> Candidates;
13205 Candidates.reserve(2 * OrigReducedVals.size());
13206 DenseMap<Value *, Value *> TrackedToOrig(2 * OrigReducedVals.size());
13207 for (unsigned Cnt = 0, Sz = OrigReducedVals.size(); Cnt < Sz; ++Cnt) {
13208 Value *RdxVal = TrackedVals.find(OrigReducedVals[Cnt])->second;
13209 // Check if the reduction value was not overriden by the extractelement
13210 // instruction because of the vectorization and exclude it, if it is not
13211 // compatible with other values.
13212 if (auto *Inst = dyn_cast<Instruction>(RdxVal))
13213 if (isVectorLikeInstWithConstOps(Inst) &&
13214 (!S.getOpcode() || !S.isOpcodeOrAlt(Inst)))
13215 continue;
13216 Candidates.push_back(RdxVal);
13217 TrackedToOrig.try_emplace(RdxVal, OrigReducedVals[Cnt]);
13218 }
13219 bool ShuffledExtracts = false;
13220 // Try to handle shuffled extractelements.
13221 if (S.getOpcode() == Instruction::ExtractElement && !S.isAltShuffle() &&
13222 I + 1 < E) {
13223 InstructionsState NextS = getSameOpcode(ReducedVals[I + 1], TLI);
13224 if (NextS.getOpcode() == Instruction::ExtractElement &&
13225 !NextS.isAltShuffle()) {
13226 SmallVector<Value *> CommonCandidates(Candidates);
13227 for (Value *RV : ReducedVals[I + 1]) {
13228 Value *RdxVal = TrackedVals.find(RV)->second;
13229 // Check if the reduction value was not overriden by the
13230 // extractelement instruction because of the vectorization and
13231 // exclude it, if it is not compatible with other values.
13232 if (auto *Inst = dyn_cast<Instruction>(RdxVal))
13233 if (!NextS.getOpcode() || !NextS.isOpcodeOrAlt(Inst))
13234 continue;
13235 CommonCandidates.push_back(RdxVal);
13236 TrackedToOrig.try_emplace(RdxVal, RV);
13237 }
13238 SmallVector<int> Mask;
13239 if (isFixedVectorShuffle(CommonCandidates, Mask)) {
13240 ++I;
13241 Candidates.swap(CommonCandidates);
13242 ShuffledExtracts = true;
13243 }
13244 }
13245 }
13246
13247 // Emit code for constant values.
13248 if (AllowHorRdxIdenityOptimization && Candidates.size() > 1 &&
13249 allConstant(Candidates)) {
13250 Value *Res = Candidates.front();
13251 ++VectorizedVals.try_emplace(Candidates.front(), 0).first->getSecond();
13252 for (Value *VC : ArrayRef(Candidates).drop_front()) {
13253 Res = createOp(Builder, RdxKind, Res, VC, "const.rdx", ReductionOps);
13254 ++VectorizedVals.try_emplace(VC, 0).first->getSecond();
13255 if (auto *ResI = dyn_cast<Instruction>(Res))
13256 V.analyzedReductionRoot(ResI);
13257 }
13258 VectorizedTree = GetNewVectorizedTree(VectorizedTree, Res);
13259 continue;
13260 }
13261
13262 unsigned NumReducedVals = Candidates.size();
13263 if (NumReducedVals < ReductionLimit &&
13264 (NumReducedVals < 2 || !AllowHorRdxIdenityOptimization ||
13265 !isSplat(Candidates)))
13266 continue;
13267
13268 // Check if we support repeated scalar values processing (optimization of
13269 // original scalar identity operations on matched horizontal reductions).
13270 IsSupportedHorRdxIdentityOp =
13271 AllowHorRdxIdenityOptimization && RdxKind != RecurKind::Mul &&
13272 RdxKind != RecurKind::FMul && RdxKind != RecurKind::FMulAdd;
13273 // Gather same values.
13274 MapVector<Value *, unsigned> SameValuesCounter;
13275 if (IsSupportedHorRdxIdentityOp)
13276 for (Value *V : Candidates)
13277 ++SameValuesCounter.insert(std::make_pair(V, 0)).first->second;
13278 // Used to check if the reduced values used same number of times. In this
13279 // case the compiler may produce better code. E.g. if reduced values are
13280 // aabbccdd (8 x values), then the first node of the tree will have a node
13281 // for 4 x abcd + shuffle <4 x abcd>, <0, 0, 1, 1, 2, 2, 3, 3>.
13282 // Plus, the final reduction will be performed on <8 x aabbccdd>.
13283 // Instead compiler may build <4 x abcd> tree immediately, + reduction (4
13284 // x abcd) * 2.
13285 // Currently it only handles add/fadd/xor. and/or/min/max do not require
13286 // this analysis, other operations may require an extra estimation of
13287 // the profitability.
13288 bool SameScaleFactor = false;
13289 bool OptReusedScalars = IsSupportedHorRdxIdentityOp &&
13290 SameValuesCounter.size() != Candidates.size();
13291 if (OptReusedScalars) {
13292 SameScaleFactor =
13293 (RdxKind == RecurKind::Add || RdxKind == RecurKind::FAdd ||
13294 RdxKind == RecurKind::Xor) &&
13295 all_of(drop_begin(SameValuesCounter),
13296 [&SameValuesCounter](const std::pair<Value *, unsigned> &P) {
13297 return P.second == SameValuesCounter.front().second;
13298 });
13299 Candidates.resize(SameValuesCounter.size());
13300 transform(SameValuesCounter, Candidates.begin(),
13301 [](const auto &P) { return P.first; });
13302 NumReducedVals = Candidates.size();
13303 // Have a reduction of the same element.
13304 if (NumReducedVals == 1) {
13305 Value *OrigV = TrackedToOrig.find(Candidates.front())->second;
13306 unsigned Cnt = SameValuesCounter.lookup(OrigV);
13307 Value *RedVal =
13308 emitScaleForReusedOps(Candidates.front(), Builder, Cnt);
13309 VectorizedTree = GetNewVectorizedTree(VectorizedTree, RedVal);
13310 VectorizedVals.try_emplace(OrigV, Cnt);
13311 continue;
13312 }
13313 }
13314
13315 unsigned MaxVecRegSize = V.getMaxVecRegSize();
13316 unsigned EltSize = V.getVectorElementSize(Candidates[0]);
13317 unsigned MaxElts =
13318 RegMaxNumber * llvm::bit_floor(MaxVecRegSize / EltSize);
13319
13320 unsigned ReduxWidth = std::min<unsigned>(
13321 llvm::bit_floor(NumReducedVals), std::max(RedValsMaxNumber, MaxElts));
13322 unsigned Start = 0;
13323 unsigned Pos = Start;
13324 // Restarts vectorization attempt with lower vector factor.
13325 unsigned PrevReduxWidth = ReduxWidth;
13326 bool CheckForReusedReductionOpsLocal = false;
13327 auto &&AdjustReducedVals = [&Pos, &Start, &ReduxWidth, NumReducedVals,
13328 &CheckForReusedReductionOpsLocal,
13329 &PrevReduxWidth, &V,
13330 &IgnoreList](bool IgnoreVL = false) {
13331 bool IsAnyRedOpGathered = !IgnoreVL && V.isAnyGathered(IgnoreList);
13332 if (!CheckForReusedReductionOpsLocal && PrevReduxWidth == ReduxWidth) {
13333 // Check if any of the reduction ops are gathered. If so, worth
13334 // trying again with less number of reduction ops.
13335 CheckForReusedReductionOpsLocal |= IsAnyRedOpGathered;
13336 }
13337 ++Pos;
13338 if (Pos < NumReducedVals - ReduxWidth + 1)
13339 return IsAnyRedOpGathered;
13340 Pos = Start;
13341 ReduxWidth /= 2;
13342 return IsAnyRedOpGathered;
13343 };
13344 bool AnyVectorized = false;
13345 while (Pos < NumReducedVals - ReduxWidth + 1 &&
13346 ReduxWidth >= ReductionLimit) {
13347 // Dependency in tree of the reduction ops - drop this attempt, try
13348 // later.
13349 if (CheckForReusedReductionOpsLocal && PrevReduxWidth != ReduxWidth &&
13350 Start == 0) {
13351 CheckForReusedReductionOps = true;
13352 break;
13353 }
13354 PrevReduxWidth = ReduxWidth;
13355 ArrayRef<Value *> VL(std::next(Candidates.begin(), Pos), ReduxWidth);
13356 // Beeing analyzed already - skip.
13357 if (V.areAnalyzedReductionVals(VL)) {
13358 (void)AdjustReducedVals(/*IgnoreVL=*/true);
13359 continue;
13360 }
13361 // Early exit if any of the reduction values were deleted during
13362 // previous vectorization attempts.
13363 if (any_of(VL, [&V](Value *RedVal) {
13364 auto *RedValI = dyn_cast<Instruction>(RedVal);
13365 if (!RedValI)
13366 return false;
13367 return V.isDeleted(RedValI);
13368 }))
13369 break;
13370 V.buildTree(VL, IgnoreList);
13371 if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) {
13372 if (!AdjustReducedVals())
13373 V.analyzedReductionVals(VL);
13374 continue;
13375 }
13376 if (V.isLoadCombineReductionCandidate(RdxKind)) {
13377 if (!AdjustReducedVals())
13378 V.analyzedReductionVals(VL);
13379 continue;
13380 }
13381 V.reorderTopToBottom();
13382 // No need to reorder the root node at all.
13383 V.reorderBottomToTop(/*IgnoreReorder=*/true);
13384 // Keep extracted other reduction values, if they are used in the
13385 // vectorization trees.
13386 BoUpSLP::ExtraValueToDebugLocsMap LocalExternallyUsedValues(
13387 ExternallyUsedValues);
13388 for (unsigned Cnt = 0, Sz = ReducedVals.size(); Cnt < Sz; ++Cnt) {
13389 if (Cnt == I || (ShuffledExtracts && Cnt == I - 1))
13390 continue;
13391 for_each(ReducedVals[Cnt],
13392 [&LocalExternallyUsedValues, &TrackedVals](Value *V) {
13393 if (isa<Instruction>(V))
13394 LocalExternallyUsedValues[TrackedVals[V]];
13395 });
13396 }
13397 if (!IsSupportedHorRdxIdentityOp) {
13398 // Number of uses of the candidates in the vector of values.
13399 assert(SameValuesCounter.empty() &&(static_cast <bool> (SameValuesCounter.empty() &&
"Reused values counter map is not empty") ? void (0) : __assert_fail
("SameValuesCounter.empty() && \"Reused values counter map is not empty\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 13400, __extension__
__PRETTY_FUNCTION__))
13400 "Reused values counter map is not empty")(static_cast <bool> (SameValuesCounter.empty() &&
"Reused values counter map is not empty") ? void (0) : __assert_fail
("SameValuesCounter.empty() && \"Reused values counter map is not empty\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 13400, __extension__
__PRETTY_FUNCTION__))
;
13401 for (unsigned Cnt = 0; Cnt < NumReducedVals; ++Cnt) {
13402 if (Cnt >= Pos && Cnt < Pos + ReduxWidth)
13403 continue;
13404 Value *V = Candidates[Cnt];
13405 Value *OrigV = TrackedToOrig.find(V)->second;
13406 ++SameValuesCounter[OrigV];
13407 }
13408 }
13409 SmallPtrSet<Value *, 4> VLScalars(VL.begin(), VL.end());
13410 // Gather externally used values.
13411 SmallPtrSet<Value *, 4> Visited;
13412 for (unsigned Cnt = 0; Cnt < NumReducedVals; ++Cnt) {
13413 if (Cnt >= Pos && Cnt < Pos + ReduxWidth)
13414 continue;
13415 Value *RdxVal = Candidates[Cnt];
13416 if (!Visited.insert(RdxVal).second)
13417 continue;
13418 // Check if the scalar was vectorized as part of the vectorization
13419 // tree but not the top node.
13420 if (!VLScalars.contains(RdxVal) && V.isVectorized(RdxVal)) {
13421 LocalExternallyUsedValues[RdxVal];
13422 continue;
13423 }
13424 Value *OrigV = TrackedToOrig.find(RdxVal)->second;
13425 unsigned NumOps =
13426 VectorizedVals.lookup(RdxVal) + SameValuesCounter[OrigV];
13427 if (NumOps != ReducedValsToOps.find(OrigV)->second.size())
13428 LocalExternallyUsedValues[RdxVal];
13429 }
13430 // Do not need the list of reused scalars in regular mode anymore.
13431 if (!IsSupportedHorRdxIdentityOp)
13432 SameValuesCounter.clear();
13433 for (Value *RdxVal : VL)
13434 if (RequiredExtract.contains(RdxVal))
13435 LocalExternallyUsedValues[RdxVal];
13436 // Update LocalExternallyUsedValues for the scalar, replaced by
13437 // extractelement instructions.
13438 for (const std::pair<Value *, Value *> &Pair : ReplacedExternals) {
13439 auto It = ExternallyUsedValues.find(Pair.first);
13440 if (It == ExternallyUsedValues.end())
13441 continue;
13442 LocalExternallyUsedValues[Pair.second].append(It->second);
13443 }
13444 V.buildExternalUses(LocalExternallyUsedValues);
13445
13446 V.computeMinimumValueSizes();
13447
13448 // Estimate cost.
13449 InstructionCost TreeCost = V.getTreeCost(VL);
13450 InstructionCost ReductionCost =
13451 getReductionCost(TTI, VL, IsCmpSelMinMax, ReduxWidth, RdxFMF);
13452 InstructionCost Cost = TreeCost + ReductionCost;
13453 LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for reduction\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Found cost = " << Cost
<< " for reduction\n"; } } while (false)
;
13454 if (!Cost.isValid())
13455 return nullptr;
13456 if (Cost >= -SLPCostThreshold) {
13457 V.getORE()->emit([&]() {
13458 return OptimizationRemarkMissed(
13459 SV_NAME"slp-vectorizer", "HorSLPNotBeneficial",
13460 ReducedValsToOps.find(VL[0])->second.front())
13461 << "Vectorizing horizontal reduction is possible "
13462 << "but not beneficial with cost " << ore::NV("Cost", Cost)
13463 << " and threshold "
13464 << ore::NV("Threshold", -SLPCostThreshold);
13465 });
13466 if (!AdjustReducedVals())
13467 V.analyzedReductionVals(VL);
13468 continue;
13469 }
13470
13471 LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
<< Cost << ". (HorRdx)\n"; } } while (false)
13472 << Cost << ". (HorRdx)\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
<< Cost << ". (HorRdx)\n"; } } while (false)
;
13473 V.getORE()->emit([&]() {
13474 return OptimizationRemark(
13475 SV_NAME"slp-vectorizer", "VectorizedHorizontalReduction",
13476 ReducedValsToOps.find(VL[0])->second.front())
13477 << "Vectorized horizontal reduction with cost "
13478 << ore::NV("Cost", Cost) << " and with tree size "
13479 << ore::NV("TreeSize", V.getTreeSize());
13480 });
13481
13482 Builder.setFastMathFlags(RdxFMF);
13483
13484 // Emit a reduction. If the root is a select (min/max idiom), the insert
13485 // point is the compare condition of that select.
13486 Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
13487 Instruction *InsertPt = RdxRootInst;
13488 if (IsCmpSelMinMax)
13489 InsertPt = GetCmpForMinMaxReduction(RdxRootInst);
13490
13491 // Vectorize a tree.
13492 Value *VectorizedRoot = V.vectorizeTree(LocalExternallyUsedValues,
13493 ReplacedExternals, InsertPt);
13494
13495 Builder.SetInsertPoint(InsertPt);
13496
13497 // To prevent poison from leaking across what used to be sequential,
13498 // safe, scalar boolean logic operations, the reduction operand must be
13499 // frozen.
13500 if (isBoolLogicOp(RdxRootInst))
13501 VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
13502
13503 // Emit code to correctly handle reused reduced values, if required.
13504 if (OptReusedScalars && !SameScaleFactor) {
13505 VectorizedRoot =
13506 emitReusedOps(VectorizedRoot, Builder, V.getRootNodeScalars(),
13507 SameValuesCounter, TrackedToOrig);
13508 }
13509
13510 Value *ReducedSubTree =
13511 emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
13512
13513 // Improved analysis for add/fadd/xor reductions with same scale factor
13514 // for all operands of reductions. We can emit scalar ops for them
13515 // instead.
13516 if (OptReusedScalars && SameScaleFactor)
13517 ReducedSubTree = emitScaleForReusedOps(
13518 ReducedSubTree, Builder, SameValuesCounter.front().second);
13519
13520 VectorizedTree = GetNewVectorizedTree(VectorizedTree, ReducedSubTree);
13521 // Count vectorized reduced values to exclude them from final reduction.
13522 for (Value *RdxVal : VL) {
13523 Value *OrigV = TrackedToOrig.find(RdxVal)->second;
13524 if (IsSupportedHorRdxIdentityOp) {
13525 VectorizedVals.try_emplace(OrigV, SameValuesCounter[RdxVal]);
13526 continue;
13527 }
13528 ++VectorizedVals.try_emplace(OrigV, 0).first->getSecond();
13529 if (!V.isVectorized(RdxVal))
13530 RequiredExtract.insert(RdxVal);
13531 }
13532 Pos += ReduxWidth;
13533 Start = Pos;
13534 ReduxWidth = llvm::bit_floor(NumReducedVals - Pos);
13535 AnyVectorized = true;
13536 }
13537 if (OptReusedScalars && !AnyVectorized) {
13538 for (const std::pair<Value *, unsigned> &P : SameValuesCounter) {
13539 Value *RedVal = emitScaleForReusedOps(P.first, Builder, P.second);
13540 VectorizedTree = GetNewVectorizedTree(VectorizedTree, RedVal);
13541 Value *OrigV = TrackedToOrig.find(P.first)->second;
13542 VectorizedVals.try_emplace(OrigV, P.second);
13543 }
13544 continue;
13545 }
13546 }
13547 if (VectorizedTree) {
13548 // Reorder operands of bool logical op in the natural order to avoid
13549 // possible problem with poison propagation. If not possible to reorder
13550 // (both operands are originally RHS), emit an extra freeze instruction
13551 // for the LHS operand.
13552 //I.e., if we have original code like this:
13553 // RedOp1 = select i1 ?, i1 LHS, i1 false
13554 // RedOp2 = select i1 RHS, i1 ?, i1 false
13555
13556 // Then, we swap LHS/RHS to create a new op that matches the poison
13557 // semantics of the original code.
13558
13559 // If we have original code like this and both values could be poison:
13560 // RedOp1 = select i1 ?, i1 LHS, i1 false
13561 // RedOp2 = select i1 ?, i1 RHS, i1 false
13562
13563 // Then, we must freeze LHS in the new op.
13564 auto &&FixBoolLogicalOps =
13565 [&Builder, VectorizedTree](Value *&LHS, Value *&RHS,
13566 Instruction *RedOp1, Instruction *RedOp2) {
13567 if (!isBoolLogicOp(RedOp1))
13568 return;
13569 if (LHS == VectorizedTree || getRdxOperand(RedOp1, 0) == LHS ||
13570 isGuaranteedNotToBePoison(LHS))
13571 return;
13572 if (!isBoolLogicOp(RedOp2))
13573 return;
13574 if (RHS == VectorizedTree || getRdxOperand(RedOp2, 0) == RHS ||
13575 isGuaranteedNotToBePoison(RHS)) {
13576 std::swap(LHS, RHS);
13577 return;
13578 }
13579 LHS = Builder.CreateFreeze(LHS);
13580 };
13581 // Finish the reduction.
13582 // Need to add extra arguments and not vectorized possible reduction
13583 // values.
13584 // Try to avoid dependencies between the scalar remainders after
13585 // reductions.
13586 auto &&FinalGen =
13587 [this, &Builder, &TrackedVals, &FixBoolLogicalOps](
13588 ArrayRef<std::pair<Instruction *, Value *>> InstVals) {
13589 unsigned Sz = InstVals.size();
13590 SmallVector<std::pair<Instruction *, Value *>> ExtraReds(Sz / 2 +
13591 Sz % 2);
13592 for (unsigned I = 0, E = (Sz / 2) * 2; I < E; I += 2) {
13593 Instruction *RedOp = InstVals[I + 1].first;
13594 Builder.SetCurrentDebugLocation(RedOp->getDebugLoc());
13595 Value *RdxVal1 = InstVals[I].second;
13596 Value *StableRdxVal1 = RdxVal1;
13597 auto It1 = TrackedVals.find(RdxVal1);
13598 if (It1 != TrackedVals.end())
13599 StableRdxVal1 = It1->second;
13600 Value *RdxVal2 = InstVals[I + 1].second;
13601 Value *StableRdxVal2 = RdxVal2;
13602 auto It2 = TrackedVals.find(RdxVal2);
13603 if (It2 != TrackedVals.end())
13604 StableRdxVal2 = It2->second;
13605 // To prevent poison from leaking across what used to be
13606 // sequential, safe, scalar boolean logic operations, the
13607 // reduction operand must be frozen.
13608 FixBoolLogicalOps(StableRdxVal1, StableRdxVal2, InstVals[I].first,
13609 RedOp);
13610 Value *ExtraRed = createOp(Builder, RdxKind, StableRdxVal1,
13611 StableRdxVal2, "op.rdx", ReductionOps);
13612 ExtraReds[I / 2] = std::make_pair(InstVals[I].first, ExtraRed);
13613 }
13614 if (Sz % 2 == 1)
13615 ExtraReds[Sz / 2] = InstVals.back();
13616 return ExtraReds;
13617 };
13618 SmallVector<std::pair<Instruction *, Value *>> ExtraReductions;
13619 ExtraReductions.emplace_back(cast<Instruction>(ReductionRoot),
13620 VectorizedTree);
13621 SmallPtrSet<Value *, 8> Visited;
13622 for (ArrayRef<Value *> Candidates : ReducedVals) {
13623 for (Value *RdxVal : Candidates) {
13624 if (!Visited.insert(RdxVal).second)
13625 continue;
13626 unsigned NumOps = VectorizedVals.lookup(RdxVal);
13627 for (Instruction *RedOp :
13628 ArrayRef(ReducedValsToOps.find(RdxVal)->second)
13629 .drop_back(NumOps))
13630 ExtraReductions.emplace_back(RedOp, RdxVal);
13631 }
13632 }
13633 for (auto &Pair : ExternallyUsedValues) {
13634 // Add each externally used value to the final reduction.
13635 for (auto *I : Pair.second)
13636 ExtraReductions.emplace_back(I, Pair.first);
13637 }
13638 // Iterate through all not-vectorized reduction values/extra arguments.
13639 while (ExtraReductions.size() > 1) {
13640 VectorizedTree = ExtraReductions.front().second;
13641 SmallVector<std::pair<Instruction *, Value *>> NewReds =
13642 FinalGen(ExtraReductions);
13643 ExtraReductions.swap(NewReds);
13644 }
13645 VectorizedTree = ExtraReductions.front().second;
13646
13647 ReductionRoot->replaceAllUsesWith(VectorizedTree);
13648
13649 // The original scalar reduction is expected to have no remaining
13650 // uses outside the reduction tree itself. Assert that we got this
13651 // correct, replace internal uses with undef, and mark for eventual
13652 // deletion.
13653#ifndef NDEBUG
13654 SmallSet<Value *, 4> IgnoreSet;
13655 for (ArrayRef<Value *> RdxOps : ReductionOps)
13656 IgnoreSet.insert(RdxOps.begin(), RdxOps.end());
13657#endif
13658 for (ArrayRef<Value *> RdxOps : ReductionOps) {
13659 for (Value *Ignore : RdxOps) {
13660 if (!Ignore)
13661 continue;
13662#ifndef NDEBUG
13663 for (auto *U : Ignore->users()) {
13664 assert(IgnoreSet.count(U) &&(static_cast <bool> (IgnoreSet.count(U) && "All users must be either in the reduction ops list."
) ? void (0) : __assert_fail ("IgnoreSet.count(U) && \"All users must be either in the reduction ops list.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 13665, __extension__
__PRETTY_FUNCTION__))
13665 "All users must be either in the reduction ops list.")(static_cast <bool> (IgnoreSet.count(U) && "All users must be either in the reduction ops list."
) ? void (0) : __assert_fail ("IgnoreSet.count(U) && \"All users must be either in the reduction ops list.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 13665, __extension__
__PRETTY_FUNCTION__))
;
13666 }
13667#endif
13668 if (!Ignore->use_empty()) {
13669 Value *Undef = UndefValue::get(Ignore->getType());
13670 Ignore->replaceAllUsesWith(Undef);
13671 }
13672 V.eraseInstruction(cast<Instruction>(Ignore));
13673 }
13674 }
13675 } else if (!CheckForReusedReductionOps) {
13676 for (ReductionOpsType &RdxOps : ReductionOps)
13677 for (Value *RdxOp : RdxOps)
13678 V.analyzedReductionRoot(cast<Instruction>(RdxOp));
13679 }
13680 return VectorizedTree;
13681 }
13682
13683private:
13684 /// Calculate the cost of a reduction.
13685 InstructionCost getReductionCost(TargetTransformInfo *TTI,
13686 ArrayRef<Value *> ReducedVals,
13687 bool IsCmpSelMinMax, unsigned ReduxWidth,
13688 FastMathFlags FMF) {
13689 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
13690 Value *FirstReducedVal = ReducedVals.front();
13691 Type *ScalarTy = FirstReducedVal->getType();
13692 FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
13693 InstructionCost VectorCost = 0, ScalarCost;
13694 // If all of the reduced values are constant, the vector cost is 0, since
13695 // the reduction value can be calculated at the compile time.
13696 bool AllConsts = allConstant(ReducedVals);
13697 auto EvaluateScalarCost = [&](function_ref<InstructionCost()> GenCostFn) {
13698 InstructionCost Cost = 0;
13699 // Scalar cost is repeated for N-1 elements.
13700 int Cnt = ReducedVals.size();
13701 for (Value *RdxVal : ReducedVals) {
13702 if (Cnt == 1)
13703 break;
13704 --Cnt;
13705 if (RdxVal->hasNUsesOrMore(IsCmpSelMinMax ? 3 : 2)) {
13706 Cost += GenCostFn();
13707 continue;
13708 }
13709 InstructionCost ScalarCost = 0;
13710 for (User *U : RdxVal->users()) {
13711 auto *RdxOp = cast<Instruction>(U);
13712 if (hasRequiredNumberOfUses(IsCmpSelMinMax, RdxOp)) {
13713 ScalarCost += TTI->getInstructionCost(RdxOp, CostKind);
13714 continue;
13715 }
13716 ScalarCost = InstructionCost::getInvalid();
13717 break;
13718 }
13719 if (ScalarCost.isValid())
13720 Cost += ScalarCost;
13721 else
13722 Cost += GenCostFn();
13723 }
13724 return Cost;
13725 };
13726 switch (RdxKind) {
13727 case RecurKind::Add:
13728 case RecurKind::Mul:
13729 case RecurKind::Or:
13730 case RecurKind::And:
13731 case RecurKind::Xor:
13732 case RecurKind::FAdd:
13733 case RecurKind::FMul: {
13734 unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
13735 if (!AllConsts)
13736 VectorCost =
13737 TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
13738 ScalarCost = EvaluateScalarCost([&]() {
13739 return TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
13740 });
13741 break;
13742 }
13743 case RecurKind::FMax:
13744 case RecurKind::FMin:
13745 case RecurKind::SMax:
13746 case RecurKind::SMin:
13747 case RecurKind::UMax:
13748 case RecurKind::UMin: {
13749 if (!AllConsts) {
13750 auto *VecCondTy =
13751 cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
13752 bool IsUnsigned =
13753 RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
13754 VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
13755 IsUnsigned, FMF, CostKind);
13756 }
13757 Intrinsic::ID Id = getMinMaxReductionIntrinsicOp(RdxKind);
13758 ScalarCost = EvaluateScalarCost([&]() {
13759 IntrinsicCostAttributes ICA(Id, ScalarTy, {ScalarTy, ScalarTy}, FMF);
13760 return TTI->getIntrinsicInstrCost(ICA, CostKind);
13761 });
13762 break;
13763 }
13764 default:
13765 llvm_unreachable("Expected arithmetic or min/max reduction operation")::llvm::llvm_unreachable_internal("Expected arithmetic or min/max reduction operation"
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 13765)
;
13766 }
13767
13768 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCostdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << VectorCost
- ScalarCost << " for reduction that starts with " <<
*FirstReducedVal << " (It is a splitting reduction)\n"
; } } while (false)
13769 << " for reduction that starts with " << *FirstReducedValdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << VectorCost
- ScalarCost << " for reduction that starts with " <<
*FirstReducedVal << " (It is a splitting reduction)\n"
; } } while (false)
13770 << " (It is a splitting reduction)\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Adding cost " << VectorCost
- ScalarCost << " for reduction that starts with " <<
*FirstReducedVal << " (It is a splitting reduction)\n"
; } } while (false)
;
13771 return VectorCost - ScalarCost;
13772 }
13773
13774 /// Emit a horizontal reduction of the vectorized value.
13775 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
13776 unsigned ReduxWidth, const TargetTransformInfo *TTI) {
13777 assert(VectorizedValue && "Need to have a vectorized tree node")(static_cast <bool> (VectorizedValue && "Need to have a vectorized tree node"
) ? void (0) : __assert_fail ("VectorizedValue && \"Need to have a vectorized tree node\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 13777, __extension__
__PRETTY_FUNCTION__))
;
13778 assert(isPowerOf2_32(ReduxWidth) &&(static_cast <bool> (isPowerOf2_32(ReduxWidth) &&
"We only handle power-of-two reductions for now") ? void (0)
: __assert_fail ("isPowerOf2_32(ReduxWidth) && \"We only handle power-of-two reductions for now\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 13779, __extension__
__PRETTY_FUNCTION__))
13779 "We only handle power-of-two reductions for now")(static_cast <bool> (isPowerOf2_32(ReduxWidth) &&
"We only handle power-of-two reductions for now") ? void (0)
: __assert_fail ("isPowerOf2_32(ReduxWidth) && \"We only handle power-of-two reductions for now\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 13779, __extension__
__PRETTY_FUNCTION__))
;
13780 assert(RdxKind != RecurKind::FMulAdd &&(static_cast <bool> (RdxKind != RecurKind::FMulAdd &&
"A call to the llvm.fmuladd intrinsic is not handled yet") ?
void (0) : __assert_fail ("RdxKind != RecurKind::FMulAdd && \"A call to the llvm.fmuladd intrinsic is not handled yet\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 13781, __extension__
__PRETTY_FUNCTION__))
13781 "A call to the llvm.fmuladd intrinsic is not handled yet")(static_cast <bool> (RdxKind != RecurKind::FMulAdd &&
"A call to the llvm.fmuladd intrinsic is not handled yet") ?
void (0) : __assert_fail ("RdxKind != RecurKind::FMulAdd && \"A call to the llvm.fmuladd intrinsic is not handled yet\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 13781, __extension__
__PRETTY_FUNCTION__))
;
13782
13783 ++NumVectorInstructions;
13784 return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
13785 }
13786
13787 /// Emits optimized code for unique scalar value reused \p Cnt times.
13788 Value *emitScaleForReusedOps(Value *VectorizedValue, IRBuilderBase &Builder,
13789 unsigned Cnt) {
13790 assert(IsSupportedHorRdxIdentityOp &&(static_cast <bool> (IsSupportedHorRdxIdentityOp &&
"The optimization of matched scalar identity horizontal reductions "
"must be supported.") ? void (0) : __assert_fail ("IsSupportedHorRdxIdentityOp && \"The optimization of matched scalar identity horizontal reductions \" \"must be supported.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 13792, __extension__
__PRETTY_FUNCTION__))
13791 "The optimization of matched scalar identity horizontal reductions "(static_cast <bool> (IsSupportedHorRdxIdentityOp &&
"The optimization of matched scalar identity horizontal reductions "
"must be supported.") ? void (0) : __assert_fail ("IsSupportedHorRdxIdentityOp && \"The optimization of matched scalar identity horizontal reductions \" \"must be supported.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 13792, __extension__
__PRETTY_FUNCTION__))
13792 "must be supported.")(static_cast <bool> (IsSupportedHorRdxIdentityOp &&
"The optimization of matched scalar identity horizontal reductions "
"must be supported.") ? void (0) : __assert_fail ("IsSupportedHorRdxIdentityOp && \"The optimization of matched scalar identity horizontal reductions \" \"must be supported.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 13792, __extension__
__PRETTY_FUNCTION__))
;
13793 switch (RdxKind) {
13794 case RecurKind::Add: {
13795 // res = mul vv, n
13796 Value *Scale = ConstantInt::get(VectorizedValue->getType(), Cnt);
13797 LLVM_DEBUG(dbgs() << "SLP: Add (to-mul) " << Cnt << "of "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Add (to-mul) " << Cnt <<
"of " << VectorizedValue << ". (HorRdx)\n"; } } while
(false)
13798 << VectorizedValue << ". (HorRdx)\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Add (to-mul) " << Cnt <<
"of " << VectorizedValue << ". (HorRdx)\n"; } } while
(false)
;
13799 return Builder.CreateMul(VectorizedValue, Scale);
13800 }
13801 case RecurKind::Xor: {
13802 // res = n % 2 ? 0 : vv
13803 LLVM_DEBUG(dbgs() << "SLP: Xor " << Cnt << "of " << VectorizedValuedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Xor " << Cnt << "of "
<< VectorizedValue << ". (HorRdx)\n"; } } while (
false)
13804 << ". (HorRdx)\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Xor " << Cnt << "of "
<< VectorizedValue << ". (HorRdx)\n"; } } while (
false)
;
13805 if (Cnt % 2 == 0)
13806 return Constant::getNullValue(VectorizedValue->getType());
13807 return VectorizedValue;
13808 }
13809 case RecurKind::FAdd: {
13810 // res = fmul v, n
13811 Value *Scale = ConstantFP::get(VectorizedValue->getType(), Cnt);
13812 LLVM_DEBUG(dbgs() << "SLP: FAdd (to-fmul) " << Cnt << "of "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: FAdd (to-fmul) " << Cnt
<< "of " << VectorizedValue << ". (HorRdx)\n"
; } } while (false)
13813 << VectorizedValue << ". (HorRdx)\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: FAdd (to-fmul) " << Cnt
<< "of " << VectorizedValue << ". (HorRdx)\n"
; } } while (false)
;
13814 return Builder.CreateFMul(VectorizedValue, Scale);
13815 }
13816 case RecurKind::And:
13817 case RecurKind::Or:
13818 case RecurKind::SMax:
13819 case RecurKind::SMin:
13820 case RecurKind::UMax:
13821 case RecurKind::UMin:
13822 case RecurKind::FMax:
13823 case RecurKind::FMin:
13824 // res = vv
13825 return VectorizedValue;
13826 case RecurKind::Mul:
13827 case RecurKind::FMul:
13828 case RecurKind::FMulAdd:
13829 case RecurKind::SelectICmp:
13830 case RecurKind::SelectFCmp:
13831 case RecurKind::None:
13832 llvm_unreachable("Unexpected reduction kind for repeated scalar.")::llvm::llvm_unreachable_internal("Unexpected reduction kind for repeated scalar."
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 13832)
;
13833 }
13834 return nullptr;
13835 }
13836
13837 /// Emits actual operation for the scalar identity values, found during
13838 /// horizontal reduction analysis.
13839 Value *emitReusedOps(Value *VectorizedValue, IRBuilderBase &Builder,
13840 ArrayRef<Value *> VL,
13841 const MapVector<Value *, unsigned> &SameValuesCounter,
13842 const DenseMap<Value *, Value *> &TrackedToOrig) {
13843 assert(IsSupportedHorRdxIdentityOp &&(static_cast <bool> (IsSupportedHorRdxIdentityOp &&
"The optimization of matched scalar identity horizontal reductions "
"must be supported.") ? void (0) : __assert_fail ("IsSupportedHorRdxIdentityOp && \"The optimization of matched scalar identity horizontal reductions \" \"must be supported.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 13845, __extension__
__PRETTY_FUNCTION__))
13844 "The optimization of matched scalar identity horizontal reductions "(static_cast <bool> (IsSupportedHorRdxIdentityOp &&
"The optimization of matched scalar identity horizontal reductions "
"must be supported.") ? void (0) : __assert_fail ("IsSupportedHorRdxIdentityOp && \"The optimization of matched scalar identity horizontal reductions \" \"must be supported.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 13845, __extension__
__PRETTY_FUNCTION__))
13845 "must be supported.")(static_cast <bool> (IsSupportedHorRdxIdentityOp &&
"The optimization of matched scalar identity horizontal reductions "
"must be supported.") ? void (0) : __assert_fail ("IsSupportedHorRdxIdentityOp && \"The optimization of matched scalar identity horizontal reductions \" \"must be supported.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 13845, __extension__
__PRETTY_FUNCTION__))
;
13846 switch (RdxKind) {
13847 case RecurKind::Add: {
13848 // root = mul prev_root, <1, 1, n, 1>
13849 SmallVector<Constant *> Vals;
13850 for (Value *V : VL) {
13851 unsigned Cnt = SameValuesCounter.lookup(TrackedToOrig.find(V)->second);
13852 Vals.push_back(ConstantInt::get(V->getType(), Cnt, /*IsSigned=*/false));
13853 }
13854 auto *Scale = ConstantVector::get(Vals);
13855 LLVM_DEBUG(dbgs() << "SLP: Add (to-mul) " << Scale << "of "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Add (to-mul) " << Scale
<< "of " << VectorizedValue << ". (HorRdx)\n"
; } } while (false)
13856 << VectorizedValue << ". (HorRdx)\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Add (to-mul) " << Scale
<< "of " << VectorizedValue << ". (HorRdx)\n"
; } } while (false)
;
13857 return Builder.CreateMul(VectorizedValue, Scale);
13858 }
13859 case RecurKind::And:
13860 case RecurKind::Or:
13861 // No need for multiple or/and(s).
13862 LLVM_DEBUG(dbgs() << "SLP: And/or of same " << VectorizedValuedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: And/or of same " << VectorizedValue
<< ". (HorRdx)\n"; } } while (false)
13863 << ". (HorRdx)\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: And/or of same " << VectorizedValue
<< ". (HorRdx)\n"; } } while (false)
;
13864 return VectorizedValue;
13865 case RecurKind::SMax:
13866 case RecurKind::SMin:
13867 case RecurKind::UMax:
13868 case RecurKind::UMin:
13869 case RecurKind::FMax:
13870 case RecurKind::FMin:
13871 // No need for multiple min/max(s) of the same value.
13872 LLVM_DEBUG(dbgs() << "SLP: Max/min of same " << VectorizedValuedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Max/min of same " << VectorizedValue
<< ". (HorRdx)\n"; } } while (false)
13873 << ". (HorRdx)\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Max/min of same " << VectorizedValue
<< ". (HorRdx)\n"; } } while (false)
;
13874 return VectorizedValue;
13875 case RecurKind::Xor: {
13876 // Replace values with even number of repeats with 0, since
13877 // x xor x = 0.
13878 // root = shuffle prev_root, zeroinitalizer, <0, 1, 2, vf, 4, vf, 5, 6,
13879 // 7>, if elements 4th and 6th elements have even number of repeats.
13880 SmallVector<int> Mask(
13881 cast<FixedVectorType>(VectorizedValue->getType())->getNumElements(),
13882 PoisonMaskElem);
13883 std::iota(Mask.begin(), Mask.end(), 0);
13884 bool NeedShuffle = false;
13885 for (unsigned I = 0, VF = VL.size(); I < VF; ++I) {
13886 Value *V = VL[I];
13887 unsigned Cnt = SameValuesCounter.lookup(TrackedToOrig.find(V)->second);
13888 if (Cnt % 2 == 0) {
13889 Mask[I] = VF;
13890 NeedShuffle = true;
13891 }
13892 }
13893 LLVM_DEBUG(dbgs() << "SLP: Xor <"; for (int Ido { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Xor <"; for (int I : Mask
) dbgs() << I << " "; dbgs() << "> of " <<
VectorizedValue << ". (HorRdx)\n"; } } while (false)
13894 : Mask) dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Xor <"; for (int I : Mask
) dbgs() << I << " "; dbgs() << "> of " <<
VectorizedValue << ". (HorRdx)\n"; } } while (false)
13895 << I << " ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Xor <"; for (int I : Mask
) dbgs() << I << " "; dbgs() << "> of " <<
VectorizedValue << ". (HorRdx)\n"; } } while (false)
13896 dbgs() << "> of " << VectorizedValue << ". (HorRdx)\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Xor <"; for (int I : Mask
) dbgs() << I << " "; dbgs() << "> of " <<
VectorizedValue << ". (HorRdx)\n"; } } while (false)
;
13897 if (NeedShuffle)
13898 VectorizedValue = Builder.CreateShuffleVector(
13899 VectorizedValue,
13900 ConstantVector::getNullValue(VectorizedValue->getType()), Mask);
13901 return VectorizedValue;
13902 }
13903 case RecurKind::FAdd: {
13904 // root = fmul prev_root, <1.0, 1.0, n.0, 1.0>
13905 SmallVector<Constant *> Vals;
13906 for (Value *V : VL) {
13907 unsigned Cnt = SameValuesCounter.lookup(TrackedToOrig.find(V)->second);
13908 Vals.push_back(ConstantFP::get(V->getType(), Cnt));
13909 }
13910 auto *Scale = ConstantVector::get(Vals);
13911 return Builder.CreateFMul(VectorizedValue, Scale);
13912 }
13913 case RecurKind::Mul:
13914 case RecurKind::FMul:
13915 case RecurKind::FMulAdd:
13916 case RecurKind::SelectICmp:
13917 case RecurKind::SelectFCmp:
13918 case RecurKind::None:
13919 llvm_unreachable("Unexpected reduction kind for reused scalars.")::llvm::llvm_unreachable_internal("Unexpected reduction kind for reused scalars."
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 13919)
;
13920 }
13921 return nullptr;
13922 }
13923};
13924} // end anonymous namespace
13925
13926static std::optional<unsigned> getAggregateSize(Instruction *InsertInst) {
13927 if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
13928 return cast<FixedVectorType>(IE->getType())->getNumElements();
13929
13930 unsigned AggregateSize = 1;
13931 auto *IV = cast<InsertValueInst>(InsertInst);
13932 Type *CurrentType = IV->getType();
13933 do {
13934 if (auto *ST = dyn_cast<StructType>(CurrentType)) {
13935 for (auto *Elt : ST->elements())
13936 if (Elt != ST->getElementType(0)) // check homogeneity
13937 return std::nullopt;
13938 AggregateSize *= ST->getNumElements();
13939 CurrentType = ST->getElementType(0);
13940 } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
13941 AggregateSize *= AT->getNumElements();
13942 CurrentType = AT->getElementType();
13943 } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
13944 AggregateSize *= VT->getNumElements();
13945 return AggregateSize;
13946 } else if (CurrentType->isSingleValueType()) {
13947 return AggregateSize;
13948 } else {
13949 return std::nullopt;
13950 }
13951 } while (true);
13952}
13953
13954static void findBuildAggregate_rec(Instruction *LastInsertInst,
13955 TargetTransformInfo *TTI,
13956 SmallVectorImpl<Value *> &BuildVectorOpds,
13957 SmallVectorImpl<Value *> &InsertElts,
13958 unsigned OperandOffset) {
13959 do {
13960 Value *InsertedOperand = LastInsertInst->getOperand(1);
13961 std::optional<unsigned> OperandIndex =
13962 getInsertIndex(LastInsertInst, OperandOffset);
13963 if (!OperandIndex)
13964 return;
13965 if (isa<InsertElementInst, InsertValueInst>(InsertedOperand)) {
13966 findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
13967 BuildVectorOpds, InsertElts, *OperandIndex);
13968
13969 } else {
13970 BuildVectorOpds[*OperandIndex] = InsertedOperand;
13971 InsertElts[*OperandIndex] = LastInsertInst;
13972 }
13973 LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
13974 } while (LastInsertInst != nullptr &&
13975 isa<InsertValueInst, InsertElementInst>(LastInsertInst) &&
13976 LastInsertInst->hasOneUse());
13977}
13978
13979/// Recognize construction of vectors like
13980/// %ra = insertelement <4 x float> poison, float %s0, i32 0
13981/// %rb = insertelement <4 x float> %ra, float %s1, i32 1
13982/// %rc = insertelement <4 x float> %rb, float %s2, i32 2
13983/// %rd = insertelement <4 x float> %rc, float %s3, i32 3
13984/// starting from the last insertelement or insertvalue instruction.
13985///
13986/// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
13987/// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
13988/// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
13989///
13990/// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
13991///
13992/// \return true if it matches.
13993static bool findBuildAggregate(Instruction *LastInsertInst,
13994 TargetTransformInfo *TTI,
13995 SmallVectorImpl<Value *> &BuildVectorOpds,
13996 SmallVectorImpl<Value *> &InsertElts) {
13997
13998 assert((isa<InsertElementInst>(LastInsertInst) ||(static_cast <bool> ((isa<InsertElementInst>(LastInsertInst
) || isa<InsertValueInst>(LastInsertInst)) && "Expected insertelement or insertvalue instruction!"
) ? void (0) : __assert_fail ("(isa<InsertElementInst>(LastInsertInst) || isa<InsertValueInst>(LastInsertInst)) && \"Expected insertelement or insertvalue instruction!\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14000, __extension__
__PRETTY_FUNCTION__))
13999 isa<InsertValueInst>(LastInsertInst)) &&(static_cast <bool> ((isa<InsertElementInst>(LastInsertInst
) || isa<InsertValueInst>(LastInsertInst)) && "Expected insertelement or insertvalue instruction!"
) ? void (0) : __assert_fail ("(isa<InsertElementInst>(LastInsertInst) || isa<InsertValueInst>(LastInsertInst)) && \"Expected insertelement or insertvalue instruction!\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14000, __extension__
__PRETTY_FUNCTION__))
14000 "Expected insertelement or insertvalue instruction!")(static_cast <bool> ((isa<InsertElementInst>(LastInsertInst
) || isa<InsertValueInst>(LastInsertInst)) && "Expected insertelement or insertvalue instruction!"
) ? void (0) : __assert_fail ("(isa<InsertElementInst>(LastInsertInst) || isa<InsertValueInst>(LastInsertInst)) && \"Expected insertelement or insertvalue instruction!\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14000, __extension__
__PRETTY_FUNCTION__))
;
14001
14002 assert((BuildVectorOpds.empty() && InsertElts.empty()) &&(static_cast <bool> ((BuildVectorOpds.empty() &&
InsertElts.empty()) && "Expected empty result vectors!"
) ? void (0) : __assert_fail ("(BuildVectorOpds.empty() && InsertElts.empty()) && \"Expected empty result vectors!\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14003, __extension__
__PRETTY_FUNCTION__))
14003 "Expected empty result vectors!")(static_cast <bool> ((BuildVectorOpds.empty() &&
InsertElts.empty()) && "Expected empty result vectors!"
) ? void (0) : __assert_fail ("(BuildVectorOpds.empty() && InsertElts.empty()) && \"Expected empty result vectors!\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14003, __extension__
__PRETTY_FUNCTION__))
;
14004
14005 std::optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
14006 if (!AggregateSize)
14007 return false;
14008 BuildVectorOpds.resize(*AggregateSize);
14009 InsertElts.resize(*AggregateSize);
14010
14011 findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
14012 llvm::erase_value(BuildVectorOpds, nullptr);
14013 llvm::erase_value(InsertElts, nullptr);
14014 if (BuildVectorOpds.size() >= 2)
14015 return true;
14016
14017 return false;
14018}
14019
14020/// Try and get a reduction instruction from a phi node.
14021///
14022/// Given a phi node \p P in a block \p ParentBB, consider possible reductions
14023/// if they come from either \p ParentBB or a containing loop latch.
14024///
14025/// \returns A candidate reduction value if possible, or \code nullptr \endcode
14026/// if not possible.
14027static Instruction *getReductionInstr(const DominatorTree *DT, PHINode *P,
14028 BasicBlock *ParentBB, LoopInfo *LI) {
14029 // There are situations where the reduction value is not dominated by the
14030 // reduction phi. Vectorizing such cases has been reported to cause
14031 // miscompiles. See PR25787.
14032 auto DominatedReduxValue = [&](Value *R) {
14033 return isa<Instruction>(R) &&
14034 DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
14035 };
14036
14037 Instruction *Rdx = nullptr;
14038
14039 // Return the incoming value if it comes from the same BB as the phi node.
14040 if (P->getIncomingBlock(0) == ParentBB) {
14041 Rdx = dyn_cast<Instruction>(P->getIncomingValue(0));
14042 } else if (P->getIncomingBlock(1) == ParentBB) {
14043 Rdx = dyn_cast<Instruction>(P->getIncomingValue(1));
14044 }
14045
14046 if (Rdx && DominatedReduxValue(Rdx))
14047 return Rdx;
14048
14049 // Otherwise, check whether we have a loop latch to look at.
14050 Loop *BBL = LI->getLoopFor(ParentBB);
14051 if (!BBL)
14052 return nullptr;
14053 BasicBlock *BBLatch = BBL->getLoopLatch();
14054 if (!BBLatch)
14055 return nullptr;
14056
14057 // There is a loop latch, return the incoming value if it comes from
14058 // that. This reduction pattern occasionally turns up.
14059 if (P->getIncomingBlock(0) == BBLatch) {
14060 Rdx = dyn_cast<Instruction>(P->getIncomingValue(0));
14061 } else if (P->getIncomingBlock(1) == BBLatch) {
14062 Rdx = dyn_cast<Instruction>(P->getIncomingValue(1));
14063 }
14064
14065 if (Rdx && DominatedReduxValue(Rdx))
14066 return Rdx;
14067
14068 return nullptr;
14069}
14070
14071static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
14072 if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
14073 return true;
14074 if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
14075 return true;
14076 if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
14077 return true;
14078 if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
14079 return true;
14080 if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
14081 return true;
14082 if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
14083 return true;
14084 if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
14085 return true;
14086 return false;
14087}
14088
14089/// We could have an initial reduction that is not an add.
14090/// r *= v1 + v2 + v3 + v4
14091/// In such a case start looking for a tree rooted in the first '+'.
14092/// \Returns the new root if found, which may be nullptr if not an instruction.
14093static Instruction *tryGetSecondaryReductionRoot(PHINode *Phi,
14094 Instruction *Root) {
14095 assert((isa<BinaryOperator>(Root) || isa<SelectInst>(Root) ||(static_cast <bool> ((isa<BinaryOperator>(Root) ||
isa<SelectInst>(Root) || isa<IntrinsicInst>(Root
)) && "Expected binop, select, or intrinsic for reduction matching"
) ? void (0) : __assert_fail ("(isa<BinaryOperator>(Root) || isa<SelectInst>(Root) || isa<IntrinsicInst>(Root)) && \"Expected binop, select, or intrinsic for reduction matching\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14097, __extension__
__PRETTY_FUNCTION__))
14096 isa<IntrinsicInst>(Root)) &&(static_cast <bool> ((isa<BinaryOperator>(Root) ||
isa<SelectInst>(Root) || isa<IntrinsicInst>(Root
)) && "Expected binop, select, or intrinsic for reduction matching"
) ? void (0) : __assert_fail ("(isa<BinaryOperator>(Root) || isa<SelectInst>(Root) || isa<IntrinsicInst>(Root)) && \"Expected binop, select, or intrinsic for reduction matching\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14097, __extension__
__PRETTY_FUNCTION__))
14097 "Expected binop, select, or intrinsic for reduction matching")(static_cast <bool> ((isa<BinaryOperator>(Root) ||
isa<SelectInst>(Root) || isa<IntrinsicInst>(Root
)) && "Expected binop, select, or intrinsic for reduction matching"
) ? void (0) : __assert_fail ("(isa<BinaryOperator>(Root) || isa<SelectInst>(Root) || isa<IntrinsicInst>(Root)) && \"Expected binop, select, or intrinsic for reduction matching\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14097, __extension__
__PRETTY_FUNCTION__))
;
14098 Value *LHS =
14099 Root->getOperand(HorizontalReduction::getFirstOperandIndex(Root));
14100 Value *RHS =
14101 Root->getOperand(HorizontalReduction::getFirstOperandIndex(Root) + 1);
14102 if (LHS == Phi)
14103 return dyn_cast<Instruction>(RHS);
14104 if (RHS == Phi)
14105 return dyn_cast<Instruction>(LHS);
14106 return nullptr;
14107}
14108
14109/// \p Returns the first operand of \p I that does not match \p Phi. If
14110/// operand is not an instruction it returns nullptr.
14111static Instruction *getNonPhiOperand(Instruction *I, PHINode *Phi) {
14112 Value *Op0 = nullptr;
14113 Value *Op1 = nullptr;
14114 if (!matchRdxBop(I, Op0, Op1))
14115 return nullptr;
14116 return dyn_cast<Instruction>(Op0 == Phi ? Op1 : Op0);
14117}
14118
14119/// \Returns true if \p I is a candidate instruction for reduction vectorization.
14120static bool isReductionCandidate(Instruction *I) {
14121 bool IsSelect = match(I, m_Select(m_Value(), m_Value(), m_Value()));
14122 Value *B0 = nullptr, *B1 = nullptr;
14123 bool IsBinop = matchRdxBop(I, B0, B1);
14124 return IsBinop || IsSelect;
14125}
14126
14127bool SLPVectorizerPass::vectorizeHorReduction(
14128 PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R, TargetTransformInfo *TTI,
14129 SmallVectorImpl<WeakTrackingVH> &PostponedInsts) {
14130 if (!ShouldVectorizeHor)
14131 return false;
14132 bool TryOperandsAsNewSeeds = P && isa<BinaryOperator>(Root);
14133
14134 if (Root->getParent() != BB || isa<PHINode>(Root))
14135 return false;
14136
14137 // If we can find a secondary reduction root, use that instead.
14138 auto SelectRoot = [&]() {
14139 if (TryOperandsAsNewSeeds && isReductionCandidate(Root) &&
14140 HorizontalReduction::getRdxKind(Root) != RecurKind::None)
14141 if (Instruction *NewRoot = tryGetSecondaryReductionRoot(P, Root))
14142 return NewRoot;
14143 return Root;
14144 };
14145
14146 // Start analysis starting from Root instruction. If horizontal reduction is
14147 // found, try to vectorize it. If it is not a horizontal reduction or
14148 // vectorization is not possible or not effective, and currently analyzed
14149 // instruction is a binary operation, try to vectorize the operands, using
14150 // pre-order DFS traversal order. If the operands were not vectorized, repeat
14151 // the same procedure considering each operand as a possible root of the
14152 // horizontal reduction.
14153 // Interrupt the process if the Root instruction itself was vectorized or all
14154 // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
14155 // If a horizintal reduction was not matched or vectorized we collect
14156 // instructions for possible later attempts for vectorization.
14157 std::queue<std::pair<Instruction *, unsigned>> Stack;
14158 Stack.emplace(SelectRoot(), 0);
14159 SmallPtrSet<Value *, 8> VisitedInstrs;
14160 bool Res = false;
14161 auto &&TryToReduce = [this, TTI, &R](Instruction *Inst) -> Value * {
14162 if (R.isAnalyzedReductionRoot(Inst))
14163 return nullptr;
14164 if (!isReductionCandidate(Inst))
14165 return nullptr;
14166 HorizontalReduction HorRdx;
14167 if (!HorRdx.matchAssociativeReduction(R, Inst, *SE, *DL, *TLI))
14168 return nullptr;
14169 return HorRdx.tryToReduce(R, TTI, *TLI);
14170 };
14171 auto TryAppendToPostponedInsts = [&](Instruction *FutureSeed) {
14172 if (TryOperandsAsNewSeeds && FutureSeed == Root) {
14173 FutureSeed = getNonPhiOperand(Root, P);
14174 if (!FutureSeed)
14175 return false;
14176 }
14177 // Do not collect CmpInst or InsertElementInst/InsertValueInst as their
14178 // analysis is done separately.
14179 if (!isa<CmpInst, InsertElementInst, InsertValueInst>(FutureSeed))
14180 PostponedInsts.push_back(FutureSeed);
14181 return true;
14182 };
14183
14184 while (!Stack.empty()) {
14185 Instruction *Inst;
14186 unsigned Level;
14187 std::tie(Inst, Level) = Stack.front();
14188 Stack.pop();
14189 // Do not try to analyze instruction that has already been vectorized.
14190 // This may happen when we vectorize instruction operands on a previous
14191 // iteration while stack was populated before that happened.
14192 if (R.isDeleted(Inst))
14193 continue;
14194 if (Value *VectorizedV = TryToReduce(Inst)) {
14195 Res = true;
14196 if (auto *I = dyn_cast<Instruction>(VectorizedV)) {
14197 // Try to find another reduction.
14198 Stack.emplace(I, Level);
14199 continue;
14200 }
14201 } else {
14202 // We could not vectorize `Inst` so try to use it as a future seed.
14203 if (!TryAppendToPostponedInsts(Inst)) {
14204 assert(Stack.empty() && "Expected empty stack")(static_cast <bool> (Stack.empty() && "Expected empty stack"
) ? void (0) : __assert_fail ("Stack.empty() && \"Expected empty stack\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14204, __extension__
__PRETTY_FUNCTION__))
;
14205 break;
14206 }
14207 }
14208
14209 // Try to vectorize operands.
14210 // Continue analysis for the instruction from the same basic block only to
14211 // save compile time.
14212 if (++Level < RecursionMaxDepth)
14213 for (auto *Op : Inst->operand_values())
14214 if (VisitedInstrs.insert(Op).second)
14215 if (auto *I = dyn_cast<Instruction>(Op))
14216 // Do not try to vectorize CmpInst operands, this is done
14217 // separately.
14218 if (!isa<PHINode, CmpInst, InsertElementInst, InsertValueInst>(I) &&
14219 !R.isDeleted(I) && I->getParent() == BB)
14220 Stack.emplace(I, Level);
14221 }
14222 return Res;
14223}
14224
14225bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Instruction *Root,
14226 BasicBlock *BB, BoUpSLP &R,
14227 TargetTransformInfo *TTI) {
14228 SmallVector<WeakTrackingVH> PostponedInsts;
14229 bool Res = vectorizeHorReduction(P, Root, BB, R, TTI, PostponedInsts);
14230 Res |= tryToVectorize(PostponedInsts, R);
14231 return Res;
14232}
14233
14234bool SLPVectorizerPass::tryToVectorize(ArrayRef<WeakTrackingVH> Insts,
14235 BoUpSLP &R) {
14236 bool Res = false;
14237 for (Value *V : Insts)
14238 if (auto *Inst = dyn_cast<Instruction>(V); Inst && !R.isDeleted(Inst))
14239 Res |= tryToVectorize(Inst, R);
14240 return Res;
14241}
14242
14243bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
14244 BasicBlock *BB, BoUpSLP &R) {
14245 const DataLayout &DL = BB->getModule()->getDataLayout();
14246 if (!R.canMapToVector(IVI->getType(), DL))
14247 return false;
14248
14249 SmallVector<Value *, 16> BuildVectorOpds;
14250 SmallVector<Value *, 16> BuildVectorInsts;
14251 if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
14252 return false;
14253
14254 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: array mappable to vector: " <<
*IVI << "\n"; } } while (false)
;
14255 // Aggregate value is unlikely to be processed in vector register.
14256 return tryToVectorizeList(BuildVectorOpds, R);
14257}
14258
14259bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
14260 BasicBlock *BB, BoUpSLP &R) {
14261 SmallVector<Value *, 16> BuildVectorInsts;
14262 SmallVector<Value *, 16> BuildVectorOpds;
14263 SmallVector<int> Mask;
14264 if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
14265 (llvm::all_of(
14266 BuildVectorOpds,
14267 [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
14268 isFixedVectorShuffle(BuildVectorOpds, Mask)))
14269 return false;
14270
14271 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: array mappable to vector: " <<
*IEI << "\n"; } } while (false)
;
14272 return tryToVectorizeList(BuildVectorInsts, R);
14273}
14274
14275template <typename T>
14276static bool tryToVectorizeSequence(
14277 SmallVectorImpl<T *> &Incoming, function_ref<bool(T *, T *)> Comparator,
14278 function_ref<bool(T *, T *)> AreCompatible,
14279 function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
14280 bool LimitForRegisterSize, BoUpSLP &R) {
14281 bool Changed = false;
14282 // Sort by type, parent, operands.
14283 stable_sort(Incoming, Comparator);
14284
14285 // Try to vectorize elements base on their type.
14286 SmallVector<T *> Candidates;
14287 for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
14288 // Look for the next elements with the same type, parent and operand
14289 // kinds.
14290 auto *SameTypeIt = IncIt;
14291 while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
14292 ++SameTypeIt;
14293
14294 // Try to vectorize them.
14295 unsigned NumElts = (SameTypeIt - IncIt);
14296 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Trying to vectorize starting at nodes ("
<< NumElts << ")\n"; } } while (false)
14297 << NumElts << ")\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Trying to vectorize starting at nodes ("
<< NumElts << ")\n"; } } while (false)
;
14298 // The vectorization is a 3-state attempt:
14299 // 1. Try to vectorize instructions with the same/alternate opcodes with the
14300 // size of maximal register at first.
14301 // 2. Try to vectorize remaining instructions with the same type, if
14302 // possible. This may result in the better vectorization results rather than
14303 // if we try just to vectorize instructions with the same/alternate opcodes.
14304 // 3. Final attempt to try to vectorize all instructions with the
14305 // same/alternate ops only, this may result in some extra final
14306 // vectorization.
14307 if (NumElts > 1 &&
14308 TryToVectorizeHelper(ArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
14309 // Success start over because instructions might have been changed.
14310 Changed = true;
14311 } else {
14312 /// \Returns the minimum number of elements that we will attempt to
14313 /// vectorize.
14314 auto GetMinNumElements = [&R](Value *V) {
14315 unsigned EltSize = R.getVectorElementSize(V);
14316 return std::max(2U, R.getMaxVecRegSize() / EltSize);
14317 };
14318 if (NumElts < GetMinNumElements(*IncIt) &&
14319 (Candidates.empty() ||
14320 Candidates.front()->getType() == (*IncIt)->getType())) {
14321 Candidates.append(IncIt, std::next(IncIt, NumElts));
14322 }
14323 }
14324 // Final attempt to vectorize instructions with the same types.
14325 if (Candidates.size() > 1 &&
14326 (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
14327 if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
14328 // Success start over because instructions might have been changed.
14329 Changed = true;
14330 } else if (LimitForRegisterSize) {
14331 // Try to vectorize using small vectors.
14332 for (auto *It = Candidates.begin(), *End = Candidates.end();
14333 It != End;) {
14334 auto *SameTypeIt = It;
14335 while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
14336 ++SameTypeIt;
14337 unsigned NumElts = (SameTypeIt - It);
14338 if (NumElts > 1 &&
14339 TryToVectorizeHelper(ArrayRef(It, NumElts),
14340 /*LimitForRegisterSize=*/false))
14341 Changed = true;
14342 It = SameTypeIt;
14343 }
14344 }
14345 Candidates.clear();
14346 }
14347
14348 // Start over at the next instruction of a different type (or the end).
14349 IncIt = SameTypeIt;
14350 }
14351 return Changed;
14352}
14353
14354/// Compare two cmp instructions. If IsCompatibility is true, function returns
14355/// true if 2 cmps have same/swapped predicates and mos compatible corresponding
14356/// operands. If IsCompatibility is false, function implements strict weak
14357/// ordering relation between two cmp instructions, returning true if the first
14358/// instruction is "less" than the second, i.e. its predicate is less than the
14359/// predicate of the second or the operands IDs are less than the operands IDs
14360/// of the second cmp instruction.
14361template <bool IsCompatibility>
14362static bool compareCmp(Value *V, Value *V2, TargetLibraryInfo &TLI,
14363 function_ref<bool(Instruction *)> IsDeleted) {
14364 auto *CI1 = cast<CmpInst>(V);
14365 auto *CI2 = cast<CmpInst>(V2);
14366 if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
14367 return false;
14368 if (CI1->getOperand(0)->getType()->getTypeID() <
14369 CI2->getOperand(0)->getType()->getTypeID())
14370 return !IsCompatibility;
14371 if (CI1->getOperand(0)->getType()->getTypeID() >
14372 CI2->getOperand(0)->getType()->getTypeID())
14373 return false;
14374 CmpInst::Predicate Pred1 = CI1->getPredicate();
14375 CmpInst::Predicate Pred2 = CI2->getPredicate();
14376 CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
14377 CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
14378 CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
14379 CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
14380 if (BasePred1 < BasePred2)
14381 return !IsCompatibility;
14382 if (BasePred1 > BasePred2)
14383 return false;
14384 // Compare operands.
14385 bool LEPreds = Pred1 <= Pred2;
14386 bool GEPreds = Pred1 >= Pred2;
14387 for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
14388 auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
14389 auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
14390 if (Op1->getValueID() < Op2->getValueID())
14391 return !IsCompatibility;
14392 if (Op1->getValueID() > Op2->getValueID())
14393 return false;
14394 if (auto *I1 = dyn_cast<Instruction>(Op1))
14395 if (auto *I2 = dyn_cast<Instruction>(Op2)) {
14396 if (I1->getParent() != I2->getParent())
14397 return false;
14398 InstructionsState S = getSameOpcode({I1, I2}, TLI);
14399 if (S.getOpcode())
14400 continue;
14401 return false;
14402 }
14403 }
14404 return IsCompatibility;
14405}
14406
14407bool SLPVectorizerPass::vectorizeCmpInsts(ArrayRef<CmpInst *> CmpInsts,
14408 BasicBlock *BB, BoUpSLP &R) {
14409 bool Changed = false;
14410 // Try to find reductions first.
14411 for (Instruction *I : CmpInsts) {
14412 if (R.isDeleted(I))
14413 continue;
14414 for (Value *Op : I->operands())
14415 if (auto *RootOp = dyn_cast<Instruction>(Op))
14416 Changed |= vectorizeRootInstruction(nullptr, RootOp, BB, R, TTI);
14417 }
14418 // Try to vectorize operands as vector bundles.
14419 for (Instruction *I : CmpInsts) {
14420 if (R.isDeleted(I))
14421 continue;
14422 Changed |= tryToVectorize(I, R);
14423 }
14424 // Try to vectorize list of compares.
14425 // Sort by type, compare predicate, etc.
14426 auto CompareSorter = [&](Value *V, Value *V2) {
14427 return compareCmp<false>(V, V2, *TLI,
14428 [&R](Instruction *I) { return R.isDeleted(I); });
14429 };
14430
14431 auto AreCompatibleCompares = [&](Value *V1, Value *V2) {
14432 if (V1 == V2)
14433 return true;
14434 return compareCmp<true>(V1, V2, *TLI,
14435 [&R](Instruction *I) { return R.isDeleted(I); });
14436 };
14437
14438 SmallVector<Value *> Vals(CmpInsts.begin(), CmpInsts.end());
14439 Changed |= tryToVectorizeSequence<Value>(
14440 Vals, CompareSorter, AreCompatibleCompares,
14441 [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
14442 // Exclude possible reductions from other blocks.
14443 bool ArePossiblyReducedInOtherBlock = any_of(Candidates, [](Value *V) {
14444 return any_of(V->users(), [V](User *U) {
14445 auto *Select = dyn_cast<SelectInst>(U);
14446 return Select &&
14447 Select->getParent() != cast<Instruction>(V)->getParent();
14448 });
14449 });
14450 if (ArePossiblyReducedInOtherBlock)
14451 return false;
14452 return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
14453 },
14454 /*LimitForRegisterSize=*/true, R);
14455 return Changed;
14456}
14457
14458bool SLPVectorizerPass::vectorizeSimpleInstructions(InstSetVector &Instructions,
14459 BasicBlock *BB, BoUpSLP &R,
14460 bool AtTerminator) {
14461 assert(all_of(Instructions,(static_cast <bool> (all_of(Instructions, [](auto *I) {
return isa<CmpInst, InsertElementInst, InsertValueInst>
(I); }) && "This function only accepts Cmp and Insert instructions"
) ? void (0) : __assert_fail ("all_of(Instructions, [](auto *I) { return isa<CmpInst, InsertElementInst, InsertValueInst>(I); }) && \"This function only accepts Cmp and Insert instructions\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14465, __extension__
__PRETTY_FUNCTION__))
14462 [](auto *I) {(static_cast <bool> (all_of(Instructions, [](auto *I) {
return isa<CmpInst, InsertElementInst, InsertValueInst>
(I); }) && "This function only accepts Cmp and Insert instructions"
) ? void (0) : __assert_fail ("all_of(Instructions, [](auto *I) { return isa<CmpInst, InsertElementInst, InsertValueInst>(I); }) && \"This function only accepts Cmp and Insert instructions\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14465, __extension__
__PRETTY_FUNCTION__))
14463 return isa<CmpInst, InsertElementInst, InsertValueInst>(I);(static_cast <bool> (all_of(Instructions, [](auto *I) {
return isa<CmpInst, InsertElementInst, InsertValueInst>
(I); }) && "This function only accepts Cmp and Insert instructions"
) ? void (0) : __assert_fail ("all_of(Instructions, [](auto *I) { return isa<CmpInst, InsertElementInst, InsertValueInst>(I); }) && \"This function only accepts Cmp and Insert instructions\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14465, __extension__
__PRETTY_FUNCTION__))
14464 }) &&(static_cast <bool> (all_of(Instructions, [](auto *I) {
return isa<CmpInst, InsertElementInst, InsertValueInst>
(I); }) && "This function only accepts Cmp and Insert instructions"
) ? void (0) : __assert_fail ("all_of(Instructions, [](auto *I) { return isa<CmpInst, InsertElementInst, InsertValueInst>(I); }) && \"This function only accepts Cmp and Insert instructions\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14465, __extension__
__PRETTY_FUNCTION__))
14465 "This function only accepts Cmp and Insert instructions")(static_cast <bool> (all_of(Instructions, [](auto *I) {
return isa<CmpInst, InsertElementInst, InsertValueInst>
(I); }) && "This function only accepts Cmp and Insert instructions"
) ? void (0) : __assert_fail ("all_of(Instructions, [](auto *I) { return isa<CmpInst, InsertElementInst, InsertValueInst>(I); }) && \"This function only accepts Cmp and Insert instructions\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14465, __extension__
__PRETTY_FUNCTION__))
;
14466 bool OpsChanged = false;
14467 SmallVector<CmpInst *, 4> PostponedCmps;
14468 SmallVector<WeakTrackingVH> PostponedInsts;
14469 // pass1 - try to vectorize reductions only
14470 for (auto *I : reverse(Instructions)) {
14471 if (R.isDeleted(I))
14472 continue;
14473 if (isa<CmpInst>(I)) {
14474 PostponedCmps.push_back(cast<CmpInst>(I));
14475 continue;
14476 }
14477 OpsChanged |= vectorizeHorReduction(nullptr, I, BB, R, TTI, PostponedInsts);
14478 }
14479 // pass2 - try to match and vectorize a buildvector sequence.
14480 for (auto *I : reverse(Instructions)) {
14481 if (R.isDeleted(I) || isa<CmpInst>(I))
14482 continue;
14483 if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I)) {
14484 OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
14485 } else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I)) {
14486 OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
14487 }
14488 }
14489 // Now try to vectorize postponed instructions.
14490 OpsChanged |= tryToVectorize(PostponedInsts, R);
14491
14492 if (AtTerminator) {
14493 OpsChanged |= vectorizeCmpInsts(PostponedCmps, BB, R);
14494 Instructions.clear();
14495 } else {
14496 Instructions.clear();
14497 // Insert in reverse order since the PostponedCmps vector was filled in
14498 // reverse order.
14499 Instructions.insert(PostponedCmps.rbegin(), PostponedCmps.rend());
14500 }
14501 return OpsChanged;
14502}
14503
14504bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
14505 bool Changed = false;
14506 SmallVector<Value *, 4> Incoming;
14507 SmallPtrSet<Value *, 16> VisitedInstrs;
14508 // Maps phi nodes to the non-phi nodes found in the use tree for each phi
14509 // node. Allows better to identify the chains that can be vectorized in the
14510 // better way.
14511 DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
14512 auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
14513 assert(isValidElementType(V1->getType()) &&(static_cast <bool> (isValidElementType(V1->getType(
)) && isValidElementType(V2->getType()) &&
"Expected vectorizable types only.") ? void (0) : __assert_fail
("isValidElementType(V1->getType()) && isValidElementType(V2->getType()) && \"Expected vectorizable types only.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14515, __extension__
__PRETTY_FUNCTION__))
14514 isValidElementType(V2->getType()) &&(static_cast <bool> (isValidElementType(V1->getType(
)) && isValidElementType(V2->getType()) &&
"Expected vectorizable types only.") ? void (0) : __assert_fail
("isValidElementType(V1->getType()) && isValidElementType(V2->getType()) && \"Expected vectorizable types only.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14515, __extension__
__PRETTY_FUNCTION__))
14515 "Expected vectorizable types only.")(static_cast <bool> (isValidElementType(V1->getType(
)) && isValidElementType(V2->getType()) &&
"Expected vectorizable types only.") ? void (0) : __assert_fail
("isValidElementType(V1->getType()) && isValidElementType(V2->getType()) && \"Expected vectorizable types only.\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14515, __extension__
__PRETTY_FUNCTION__))
;
14516 // It is fine to compare type IDs here, since we expect only vectorizable
14517 // types, like ints, floats and pointers, we don't care about other type.
14518 if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
14519 return true;
14520 if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
14521 return false;
14522 ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
14523 ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
14524 if (Opcodes1.size() < Opcodes2.size())
14525 return true;
14526 if (Opcodes1.size() > Opcodes2.size())
14527 return false;
14528 std::optional<bool> ConstOrder;
14529 for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
14530 // Undefs are compatible with any other value.
14531 if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
14532 if (!ConstOrder)
14533 ConstOrder =
14534 !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
14535 continue;
14536 }
14537 if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
14538 if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
14539 DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
14540 DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
14541 if (!NodeI1)
14542 return NodeI2 != nullptr;
14543 if (!NodeI2)
14544 return false;
14545 assert((NodeI1 == NodeI2) ==(static_cast <bool> ((NodeI1 == NodeI2) == (NodeI1->
getDFSNumIn() == NodeI2->getDFSNumIn()) && "Different nodes should have different DFS numbers"
) ? void (0) : __assert_fail ("(NodeI1 == NodeI2) == (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && \"Different nodes should have different DFS numbers\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14547, __extension__
__PRETTY_FUNCTION__))
14546 (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&(static_cast <bool> ((NodeI1 == NodeI2) == (NodeI1->
getDFSNumIn() == NodeI2->getDFSNumIn()) && "Different nodes should have different DFS numbers"
) ? void (0) : __assert_fail ("(NodeI1 == NodeI2) == (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && \"Different nodes should have different DFS numbers\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14547, __extension__
__PRETTY_FUNCTION__))
14547 "Different nodes should have different DFS numbers")(static_cast <bool> ((NodeI1 == NodeI2) == (NodeI1->
getDFSNumIn() == NodeI2->getDFSNumIn()) && "Different nodes should have different DFS numbers"
) ? void (0) : __assert_fail ("(NodeI1 == NodeI2) == (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && \"Different nodes should have different DFS numbers\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14547, __extension__
__PRETTY_FUNCTION__))
;
14548 if (NodeI1 != NodeI2)
14549 return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
14550 InstructionsState S = getSameOpcode({I1, I2}, *TLI);
14551 if (S.getOpcode())
14552 continue;
14553 return I1->getOpcode() < I2->getOpcode();
14554 }
14555 if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
14556 if (!ConstOrder)
14557 ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
14558 continue;
14559 }
14560 if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
14561 return true;
14562 if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
14563 return false;
14564 }
14565 return ConstOrder && *ConstOrder;
14566 };
14567 auto AreCompatiblePHIs = [&PHIToOpcodes, this](Value *V1, Value *V2) {
14568 if (V1 == V2)
14569 return true;
14570 if (V1->getType() != V2->getType())
14571 return false;
14572 ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
14573 ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
14574 if (Opcodes1.size() != Opcodes2.size())
14575 return false;
14576 for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
14577 // Undefs are compatible with any other value.
14578 if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
14579 continue;
14580 if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
14581 if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
14582 if (I1->getParent() != I2->getParent())
14583 return false;
14584 InstructionsState S = getSameOpcode({I1, I2}, *TLI);
14585 if (S.getOpcode())
14586 continue;
14587 return false;
14588 }
14589 if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
14590 continue;
14591 if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
14592 return false;
14593 }
14594 return true;
14595 };
14596
14597 bool HaveVectorizedPhiNodes = false;
14598 do {
14599 // Collect the incoming values from the PHIs.
14600 Incoming.clear();
14601 for (Instruction &I : *BB) {
14602 PHINode *P = dyn_cast<PHINode>(&I);
14603 if (!P)
14604 break;
14605
14606 // No need to analyze deleted, vectorized and non-vectorizable
14607 // instructions.
14608 if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
14609 isValidElementType(P->getType()))
14610 Incoming.push_back(P);
14611 }
14612
14613 // Find the corresponding non-phi nodes for better matching when trying to
14614 // build the tree.
14615 for (Value *V : Incoming) {
14616 SmallVectorImpl<Value *> &Opcodes =
14617 PHIToOpcodes.try_emplace(V).first->getSecond();
14618 if (!Opcodes.empty())
14619 continue;
14620 SmallVector<Value *, 4> Nodes(1, V);
14621 SmallPtrSet<Value *, 4> Visited;
14622 while (!Nodes.empty()) {
14623 auto *PHI = cast<PHINode>(Nodes.pop_back_val());
14624 if (!Visited.insert(PHI).second)
14625 continue;
14626 for (Value *V : PHI->incoming_values()) {
14627 if (auto *PHI1 = dyn_cast<PHINode>((V))) {
14628 Nodes.push_back(PHI1);
14629 continue;
14630 }
14631 Opcodes.emplace_back(V);
14632 }
14633 }
14634 }
14635
14636 HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
14637 Incoming, PHICompare, AreCompatiblePHIs,
14638 [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
14639 return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
14640 },
14641 /*LimitForRegisterSize=*/true, R);
14642 Changed |= HaveVectorizedPhiNodes;
14643 VisitedInstrs.insert(Incoming.begin(), Incoming.end());
14644 } while (HaveVectorizedPhiNodes);
14645
14646 VisitedInstrs.clear();
14647
14648 InstSetVector PostProcessInstructions;
14649 SmallDenseSet<Instruction *, 4> KeyNodes;
14650 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
14651 // Skip instructions with scalable type. The num of elements is unknown at
14652 // compile-time for scalable type.
14653 if (isa<ScalableVectorType>(it->getType()))
14654 continue;
14655
14656 // Skip instructions marked for the deletion.
14657 if (R.isDeleted(&*it))
14658 continue;
14659 // We may go through BB multiple times so skip the one we have checked.
14660 if (!VisitedInstrs.insert(&*it).second) {
14661 if (it->use_empty() && KeyNodes.contains(&*it) &&
14662 vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
14663 it->isTerminator())) {
14664 // We would like to start over since some instructions are deleted
14665 // and the iterator may become invalid value.
14666 Changed = true;
14667 it = BB->begin();
14668 e = BB->end();
14669 }
14670 continue;
14671 }
14672
14673 if (isa<DbgInfoIntrinsic>(it))
14674 continue;
14675
14676 // Try to vectorize reductions that use PHINodes.
14677 if (PHINode *P = dyn_cast<PHINode>(it)) {
14678 // Check that the PHI is a reduction PHI.
14679 if (P->getNumIncomingValues() == 2) {
14680 // Try to match and vectorize a horizontal reduction.
14681 Instruction *Root = getReductionInstr(DT, P, BB, LI);
14682 if (Root && vectorizeRootInstruction(P, Root, BB, R, TTI)) {
14683 Changed = true;
14684 it = BB->begin();
14685 e = BB->end();
14686 continue;
14687 }
14688 }
14689 // Try to vectorize the incoming values of the PHI, to catch reductions
14690 // that feed into PHIs.
14691 for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
14692 // Skip if the incoming block is the current BB for now. Also, bypass
14693 // unreachable IR for efficiency and to avoid crashing.
14694 // TODO: Collect the skipped incoming values and try to vectorize them
14695 // after processing BB.
14696 if (BB == P->getIncomingBlock(I) ||
14697 !DT->isReachableFromEntry(P->getIncomingBlock(I)))
14698 continue;
14699
14700 // Postponed instructions should not be vectorized here, delay their
14701 // vectorization.
14702 if (auto *PI = dyn_cast<Instruction>(P->getIncomingValue(I));
14703 PI && !PostProcessInstructions.contains(PI))
14704 Changed |= vectorizeRootInstruction(nullptr, PI,
14705 P->getIncomingBlock(I), R, TTI);
14706 }
14707 continue;
14708 }
14709
14710 // Ran into an instruction without users, like terminator, or function call
14711 // with ignored return value, store. Ignore unused instructions (basing on
14712 // instruction type, except for CallInst and InvokeInst).
14713 if (it->use_empty() &&
14714 (it->getType()->isVoidTy() || isa<CallInst, InvokeInst>(it))) {
14715 KeyNodes.insert(&*it);
14716 bool OpsChanged = false;
14717 auto *SI = dyn_cast<StoreInst>(it);
14718 bool TryToVectorizeRoot = ShouldStartVectorizeHorAtStore || !SI;
14719 if (SI) {
14720 auto I = Stores.find(getUnderlyingObject(SI->getPointerOperand()));
14721 // Try to vectorize chain in store, if this is the only store to the
14722 // address in the block.
14723 // TODO: This is just a temporarily solution to save compile time. Need
14724 // to investigate if we can safely turn on slp-vectorize-hor-store
14725 // instead to allow lookup for reduction chains in all non-vectorized
14726 // stores (need to check side effects and compile time).
14727 TryToVectorizeRoot = (I == Stores.end() || I->second.size() == 1) &&
14728 SI->getValueOperand()->hasOneUse();
14729 }
14730 if (TryToVectorizeRoot) {
14731 for (auto *V : it->operand_values()) {
14732 // Postponed instructions should not be vectorized here, delay their
14733 // vectorization.
14734 if (auto *VI = dyn_cast<Instruction>(V);
14735 VI && !PostProcessInstructions.contains(VI))
14736 // Try to match and vectorize a horizontal reduction.
14737 OpsChanged |= vectorizeRootInstruction(nullptr, VI, BB, R, TTI);
14738 }
14739 }
14740 // Start vectorization of post-process list of instructions from the
14741 // top-tree instructions to try to vectorize as many instructions as
14742 // possible.
14743 OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
14744 it->isTerminator());
14745 if (OpsChanged) {
14746 // We would like to start over since some instructions are deleted
14747 // and the iterator may become invalid value.
14748 Changed = true;
14749 it = BB->begin();
14750 e = BB->end();
14751 continue;
14752 }
14753 }
14754
14755 if (isa<CmpInst, InsertElementInst, InsertValueInst>(it))
14756 PostProcessInstructions.insert(&*it);
14757 }
14758
14759 return Changed;
14760}
14761
14762bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
14763 auto Changed = false;
14764 for (auto &Entry : GEPs) {
14765 // If the getelementptr list has fewer than two elements, there's nothing
14766 // to do.
14767 if (Entry.second.size() < 2)
14768 continue;
14769
14770 LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Analyzing a getelementptr list of length "
<< Entry.second.size() << ".\n"; } } while (false
)
14771 << Entry.second.size() << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Analyzing a getelementptr list of length "
<< Entry.second.size() << ".\n"; } } while (false
)
;
14772
14773 // Process the GEP list in chunks suitable for the target's supported
14774 // vector size. If a vector register can't hold 1 element, we are done. We
14775 // are trying to vectorize the index computations, so the maximum number of
14776 // elements is based on the size of the index expression, rather than the
14777 // size of the GEP itself (the target's pointer size).
14778 unsigned MaxVecRegSize = R.getMaxVecRegSize();
14779 unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
14780 if (MaxVecRegSize < EltSize)
14781 continue;
14782
14783 unsigned MaxElts = MaxVecRegSize / EltSize;
14784 for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
14785 auto Len = std::min<unsigned>(BE - BI, MaxElts);
14786 ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
14787
14788 // Initialize a set a candidate getelementptrs. Note that we use a
14789 // SetVector here to preserve program order. If the index computations
14790 // are vectorizable and begin with loads, we want to minimize the chance
14791 // of having to reorder them later.
14792 SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
14793
14794 // Some of the candidates may have already been vectorized after we
14795 // initially collected them. If so, they are marked as deleted, so remove
14796 // them from the set of candidates.
14797 Candidates.remove_if(
14798 [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
14799
14800 // Remove from the set of candidates all pairs of getelementptrs with
14801 // constant differences. Such getelementptrs are likely not good
14802 // candidates for vectorization in a bottom-up phase since one can be
14803 // computed from the other. We also ensure all candidate getelementptr
14804 // indices are unique.
14805 for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
14806 auto *GEPI = GEPList[I];
14807 if (!Candidates.count(GEPI))
14808 continue;
14809 auto *SCEVI = SE->getSCEV(GEPList[I]);
14810 for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
14811 auto *GEPJ = GEPList[J];
14812 auto *SCEVJ = SE->getSCEV(GEPList[J]);
14813 if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
14814 Candidates.remove(GEPI);
14815 Candidates.remove(GEPJ);
14816 } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
14817 Candidates.remove(GEPJ);
14818 }
14819 }
14820 }
14821
14822 // We break out of the above computation as soon as we know there are
14823 // fewer than two candidates remaining.
14824 if (Candidates.size() < 2)
14825 continue;
14826
14827 // Add the single, non-constant index of each candidate to the bundle. We
14828 // ensured the indices met these constraints when we originally collected
14829 // the getelementptrs.
14830 SmallVector<Value *, 16> Bundle(Candidates.size());
14831 auto BundleIndex = 0u;
14832 for (auto *V : Candidates) {
14833 auto *GEP = cast<GetElementPtrInst>(V);
14834 auto *GEPIdx = GEP->idx_begin()->get();
14835 assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx))(static_cast <bool> (GEP->getNumIndices() == 1 || !isa
<Constant>(GEPIdx)) ? void (0) : __assert_fail ("GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx)"
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14835, __extension__
__PRETTY_FUNCTION__))
;
14836 Bundle[BundleIndex++] = GEPIdx;
14837 }
14838
14839 // Try and vectorize the indices. We are currently only interested in
14840 // gather-like cases of the form:
14841 //
14842 // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
14843 //
14844 // where the loads of "a", the loads of "b", and the subtractions can be
14845 // performed in parallel. It's likely that detecting this pattern in a
14846 // bottom-up phase will be simpler and less costly than building a
14847 // full-blown top-down phase beginning at the consecutive loads.
14848 Changed |= tryToVectorizeList(Bundle, R);
14849 }
14850 }
14851 return Changed;
14852}
14853
14854bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
14855 bool Changed = false;
14856 // Sort by type, base pointers and values operand. Value operands must be
14857 // compatible (have the same opcode, same parent), otherwise it is
14858 // definitely not profitable to try to vectorize them.
14859 auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
14860 if (V->getPointerOperandType()->getTypeID() <
14861 V2->getPointerOperandType()->getTypeID())
14862 return true;
14863 if (V->getPointerOperandType()->getTypeID() >
14864 V2->getPointerOperandType()->getTypeID())
14865 return false;
14866 // UndefValues are compatible with all other values.
14867 if (isa<UndefValue>(V->getValueOperand()) ||
14868 isa<UndefValue>(V2->getValueOperand()))
14869 return false;
14870 if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
14871 if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
14872 DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
14873 DT->getNode(I1->getParent());
14874 DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
14875 DT->getNode(I2->getParent());
14876 assert(NodeI1 && "Should only process reachable instructions")(static_cast <bool> (NodeI1 && "Should only process reachable instructions"
) ? void (0) : __assert_fail ("NodeI1 && \"Should only process reachable instructions\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14876, __extension__
__PRETTY_FUNCTION__))
;
14877 assert(NodeI2 && "Should only process reachable instructions")(static_cast <bool> (NodeI2 && "Should only process reachable instructions"
) ? void (0) : __assert_fail ("NodeI2 && \"Should only process reachable instructions\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14877, __extension__
__PRETTY_FUNCTION__))
;
14878 assert((NodeI1 == NodeI2) ==(static_cast <bool> ((NodeI1 == NodeI2) == (NodeI1->
getDFSNumIn() == NodeI2->getDFSNumIn()) && "Different nodes should have different DFS numbers"
) ? void (0) : __assert_fail ("(NodeI1 == NodeI2) == (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && \"Different nodes should have different DFS numbers\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14880, __extension__
__PRETTY_FUNCTION__))
14879 (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&(static_cast <bool> ((NodeI1 == NodeI2) == (NodeI1->
getDFSNumIn() == NodeI2->getDFSNumIn()) && "Different nodes should have different DFS numbers"
) ? void (0) : __assert_fail ("(NodeI1 == NodeI2) == (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && \"Different nodes should have different DFS numbers\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14880, __extension__
__PRETTY_FUNCTION__))
14880 "Different nodes should have different DFS numbers")(static_cast <bool> ((NodeI1 == NodeI2) == (NodeI1->
getDFSNumIn() == NodeI2->getDFSNumIn()) && "Different nodes should have different DFS numbers"
) ? void (0) : __assert_fail ("(NodeI1 == NodeI2) == (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && \"Different nodes should have different DFS numbers\""
, "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 14880, __extension__
__PRETTY_FUNCTION__))
;
14881 if (NodeI1 != NodeI2)
14882 return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
14883 InstructionsState S = getSameOpcode({I1, I2}, *TLI);
14884 if (S.getOpcode())
14885 return false;
14886 return I1->getOpcode() < I2->getOpcode();
14887 }
14888 if (isa<Constant>(V->getValueOperand()) &&
14889 isa<Constant>(V2->getValueOperand()))
14890 return false;
14891 return V->getValueOperand()->getValueID() <
14892 V2->getValueOperand()->getValueID();
14893 };
14894
14895 auto &&AreCompatibleStores = [this](StoreInst *V1, StoreInst *V2) {
14896 if (V1 == V2)
14897 return true;
14898 if (V1->getPointerOperandType() != V2->getPointerOperandType())
14899 return false;
14900 // Undefs are compatible with any other value.
14901 if (isa<UndefValue>(V1->getValueOperand()) ||
14902 isa<UndefValue>(V2->getValueOperand()))
14903 return true;
14904 if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
14905 if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
14906 if (I1->getParent() != I2->getParent())
14907 return false;
14908 InstructionsState S = getSameOpcode({I1, I2}, *TLI);
14909 return S.getOpcode() > 0;
14910 }
14911 if (isa<Constant>(V1->getValueOperand()) &&
14912 isa<Constant>(V2->getValueOperand()))
14913 return true;
14914 return V1->getValueOperand()->getValueID() ==
14915 V2->getValueOperand()->getValueID();
14916 };
14917
14918 // Attempt to sort and vectorize each of the store-groups.
14919 for (auto &Pair : Stores) {
14920 if (Pair.second.size() < 2)
14921 continue;
14922
14923 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Analyzing a store chain of length "
<< Pair.second.size() << ".\n"; } } while (false
)
14924 << Pair.second.size() << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("SLP")) { dbgs() << "SLP: Analyzing a store chain of length "
<< Pair.second.size() << ".\n"; } } while (false
)
;
14925
14926 if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
14927 continue;
14928
14929 Changed |= tryToVectorizeSequence<StoreInst>(
14930 Pair.second, StoreSorter, AreCompatibleStores,
14931 [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
14932 return vectorizeStores(Candidates, R);
14933 },
14934 /*LimitForRegisterSize=*/false, R);
14935 }
14936 return Changed;
14937}