Bug Summary

File:build/source/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
Warning:line 11931, column 9
Value stored to 'VectorizedTree' is never read

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