Bug Summary

File:llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
Warning:line 6154, column 9
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SLPVectorizer.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -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 -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/lib/Transforms/Vectorize -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/lib/Transforms/Vectorize -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/lib/Transforms/Vectorize -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include -D 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-14/lib/clang/14.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 -O2 -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 -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/lib/Transforms/Vectorize -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -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-2021-09-04-040900-46481-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/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/STLExtras.h"
25#include "llvm/ADT/SetOperations.h"
26#include "llvm/ADT/SetVector.h"
27#include "llvm/ADT/SmallBitVector.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/SmallSet.h"
30#include "llvm/ADT/SmallString.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/ADT/iterator.h"
33#include "llvm/ADT/iterator_range.h"
34#include "llvm/Analysis/AliasAnalysis.h"
35#include "llvm/Analysis/AssumptionCache.h"
36#include "llvm/Analysis/CodeMetrics.h"
37#include "llvm/Analysis/DemandedBits.h"
38#include "llvm/Analysis/GlobalsModRef.h"
39#include "llvm/Analysis/IVDescriptors.h"
40#include "llvm/Analysis/LoopAccessAnalysis.h"
41#include "llvm/Analysis/LoopInfo.h"
42#include "llvm/Analysis/MemoryLocation.h"
43#include "llvm/Analysis/OptimizationRemarkEmitter.h"
44#include "llvm/Analysis/ScalarEvolution.h"
45#include "llvm/Analysis/ScalarEvolutionExpressions.h"
46#include "llvm/Analysis/TargetLibraryInfo.h"
47#include "llvm/Analysis/TargetTransformInfo.h"
48#include "llvm/Analysis/ValueTracking.h"
49#include "llvm/Analysis/VectorUtils.h"
50#include "llvm/IR/Attributes.h"
51#include "llvm/IR/BasicBlock.h"
52#include "llvm/IR/Constant.h"
53#include "llvm/IR/Constants.h"
54#include "llvm/IR/DataLayout.h"
55#include "llvm/IR/DebugLoc.h"
56#include "llvm/IR/DerivedTypes.h"
57#include "llvm/IR/Dominators.h"
58#include "llvm/IR/Function.h"
59#include "llvm/IR/IRBuilder.h"
60#include "llvm/IR/InstrTypes.h"
61#include "llvm/IR/Instruction.h"
62#include "llvm/IR/Instructions.h"
63#include "llvm/IR/IntrinsicInst.h"
64#include "llvm/IR/Intrinsics.h"
65#include "llvm/IR/Module.h"
66#include "llvm/IR/NoFolder.h"
67#include "llvm/IR/Operator.h"
68#include "llvm/IR/PatternMatch.h"
69#include "llvm/IR/Type.h"
70#include "llvm/IR/Use.h"
71#include "llvm/IR/User.h"
72#include "llvm/IR/Value.h"
73#include "llvm/IR/ValueHandle.h"
74#include "llvm/IR/Verifier.h"
75#include "llvm/InitializePasses.h"
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/LoopUtils.h"
90#include "llvm/Transforms/Vectorize.h"
91#include <algorithm>
92#include <cassert>
93#include <cstdint>
94#include <iterator>
95#include <memory>
96#include <set>
97#include <string>
98#include <tuple>
99#include <utility>
100#include <vector>
101
102using namespace llvm;
103using namespace llvm::PatternMatch;
104using namespace slpvectorizer;
105
106#define SV_NAME"slp-vectorizer" "slp-vectorizer"
107#define DEBUG_TYPE"SLP" "SLP"
108
109STATISTIC(NumVectorInstructions, "Number of vector instructions generated")static llvm::Statistic NumVectorInstructions = {"SLP", "NumVectorInstructions"
, "Number of vector instructions generated"}
;
110
111cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
112 cl::desc("Run the SLP vectorization passes"));
113
114static cl::opt<int>
115 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
116 cl::desc("Only vectorize if you gain more than this "
117 "number "));
118
119static cl::opt<bool>
120ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
121 cl::desc("Attempt to vectorize horizontal reductions"));
122
123static cl::opt<bool> ShouldStartVectorizeHorAtStore(
124 "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
125 cl::desc(
126 "Attempt to vectorize horizontal reductions feeding into a store"));
127
128static cl::opt<int>
129MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
130 cl::desc("Attempt to vectorize for this register size in bits"));
131
132static cl::opt<unsigned>
133MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
134 cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
135
136static cl::opt<int>
137MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
138 cl::desc("Maximum depth of the lookup for consecutive stores."));
139
140/// Limits the size of scheduling regions in a block.
141/// It avoid long compile times for _very_ large blocks where vector
142/// instructions are spread over a wide range.
143/// This limit is way higher than needed by real-world functions.
144static cl::opt<int>
145ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
146 cl::desc("Limit the size of the SLP scheduling region per block"));
147
148static cl::opt<int> MinVectorRegSizeOption(
149 "slp-min-reg-size", cl::init(128), cl::Hidden,
150 cl::desc("Attempt to vectorize for this register size in bits"));
151
152static cl::opt<unsigned> RecursionMaxDepth(
153 "slp-recursion-max-depth", cl::init(12), cl::Hidden,
154 cl::desc("Limit the recursion depth when building a vectorizable tree"));
155
156static cl::opt<unsigned> MinTreeSize(
157 "slp-min-tree-size", cl::init(3), cl::Hidden,
158 cl::desc("Only vectorize small trees if they are fully vectorizable"));
159
160// The maximum depth that the look-ahead score heuristic will explore.
161// The higher this value, the higher the compilation time overhead.
162static cl::opt<int> LookAheadMaxDepth(
163 "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
164 cl::desc("The maximum look-ahead depth for operand reordering scores"));
165
166// The Look-ahead heuristic goes through the users of the bundle to calculate
167// the users cost in getExternalUsesCost(). To avoid compilation time increase
168// we limit the number of users visited to this value.
169static cl::opt<unsigned> LookAheadUsersBudget(
170 "slp-look-ahead-users-budget", cl::init(2), cl::Hidden,
171 cl::desc("The maximum number of users to visit while visiting the "
172 "predecessors. This prevents compilation time increase."));
173
174static cl::opt<bool>
175 ViewSLPTree("view-slp-tree", cl::Hidden,
176 cl::desc("Display the SLP trees with Graphviz"));
177
178// Limit the number of alias checks. The limit is chosen so that
179// it has no negative effect on the llvm benchmarks.
180static const unsigned AliasedCheckLimit = 10;
181
182// Another limit for the alias checks: The maximum distance between load/store
183// instructions where alias checks are done.
184// This limit is useful for very large basic blocks.
185static const unsigned MaxMemDepDistance = 160;
186
187/// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
188/// regions to be handled.
189static const int MinScheduleRegionSize = 16;
190
191/// Predicate for the element types that the SLP vectorizer supports.
192///
193/// The most important thing to filter here are types which are invalid in LLVM
194/// vectors. We also filter target specific types which have absolutely no
195/// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
196/// avoids spending time checking the cost model and realizing that they will
197/// be inevitably scalarized.
198static bool isValidElementType(Type *Ty) {
199 return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
200 !Ty->isPPC_FP128Ty();
201}
202
203/// \returns true if all of the instructions in \p VL are in the same block or
204/// false otherwise.
205static bool allSameBlock(ArrayRef<Value *> VL) {
206 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
207 if (!I0)
208 return false;
209 BasicBlock *BB = I0->getParent();
210 for (int I = 1, E = VL.size(); I < E; I++) {
211 auto *II = dyn_cast<Instruction>(VL[I]);
212 if (!II)
213 return false;
214
215 if (BB != II->getParent())
216 return false;
217 }
218 return true;
219}
220
221/// \returns True if the value is a constant (but not globals/constant
222/// expressions).
223static bool isConstant(Value *V) {
224 return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
225}
226
227/// \returns True if all of the values in \p VL are constants (but not
228/// globals/constant expressions).
229static bool allConstant(ArrayRef<Value *> VL) {
230 // Constant expressions and globals can't be vectorized like normal integer/FP
231 // constants.
232 return all_of(VL, isConstant);
233}
234
235/// \returns True if all of the values in \p VL are identical.
236static bool isSplat(ArrayRef<Value *> VL) {
237 for (unsigned i = 1, e = VL.size(); i < e; ++i)
238 if (VL[i] != VL[0])
239 return false;
240 return true;
241}
242
243/// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
244static bool isCommutative(Instruction *I) {
245 if (auto *Cmp = dyn_cast<CmpInst>(I))
246 return Cmp->isCommutative();
247 if (auto *BO = dyn_cast<BinaryOperator>(I))
248 return BO->isCommutative();
249 // TODO: This should check for generic Instruction::isCommutative(), but
250 // we need to confirm that the caller code correctly handles Intrinsics
251 // for example (does not have 2 operands).
252 return false;
253}
254
255/// Checks if the vector of instructions can be represented as a shuffle, like:
256/// %x0 = extractelement <4 x i8> %x, i32 0
257/// %x3 = extractelement <4 x i8> %x, i32 3
258/// %y1 = extractelement <4 x i8> %y, i32 1
259/// %y2 = extractelement <4 x i8> %y, i32 2
260/// %x0x0 = mul i8 %x0, %x0
261/// %x3x3 = mul i8 %x3, %x3
262/// %y1y1 = mul i8 %y1, %y1
263/// %y2y2 = mul i8 %y2, %y2
264/// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
265/// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
266/// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
267/// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
268/// ret <4 x i8> %ins4
269/// can be transformed into:
270/// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
271/// i32 6>
272/// %2 = mul <4 x i8> %1, %1
273/// ret <4 x i8> %2
274/// We convert this initially to something like:
275/// %x0 = extractelement <4 x i8> %x, i32 0
276/// %x3 = extractelement <4 x i8> %x, i32 3
277/// %y1 = extractelement <4 x i8> %y, i32 1
278/// %y2 = extractelement <4 x i8> %y, i32 2
279/// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
280/// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
281/// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
282/// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
283/// %5 = mul <4 x i8> %4, %4
284/// %6 = extractelement <4 x i8> %5, i32 0
285/// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
286/// %7 = extractelement <4 x i8> %5, i32 1
287/// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
288/// %8 = extractelement <4 x i8> %5, i32 2
289/// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
290/// %9 = extractelement <4 x i8> %5, i32 3
291/// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
292/// ret <4 x i8> %ins4
293/// InstCombiner transforms this into a shuffle and vector mul
294/// Mask will return the Shuffle Mask equivalent to the extracted elements.
295/// TODO: Can we split off and reuse the shuffle mask detection from
296/// TargetTransformInfo::getInstructionThroughput?
297static Optional<TargetTransformInfo::ShuffleKind>
298isShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
299 auto *EI0 = cast<ExtractElementInst>(VL[0]);
300 unsigned Size =
301 cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
302 Value *Vec1 = nullptr;
303 Value *Vec2 = nullptr;
304 enum ShuffleMode { Unknown, Select, Permute };
305 ShuffleMode CommonShuffleMode = Unknown;
306 for (unsigned I = 0, E = VL.size(); I < E; ++I) {
307 auto *EI = cast<ExtractElementInst>(VL[I]);
308 auto *Vec = EI->getVectorOperand();
309 // All vector operands must have the same number of vector elements.
310 if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
311 return None;
312 auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
313 if (!Idx)
314 return None;
315 // Undefined behavior if Idx is negative or >= Size.
316 if (Idx->getValue().uge(Size)) {
317 Mask.push_back(UndefMaskElem);
318 continue;
319 }
320 unsigned IntIdx = Idx->getValue().getZExtValue();
321 Mask.push_back(IntIdx);
322 // We can extractelement from undef or poison vector.
323 if (isa<UndefValue>(Vec))
324 continue;
325 // For correct shuffling we have to have at most 2 different vector operands
326 // in all extractelement instructions.
327 if (!Vec1 || Vec1 == Vec)
328 Vec1 = Vec;
329 else if (!Vec2 || Vec2 == Vec)
330 Vec2 = Vec;
331 else
332 return None;
333 if (CommonShuffleMode == Permute)
334 continue;
335 // If the extract index is not the same as the operation number, it is a
336 // permutation.
337 if (IntIdx != I) {
338 CommonShuffleMode = Permute;
339 continue;
340 }
341 CommonShuffleMode = Select;
342 }
343 // If we're not crossing lanes in different vectors, consider it as blending.
344 if (CommonShuffleMode == Select && Vec2)
345 return TargetTransformInfo::SK_Select;
346 // If Vec2 was never used, we have a permutation of a single vector, otherwise
347 // we have permutation of 2 vectors.
348 return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
349 : TargetTransformInfo::SK_PermuteSingleSrc;
350}
351
352namespace {
353
354/// Main data required for vectorization of instructions.
355struct InstructionsState {
356 /// The very first instruction in the list with the main opcode.
357 Value *OpValue = nullptr;
358
359 /// The main/alternate instruction.
360 Instruction *MainOp = nullptr;
361 Instruction *AltOp = nullptr;
362
363 /// The main/alternate opcodes for the list of instructions.
364 unsigned getOpcode() const {
365 return MainOp ? MainOp->getOpcode() : 0;
366 }
367
368 unsigned getAltOpcode() const {
369 return AltOp ? AltOp->getOpcode() : 0;
370 }
371
372 /// Some of the instructions in the list have alternate opcodes.
373 bool isAltShuffle() const { return getOpcode() != getAltOpcode(); }
374
375 bool isOpcodeOrAlt(Instruction *I) const {
376 unsigned CheckedOpcode = I->getOpcode();
377 return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
378 }
379
380 InstructionsState() = delete;
381 InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
382 : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
383};
384
385} // end anonymous namespace
386
387/// Chooses the correct key for scheduling data. If \p Op has the same (or
388/// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
389/// OpValue.
390static Value *isOneOf(const InstructionsState &S, Value *Op) {
391 auto *I = dyn_cast<Instruction>(Op);
392 if (I && S.isOpcodeOrAlt(I))
393 return Op;
394 return S.OpValue;
395}
396
397/// \returns true if \p Opcode is allowed as part of of the main/alternate
398/// instruction for SLP vectorization.
399///
400/// Example of unsupported opcode is SDIV that can potentially cause UB if the
401/// "shuffled out" lane would result in division by zero.
402static bool isValidForAlternation(unsigned Opcode) {
403 if (Instruction::isIntDivRem(Opcode))
404 return false;
405
406 return true;
407}
408
409/// \returns analysis of the Instructions in \p VL described in
410/// InstructionsState, the Opcode that we suppose the whole list
411/// could be vectorized even if its structure is diverse.
412static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
413 unsigned BaseIndex = 0) {
414 // Make sure these are all Instructions.
415 if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
416 return InstructionsState(VL[BaseIndex], nullptr, nullptr);
417
418 bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
419 bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
420 unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
421 unsigned AltOpcode = Opcode;
422 unsigned AltIndex = BaseIndex;
423
424 // Check for one alternate opcode from another BinaryOperator.
425 // TODO - generalize to support all operators (types, calls etc.).
426 for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
427 unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
428 if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
429 if (InstOpcode == Opcode || InstOpcode == AltOpcode)
430 continue;
431 if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
432 isValidForAlternation(Opcode)) {
433 AltOpcode = InstOpcode;
434 AltIndex = Cnt;
435 continue;
436 }
437 } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
438 Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
439 Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
440 if (Ty0 == Ty1) {
441 if (InstOpcode == Opcode || InstOpcode == AltOpcode)
442 continue;
443 if (Opcode == AltOpcode) {
444 assert(isValidForAlternation(Opcode) &&(static_cast<void> (0))
445 isValidForAlternation(InstOpcode) &&(static_cast<void> (0))
446 "Cast isn't safe for alternation, logic needs to be updated!")(static_cast<void> (0));
447 AltOpcode = InstOpcode;
448 AltIndex = Cnt;
449 continue;
450 }
451 }
452 } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
453 continue;
454 return InstructionsState(VL[BaseIndex], nullptr, nullptr);
455 }
456
457 return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
458 cast<Instruction>(VL[AltIndex]));
459}
460
461/// \returns true if all of the values in \p VL have the same type or false
462/// otherwise.
463static bool allSameType(ArrayRef<Value *> VL) {
464 Type *Ty = VL[0]->getType();
465 for (int i = 1, e = VL.size(); i < e; i++)
466 if (VL[i]->getType() != Ty)
467 return false;
468
469 return true;
470}
471
472/// \returns True if Extract{Value,Element} instruction extracts element Idx.
473static Optional<unsigned> getExtractIndex(Instruction *E) {
474 unsigned Opcode = E->getOpcode();
475 assert((Opcode == Instruction::ExtractElement ||(static_cast<void> (0))
476 Opcode == Instruction::ExtractValue) &&(static_cast<void> (0))
477 "Expected extractelement or extractvalue instruction.")(static_cast<void> (0));
478 if (Opcode == Instruction::ExtractElement) {
479 auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
480 if (!CI)
481 return None;
482 return CI->getZExtValue();
483 }
484 ExtractValueInst *EI = cast<ExtractValueInst>(E);
485 if (EI->getNumIndices() != 1)
486 return None;
487 return *EI->idx_begin();
488}
489
490/// \returns True if in-tree use also needs extract. This refers to
491/// possible scalar operand in vectorized instruction.
492static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
493 TargetLibraryInfo *TLI) {
494 unsigned Opcode = UserInst->getOpcode();
495 switch (Opcode) {
496 case Instruction::Load: {
497 LoadInst *LI = cast<LoadInst>(UserInst);
498 return (LI->getPointerOperand() == Scalar);
499 }
500 case Instruction::Store: {
501 StoreInst *SI = cast<StoreInst>(UserInst);
502 return (SI->getPointerOperand() == Scalar);
503 }
504 case Instruction::Call: {
505 CallInst *CI = cast<CallInst>(UserInst);
506 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
507 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
508 if (hasVectorInstrinsicScalarOpd(ID, i))
509 return (CI->getArgOperand(i) == Scalar);
510 }
511 LLVM_FALLTHROUGH[[gnu::fallthrough]];
512 }
513 default:
514 return false;
515 }
516}
517
518/// \returns the AA location that is being access by the instruction.
519static MemoryLocation getLocation(Instruction *I, AAResults *AA) {
520 if (StoreInst *SI = dyn_cast<StoreInst>(I))
521 return MemoryLocation::get(SI);
522 if (LoadInst *LI = dyn_cast<LoadInst>(I))
523 return MemoryLocation::get(LI);
524 return MemoryLocation();
525}
526
527/// \returns True if the instruction is not a volatile or atomic load/store.
528static bool isSimple(Instruction *I) {
529 if (LoadInst *LI = dyn_cast<LoadInst>(I))
530 return LI->isSimple();
531 if (StoreInst *SI = dyn_cast<StoreInst>(I))
532 return SI->isSimple();
533 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
534 return !MI->isVolatile();
535 return true;
536}
537
538namespace llvm {
539
540static void inversePermutation(ArrayRef<unsigned> Indices,
541 SmallVectorImpl<int> &Mask) {
542 Mask.clear();
543 const unsigned E = Indices.size();
544 Mask.resize(E, E + 1);
545 for (unsigned I = 0; I < E; ++I)
546 Mask[Indices[I]] = I;
547}
548
549/// \returns inserting index of InsertElement or InsertValue instruction,
550/// using Offset as base offset for index.
551static Optional<int> getInsertIndex(Value *InsertInst, unsigned Offset) {
552 int Index = Offset;
553 if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
554 if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
555 auto *VT = cast<FixedVectorType>(IE->getType());
556 if (CI->getValue().uge(VT->getNumElements()))
557 return UndefMaskElem;
558 Index *= VT->getNumElements();
559 Index += CI->getZExtValue();
560 return Index;
561 }
562 if (isa<UndefValue>(IE->getOperand(2)))
563 return UndefMaskElem;
564 return None;
565 }
566
567 auto *IV = cast<InsertValueInst>(InsertInst);
568 Type *CurrentType = IV->getType();
569 for (unsigned I : IV->indices()) {
570 if (auto *ST = dyn_cast<StructType>(CurrentType)) {
571 Index *= ST->getNumElements();
572 CurrentType = ST->getElementType(I);
573 } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
574 Index *= AT->getNumElements();
575 CurrentType = AT->getElementType();
576 } else {
577 return None;
578 }
579 Index += I;
580 }
581 return Index;
582}
583
584namespace slpvectorizer {
585
586/// Bottom Up SLP Vectorizer.
587class BoUpSLP {
588 struct TreeEntry;
589 struct ScheduleData;
590
591public:
592 using ValueList = SmallVector<Value *, 8>;
593 using InstrList = SmallVector<Instruction *, 16>;
594 using ValueSet = SmallPtrSet<Value *, 16>;
595 using StoreList = SmallVector<StoreInst *, 8>;
596 using ExtraValueToDebugLocsMap =
597 MapVector<Value *, SmallVector<Instruction *, 2>>;
598 using OrdersType = SmallVector<unsigned, 4>;
599
600 BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
601 TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
602 DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
603 const DataLayout *DL, OptimizationRemarkEmitter *ORE)
604 : F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC),
605 DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
606 CodeMetrics::collectEphemeralValues(F, AC, EphValues);
607 // Use the vector register size specified by the target unless overridden
608 // by a command-line option.
609 // TODO: It would be better to limit the vectorization factor based on
610 // data type rather than just register size. For example, x86 AVX has
611 // 256-bit registers, but it does not support integer operations
612 // at that width (that requires AVX2).
613 if (MaxVectorRegSizeOption.getNumOccurrences())
614 MaxVecRegSize = MaxVectorRegSizeOption;
615 else
616 MaxVecRegSize =
617 TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
618 .getFixedSize();
619
620 if (MinVectorRegSizeOption.getNumOccurrences())
621 MinVecRegSize = MinVectorRegSizeOption;
622 else
623 MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
624 }
625
626 /// Vectorize the tree that starts with the elements in \p VL.
627 /// Returns the vectorized root.
628 Value *vectorizeTree();
629
630 /// Vectorize the tree but with the list of externally used values \p
631 /// ExternallyUsedValues. Values in this MapVector can be replaced but the
632 /// generated extractvalue instructions.
633 Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
634
635 /// \returns the cost incurred by unwanted spills and fills, caused by
636 /// holding live values over call sites.
637 InstructionCost getSpillCost() const;
638
639 /// \returns the vectorization cost of the subtree that starts at \p VL.
640 /// A negative number means that this is profitable.
641 InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
642
643 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
644 /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
645 void buildTree(ArrayRef<Value *> Roots,
646 ArrayRef<Value *> UserIgnoreLst = None);
647
648 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
649 /// the purpose of scheduling and extraction in the \p UserIgnoreLst taking
650 /// into account (and updating it, if required) list of externally used
651 /// values stored in \p ExternallyUsedValues.
652 void buildTree(ArrayRef<Value *> Roots,
653 ExtraValueToDebugLocsMap &ExternallyUsedValues,
654 ArrayRef<Value *> UserIgnoreLst = None);
655
656 /// Clear the internal data structures that are created by 'buildTree'.
657 void deleteTree() {
658 VectorizableTree.clear();
659 ScalarToTreeEntry.clear();
660 MustGather.clear();
661 ExternalUses.clear();
662 NumOpsWantToKeepOrder.clear();
663 NumOpsWantToKeepOriginalOrder = 0;
664 for (auto &Iter : BlocksSchedules) {
665 BlockScheduling *BS = Iter.second.get();
666 BS->clear();
667 }
668 MinBWs.clear();
669 InstrElementSize.clear();
670 }
671
672 unsigned getTreeSize() const { return VectorizableTree.size(); }
673
674 /// Perform LICM and CSE on the newly generated gather sequences.
675 void optimizeGatherSequence();
676
677 /// \returns The best order of instructions for vectorization.
678 Optional<ArrayRef<unsigned>> bestOrder() const {
679 assert(llvm::all_of((static_cast<void> (0))
680 NumOpsWantToKeepOrder,(static_cast<void> (0))
681 [this](const decltype(NumOpsWantToKeepOrder)::value_type &D) {(static_cast<void> (0))
682 return D.getFirst().size() ==(static_cast<void> (0))
683 VectorizableTree[0]->Scalars.size();(static_cast<void> (0))
684 }) &&(static_cast<void> (0))
685 "All orders must have the same size as number of instructions in "(static_cast<void> (0))
686 "tree node.")(static_cast<void> (0));
687 auto I = std::max_element(
688 NumOpsWantToKeepOrder.begin(), NumOpsWantToKeepOrder.end(),
689 [](const decltype(NumOpsWantToKeepOrder)::value_type &D1,
690 const decltype(NumOpsWantToKeepOrder)::value_type &D2) {
691 return D1.second < D2.second;
692 });
693 if (I == NumOpsWantToKeepOrder.end() ||
694 I->getSecond() <= NumOpsWantToKeepOriginalOrder)
695 return None;
696
697 return makeArrayRef(I->getFirst());
698 }
699
700 /// Builds the correct order for root instructions.
701 /// If some leaves have the same instructions to be vectorized, we may
702 /// incorrectly evaluate the best order for the root node (it is built for the
703 /// vector of instructions without repeated instructions and, thus, has less
704 /// elements than the root node). This function builds the correct order for
705 /// the root node.
706 /// For example, if the root node is \<a+b, a+c, a+d, f+e\>, then the leaves
707 /// are \<a, a, a, f\> and \<b, c, d, e\>. When we try to vectorize the first
708 /// leaf, it will be shrink to \<a, b\>. If instructions in this leaf should
709 /// be reordered, the best order will be \<1, 0\>. We need to extend this
710 /// order for the root node. For the root node this order should look like
711 /// \<3, 0, 1, 2\>. This function extends the order for the reused
712 /// instructions.
713 void findRootOrder(OrdersType &Order) {
714 // If the leaf has the same number of instructions to vectorize as the root
715 // - order must be set already.
716 unsigned RootSize = VectorizableTree[0]->Scalars.size();
717 if (Order.size() == RootSize)
718 return;
719 SmallVector<unsigned, 4> RealOrder(Order.size());
720 std::swap(Order, RealOrder);
721 SmallVector<int, 4> Mask;
722 inversePermutation(RealOrder, Mask);
723 Order.assign(Mask.begin(), Mask.end());
724 // The leaf has less number of instructions - need to find the true order of
725 // the root.
726 // Scan the nodes starting from the leaf back to the root.
727 const TreeEntry *PNode = VectorizableTree.back().get();
728 SmallVector<const TreeEntry *, 4> Nodes(1, PNode);
729 SmallPtrSet<const TreeEntry *, 4> Visited;
730 while (!Nodes.empty() && Order.size() != RootSize) {
731 const TreeEntry *PNode = Nodes.pop_back_val();
732 if (!Visited.insert(PNode).second)
733 continue;
734 const TreeEntry &Node = *PNode;
735 for (const EdgeInfo &EI : Node.UserTreeIndices)
736 if (EI.UserTE)
737 Nodes.push_back(EI.UserTE);
738 if (Node.ReuseShuffleIndices.empty())
739 continue;
740 // Build the order for the parent node.
741 OrdersType NewOrder(Node.ReuseShuffleIndices.size(), RootSize);
742 SmallVector<unsigned, 4> OrderCounter(Order.size(), 0);
743 // The algorithm of the order extension is:
744 // 1. Calculate the number of the same instructions for the order.
745 // 2. Calculate the index of the new order: total number of instructions
746 // with order less than the order of the current instruction + reuse
747 // number of the current instruction.
748 // 3. The new order is just the index of the instruction in the original
749 // vector of the instructions.
750 for (unsigned I : Node.ReuseShuffleIndices)
751 ++OrderCounter[Order[I]];
752 SmallVector<unsigned, 4> CurrentCounter(Order.size(), 0);
753 for (unsigned I = 0, E = Node.ReuseShuffleIndices.size(); I < E; ++I) {
754 unsigned ReusedIdx = Node.ReuseShuffleIndices[I];
755 unsigned OrderIdx = Order[ReusedIdx];
756 unsigned NewIdx = 0;
757 for (unsigned J = 0; J < OrderIdx; ++J)
758 NewIdx += OrderCounter[J];
759 NewIdx += CurrentCounter[OrderIdx];
760 ++CurrentCounter[OrderIdx];
761 assert(NewOrder[NewIdx] == RootSize &&(static_cast<void> (0))
762 "The order index should not be written already.")(static_cast<void> (0));
763 NewOrder[NewIdx] = I;
764 }
765 std::swap(Order, NewOrder);
766 }
767 assert(Order.size() == RootSize &&(static_cast<void> (0))
768 "Root node is expected or the size of the order must be the same as "(static_cast<void> (0))
769 "the number of elements in the root node.")(static_cast<void> (0));
770 assert(llvm::all_of(Order,(static_cast<void> (0))
771 [RootSize](unsigned Val) { return Val != RootSize; }) &&(static_cast<void> (0))
772 "All indices must be initialized")(static_cast<void> (0));
773 }
774
775 /// \return The vector element size in bits to use when vectorizing the
776 /// expression tree ending at \p V. If V is a store, the size is the width of
777 /// the stored value. Otherwise, the size is the width of the largest loaded
778 /// value reaching V. This method is used by the vectorizer to calculate
779 /// vectorization factors.
780 unsigned getVectorElementSize(Value *V);
781
782 /// Compute the minimum type sizes required to represent the entries in a
783 /// vectorizable tree.
784 void computeMinimumValueSizes();
785
786 // \returns maximum vector register size as set by TTI or overridden by cl::opt.
787 unsigned getMaxVecRegSize() const {
788 return MaxVecRegSize;
789 }
790
791 // \returns minimum vector register size as set by cl::opt.
792 unsigned getMinVecRegSize() const {
793 return MinVecRegSize;
794 }
795
796 unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
797 unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
798 MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
799 return MaxVF ? MaxVF : UINT_MAX(2147483647 *2U +1U);
800 }
801
802 /// Check if homogeneous aggregate is isomorphic to some VectorType.
803 /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
804 /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
805 /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
806 ///
807 /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
808 unsigned canMapToVector(Type *T, const DataLayout &DL) const;
809
810 /// \returns True if the VectorizableTree is both tiny and not fully
811 /// vectorizable. We do not vectorize such trees.
812 bool isTreeTinyAndNotFullyVectorizable() const;
813
814 /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
815 /// can be load combined in the backend. Load combining may not be allowed in
816 /// the IR optimizer, so we do not want to alter the pattern. For example,
817 /// partially transforming a scalar bswap() pattern into vector code is
818 /// effectively impossible for the backend to undo.
819 /// TODO: If load combining is allowed in the IR optimizer, this analysis
820 /// may not be necessary.
821 bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
822
823 /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
824 /// can be load combined in the backend. Load combining may not be allowed in
825 /// the IR optimizer, so we do not want to alter the pattern. For example,
826 /// partially transforming a scalar bswap() pattern into vector code is
827 /// effectively impossible for the backend to undo.
828 /// TODO: If load combining is allowed in the IR optimizer, this analysis
829 /// may not be necessary.
830 bool isLoadCombineCandidate() const;
831
832 OptimizationRemarkEmitter *getORE() { return ORE; }
833
834 /// This structure holds any data we need about the edges being traversed
835 /// during buildTree_rec(). We keep track of:
836 /// (i) the user TreeEntry index, and
837 /// (ii) the index of the edge.
838 struct EdgeInfo {
839 EdgeInfo() = default;
840 EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
841 : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
842 /// The user TreeEntry.
843 TreeEntry *UserTE = nullptr;
844 /// The operand index of the use.
845 unsigned EdgeIdx = UINT_MAX(2147483647 *2U +1U);
846#ifndef NDEBUG1
847 friend inline raw_ostream &operator<<(raw_ostream &OS,
848 const BoUpSLP::EdgeInfo &EI) {
849 EI.dump(OS);
850 return OS;
851 }
852 /// Debug print.
853 void dump(raw_ostream &OS) const {
854 OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
855 << " EdgeIdx:" << EdgeIdx << "}";
856 }
857 LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void dump() const { dump(dbgs()); }
858#endif
859 };
860
861 /// A helper data structure to hold the operands of a vector of instructions.
862 /// This supports a fixed vector length for all operand vectors.
863 class VLOperands {
864 /// For each operand we need (i) the value, and (ii) the opcode that it
865 /// would be attached to if the expression was in a left-linearized form.
866 /// This is required to avoid illegal operand reordering.
867 /// For example:
868 /// \verbatim
869 /// 0 Op1
870 /// |/
871 /// Op1 Op2 Linearized + Op2
872 /// \ / ----------> |/
873 /// - -
874 ///
875 /// Op1 - Op2 (0 + Op1) - Op2
876 /// \endverbatim
877 ///
878 /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
879 ///
880 /// Another way to think of this is to track all the operations across the
881 /// path from the operand all the way to the root of the tree and to
882 /// calculate the operation that corresponds to this path. For example, the
883 /// path from Op2 to the root crosses the RHS of the '-', therefore the
884 /// corresponding operation is a '-' (which matches the one in the
885 /// linearized tree, as shown above).
886 ///
887 /// For lack of a better term, we refer to this operation as Accumulated
888 /// Path Operation (APO).
889 struct OperandData {
890 OperandData() = default;
891 OperandData(Value *V, bool APO, bool IsUsed)
892 : V(V), APO(APO), IsUsed(IsUsed) {}
893 /// The operand value.
894 Value *V = nullptr;
895 /// TreeEntries only allow a single opcode, or an alternate sequence of
896 /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
897 /// APO. It is set to 'true' if 'V' is attached to an inverse operation
898 /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
899 /// (e.g., Add/Mul)
900 bool APO = false;
901 /// Helper data for the reordering function.
902 bool IsUsed = false;
903 };
904
905 /// During operand reordering, we are trying to select the operand at lane
906 /// that matches best with the operand at the neighboring lane. Our
907 /// selection is based on the type of value we are looking for. For example,
908 /// if the neighboring lane has a load, we need to look for a load that is
909 /// accessing a consecutive address. These strategies are summarized in the
910 /// 'ReorderingMode' enumerator.
911 enum class ReorderingMode {
912 Load, ///< Matching loads to consecutive memory addresses
913 Opcode, ///< Matching instructions based on opcode (same or alternate)
914 Constant, ///< Matching constants
915 Splat, ///< Matching the same instruction multiple times (broadcast)
916 Failed, ///< We failed to create a vectorizable group
917 };
918
919 using OperandDataVec = SmallVector<OperandData, 2>;
920
921 /// A vector of operand vectors.
922 SmallVector<OperandDataVec, 4> OpsVec;
923
924 const DataLayout &DL;
925 ScalarEvolution &SE;
926 const BoUpSLP &R;
927
928 /// \returns the operand data at \p OpIdx and \p Lane.
929 OperandData &getData(unsigned OpIdx, unsigned Lane) {
930 return OpsVec[OpIdx][Lane];
931 }
932
933 /// \returns the operand data at \p OpIdx and \p Lane. Const version.
934 const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
935 return OpsVec[OpIdx][Lane];
936 }
937
938 /// Clears the used flag for all entries.
939 void clearUsed() {
940 for (unsigned OpIdx = 0, NumOperands = getNumOperands();
941 OpIdx != NumOperands; ++OpIdx)
942 for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
943 ++Lane)
944 OpsVec[OpIdx][Lane].IsUsed = false;
945 }
946
947 /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
948 void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
949 std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
950 }
951
952 // The hard-coded scores listed here are not very important. When computing
953 // the scores of matching one sub-tree with another, we are basically
954 // counting the number of values that are matching. So even if all scores
955 // are set to 1, we would still get a decent matching result.
956 // However, sometimes we have to break ties. For example we may have to
957 // choose between matching loads vs matching opcodes. This is what these
958 // scores are helping us with: they provide the order of preference.
959
960 /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
961 static const int ScoreConsecutiveLoads = 3;
962 /// ExtractElementInst from same vector and consecutive indexes.
963 static const int ScoreConsecutiveExtracts = 3;
964 /// Constants.
965 static const int ScoreConstants = 2;
966 /// Instructions with the same opcode.
967 static const int ScoreSameOpcode = 2;
968 /// Instructions with alt opcodes (e.g, add + sub).
969 static const int ScoreAltOpcodes = 1;
970 /// Identical instructions (a.k.a. splat or broadcast).
971 static const int ScoreSplat = 1;
972 /// Matching with an undef is preferable to failing.
973 static const int ScoreUndef = 1;
974 /// Score for failing to find a decent match.
975 static const int ScoreFail = 0;
976 /// User exteranl to the vectorized code.
977 static const int ExternalUseCost = 1;
978 /// The user is internal but in a different lane.
979 static const int UserInDiffLaneCost = ExternalUseCost;
980
981 /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
982 static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
983 ScalarEvolution &SE) {
984 auto *LI1 = dyn_cast<LoadInst>(V1);
985 auto *LI2 = dyn_cast<LoadInst>(V2);
986 if (LI1 && LI2) {
987 if (LI1->getParent() != LI2->getParent())
988 return VLOperands::ScoreFail;
989
990 Optional<int> Dist = getPointersDiff(
991 LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
992 LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
993 return (Dist && *Dist == 1) ? VLOperands::ScoreConsecutiveLoads
994 : VLOperands::ScoreFail;
995 }
996
997 auto *C1 = dyn_cast<Constant>(V1);
998 auto *C2 = dyn_cast<Constant>(V2);
999 if (C1 && C2)
1000 return VLOperands::ScoreConstants;
1001
1002 // Extracts from consecutive indexes of the same vector better score as
1003 // the extracts could be optimized away.
1004 Value *EV;
1005 ConstantInt *Ex1Idx, *Ex2Idx;
1006 if (match(V1, m_ExtractElt(m_Value(EV), m_ConstantInt(Ex1Idx))) &&
1007 match(V2, m_ExtractElt(m_Deferred(EV), m_ConstantInt(Ex2Idx))) &&
1008 Ex1Idx->getZExtValue() + 1 == Ex2Idx->getZExtValue())
1009 return VLOperands::ScoreConsecutiveExtracts;
1010
1011 auto *I1 = dyn_cast<Instruction>(V1);
1012 auto *I2 = dyn_cast<Instruction>(V2);
1013 if (I1 && I2) {
1014 if (I1 == I2)
1015 return VLOperands::ScoreSplat;
1016 InstructionsState S = getSameOpcode({I1, I2});
1017 // Note: Only consider instructions with <= 2 operands to avoid
1018 // complexity explosion.
1019 if (S.getOpcode() && S.MainOp->getNumOperands() <= 2)
1020 return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1021 : VLOperands::ScoreSameOpcode;
1022 }
1023
1024 if (isa<UndefValue>(V2))
1025 return VLOperands::ScoreUndef;
1026
1027 return VLOperands::ScoreFail;
1028 }
1029
1030 /// Holds the values and their lane that are taking part in the look-ahead
1031 /// score calculation. This is used in the external uses cost calculation.
1032 SmallDenseMap<Value *, int> InLookAheadValues;
1033
1034 /// \Returns the additinal cost due to uses of \p LHS and \p RHS that are
1035 /// either external to the vectorized code, or require shuffling.
1036 int getExternalUsesCost(const std::pair<Value *, int> &LHS,
1037 const std::pair<Value *, int> &RHS) {
1038 int Cost = 0;
1039 std::array<std::pair<Value *, int>, 2> Values = {{LHS, RHS}};
1040 for (int Idx = 0, IdxE = Values.size(); Idx != IdxE; ++Idx) {
1041 Value *V = Values[Idx].first;
1042 if (isa<Constant>(V)) {
1043 // Since this is a function pass, it doesn't make semantic sense to
1044 // walk the users of a subclass of Constant. The users could be in
1045 // another function, or even another module that happens to be in
1046 // the same LLVMContext.
1047 continue;
1048 }
1049
1050 // Calculate the absolute lane, using the minimum relative lane of LHS
1051 // and RHS as base and Idx as the offset.
1052 int Ln = std::min(LHS.second, RHS.second) + Idx;
1053 assert(Ln >= 0 && "Bad lane calculation")(static_cast<void> (0));
1054 unsigned UsersBudget = LookAheadUsersBudget;
1055 for (User *U : V->users()) {
1056 if (const TreeEntry *UserTE = R.getTreeEntry(U)) {
1057 // The user is in the VectorizableTree. Check if we need to insert.
1058 auto It = llvm::find(UserTE->Scalars, U);
1059 assert(It != UserTE->Scalars.end() && "U is in UserTE")(static_cast<void> (0));
1060 int UserLn = std::distance(UserTE->Scalars.begin(), It);
1061 assert(UserLn >= 0 && "Bad lane")(static_cast<void> (0));
1062 if (UserLn != Ln)
1063 Cost += UserInDiffLaneCost;
1064 } else {
1065 // Check if the user is in the look-ahead code.
1066 auto It2 = InLookAheadValues.find(U);
1067 if (It2 != InLookAheadValues.end()) {
1068 // The user is in the look-ahead code. Check the lane.
1069 if (It2->second != Ln)
1070 Cost += UserInDiffLaneCost;
1071 } else {
1072 // The user is neither in SLP tree nor in the look-ahead code.
1073 Cost += ExternalUseCost;
1074 }
1075 }
1076 // Limit the number of visited uses to cap compilation time.
1077 if (--UsersBudget == 0)
1078 break;
1079 }
1080 }
1081 return Cost;
1082 }
1083
1084 /// Go through the operands of \p LHS and \p RHS recursively until \p
1085 /// MaxLevel, and return the cummulative score. For example:
1086 /// \verbatim
1087 /// A[0] B[0] A[1] B[1] C[0] D[0] B[1] A[1]
1088 /// \ / \ / \ / \ /
1089 /// + + + +
1090 /// G1 G2 G3 G4
1091 /// \endverbatim
1092 /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1093 /// each level recursively, accumulating the score. It starts from matching
1094 /// the additions at level 0, then moves on to the loads (level 1). The
1095 /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1096 /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1097 /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1098 /// Please note that the order of the operands does not matter, as we
1099 /// evaluate the score of all profitable combinations of operands. In
1100 /// other words the score of G1 and G4 is the same as G1 and G2. This
1101 /// heuristic is based on ideas described in:
1102 /// Look-ahead SLP: Auto-vectorization in the presence of commutative
1103 /// operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1104 /// Luís F. W. Góes
1105 int getScoreAtLevelRec(const std::pair<Value *, int> &LHS,
1106 const std::pair<Value *, int> &RHS, int CurrLevel,
1107 int MaxLevel) {
1108
1109 Value *V1 = LHS.first;
1110 Value *V2 = RHS.first;
1111 // Get the shallow score of V1 and V2.
1112 int ShallowScoreAtThisLevel =
1113 std::max((int)ScoreFail, getShallowScore(V1, V2, DL, SE) -
1114 getExternalUsesCost(LHS, RHS));
1115 int Lane1 = LHS.second;
1116 int Lane2 = RHS.second;
1117
1118 // If reached MaxLevel,
1119 // or if V1 and V2 are not instructions,
1120 // or if they are SPLAT,
1121 // or if they are not consecutive, early return the current cost.
1122 auto *I1 = dyn_cast<Instruction>(V1);
1123 auto *I2 = dyn_cast<Instruction>(V2);
1124 if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1125 ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1126 (isa<LoadInst>(I1) && isa<LoadInst>(I2) && ShallowScoreAtThisLevel))
1127 return ShallowScoreAtThisLevel;
1128 assert(I1 && I2 && "Should have early exited.")(static_cast<void> (0));
1129
1130 // Keep track of in-tree values for determining the external-use cost.
1131 InLookAheadValues[V1] = Lane1;
1132 InLookAheadValues[V2] = Lane2;
1133
1134 // Contains the I2 operand indexes that got matched with I1 operands.
1135 SmallSet<unsigned, 4> Op2Used;
1136
1137 // Recursion towards the operands of I1 and I2. We are trying all possbile
1138 // operand pairs, and keeping track of the best score.
1139 for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1140 OpIdx1 != NumOperands1; ++OpIdx1) {
1141 // Try to pair op1I with the best operand of I2.
1142 int MaxTmpScore = 0;
1143 unsigned MaxOpIdx2 = 0;
1144 bool FoundBest = false;
1145 // If I2 is commutative try all combinations.
1146 unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1147 unsigned ToIdx = isCommutative(I2)
1148 ? I2->getNumOperands()
1149 : std::min(I2->getNumOperands(), OpIdx1 + 1);
1150 assert(FromIdx <= ToIdx && "Bad index")(static_cast<void> (0));
1151 for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1152 // Skip operands already paired with OpIdx1.
1153 if (Op2Used.count(OpIdx2))
1154 continue;
1155 // Recursively calculate the cost at each level
1156 int TmpScore = getScoreAtLevelRec({I1->getOperand(OpIdx1), Lane1},
1157 {I2->getOperand(OpIdx2), Lane2},
1158 CurrLevel + 1, MaxLevel);
1159 // Look for the best score.
1160 if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1161 MaxTmpScore = TmpScore;
1162 MaxOpIdx2 = OpIdx2;
1163 FoundBest = true;
1164 }
1165 }
1166 if (FoundBest) {
1167 // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1168 Op2Used.insert(MaxOpIdx2);
1169 ShallowScoreAtThisLevel += MaxTmpScore;
1170 }
1171 }
1172 return ShallowScoreAtThisLevel;
1173 }
1174
1175 /// \Returns the look-ahead score, which tells us how much the sub-trees
1176 /// rooted at \p LHS and \p RHS match, the more they match the higher the
1177 /// score. This helps break ties in an informed way when we cannot decide on
1178 /// the order of the operands by just considering the immediate
1179 /// predecessors.
1180 int getLookAheadScore(const std::pair<Value *, int> &LHS,
1181 const std::pair<Value *, int> &RHS) {
1182 InLookAheadValues.clear();
1183 return getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth);
1184 }
1185
1186 // Search all operands in Ops[*][Lane] for the one that matches best
1187 // Ops[OpIdx][LastLane] and return its opreand index.
1188 // If no good match can be found, return None.
1189 Optional<unsigned>
1190 getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1191 ArrayRef<ReorderingMode> ReorderingModes) {
1192 unsigned NumOperands = getNumOperands();
1193
1194 // The operand of the previous lane at OpIdx.
1195 Value *OpLastLane = getData(OpIdx, LastLane).V;
1196
1197 // Our strategy mode for OpIdx.
1198 ReorderingMode RMode = ReorderingModes[OpIdx];
1199
1200 // The linearized opcode of the operand at OpIdx, Lane.
1201 bool OpIdxAPO = getData(OpIdx, Lane).APO;
1202
1203 // The best operand index and its score.
1204 // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1205 // are using the score to differentiate between the two.
1206 struct BestOpData {
1207 Optional<unsigned> Idx = None;
1208 unsigned Score = 0;
1209 } BestOp;
1210
1211 // Iterate through all unused operands and look for the best.
1212 for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1213 // Get the operand at Idx and Lane.
1214 OperandData &OpData = getData(Idx, Lane);
1215 Value *Op = OpData.V;
1216 bool OpAPO = OpData.APO;
1217
1218 // Skip already selected operands.
1219 if (OpData.IsUsed)
1220 continue;
1221
1222 // Skip if we are trying to move the operand to a position with a
1223 // different opcode in the linearized tree form. This would break the
1224 // semantics.
1225 if (OpAPO != OpIdxAPO)
1226 continue;
1227
1228 // Look for an operand that matches the current mode.
1229 switch (RMode) {
1230 case ReorderingMode::Load:
1231 case ReorderingMode::Constant:
1232 case ReorderingMode::Opcode: {
1233 bool LeftToRight = Lane > LastLane;
1234 Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1235 Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1236 unsigned Score =
1237 getLookAheadScore({OpLeft, LastLane}, {OpRight, Lane});
1238 if (Score > BestOp.Score) {
1239 BestOp.Idx = Idx;
1240 BestOp.Score = Score;
1241 }
1242 break;
1243 }
1244 case ReorderingMode::Splat:
1245 if (Op == OpLastLane)
1246 BestOp.Idx = Idx;
1247 break;
1248 case ReorderingMode::Failed:
1249 return None;
1250 }
1251 }
1252
1253 if (BestOp.Idx) {
1254 getData(BestOp.Idx.getValue(), Lane).IsUsed = true;
1255 return BestOp.Idx;
1256 }
1257 // If we could not find a good match return None.
1258 return None;
1259 }
1260
1261 /// Helper for reorderOperandVecs. \Returns the lane that we should start
1262 /// reordering from. This is the one which has the least number of operands
1263 /// that can freely move about.
1264 unsigned getBestLaneToStartReordering() const {
1265 unsigned BestLane = 0;
1266 unsigned Min = UINT_MAX(2147483647 *2U +1U);
1267 for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1268 ++Lane) {
1269 unsigned NumFreeOps = getMaxNumOperandsThatCanBeReordered(Lane);
1270 if (NumFreeOps < Min) {
1271 Min = NumFreeOps;
1272 BestLane = Lane;
1273 }
1274 }
1275 return BestLane;
1276 }
1277
1278 /// \Returns the maximum number of operands that are allowed to be reordered
1279 /// for \p Lane. This is used as a heuristic for selecting the first lane to
1280 /// start operand reordering.
1281 unsigned getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1282 unsigned CntTrue = 0;
1283 unsigned NumOperands = getNumOperands();
1284 // Operands with the same APO can be reordered. We therefore need to count
1285 // how many of them we have for each APO, like this: Cnt[APO] = x.
1286 // Since we only have two APOs, namely true and false, we can avoid using
1287 // a map. Instead we can simply count the number of operands that
1288 // correspond to one of them (in this case the 'true' APO), and calculate
1289 // the other by subtracting it from the total number of operands.
1290 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx)
1291 if (getData(OpIdx, Lane).APO)
1292 ++CntTrue;
1293 unsigned CntFalse = NumOperands - CntTrue;
1294 return std::max(CntTrue, CntFalse);
1295 }
1296
1297 /// Go through the instructions in VL and append their operands.
1298 void appendOperandsOfVL(ArrayRef<Value *> VL) {
1299 assert(!VL.empty() && "Bad VL")(static_cast<void> (0));
1300 assert((empty() || VL.size() == getNumLanes()) &&(static_cast<void> (0))
1301 "Expected same number of lanes")(static_cast<void> (0));
1302 assert(isa<Instruction>(VL[0]) && "Expected instruction")(static_cast<void> (0));
1303 unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1304 OpsVec.resize(NumOperands);
1305 unsigned NumLanes = VL.size();
1306 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1307 OpsVec[OpIdx].resize(NumLanes);
1308 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1309 assert(isa<Instruction>(VL[Lane]) && "Expected instruction")(static_cast<void> (0));
1310 // Our tree has just 3 nodes: the root and two operands.
1311 // It is therefore trivial to get the APO. We only need to check the
1312 // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1313 // RHS operand. The LHS operand of both add and sub is never attached
1314 // to an inversese operation in the linearized form, therefore its APO
1315 // is false. The RHS is true only if VL[Lane] is an inverse operation.
1316
1317 // Since operand reordering is performed on groups of commutative
1318 // operations or alternating sequences (e.g., +, -), we can safely
1319 // tell the inverse operations by checking commutativity.
1320 bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1321 bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1322 OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1323 APO, false};
1324 }
1325 }
1326 }
1327
1328 /// \returns the number of operands.
1329 unsigned getNumOperands() const { return OpsVec.size(); }
1330
1331 /// \returns the number of lanes.
1332 unsigned getNumLanes() const { return OpsVec[0].size(); }
1333
1334 /// \returns the operand value at \p OpIdx and \p Lane.
1335 Value *getValue(unsigned OpIdx, unsigned Lane) const {
1336 return getData(OpIdx, Lane).V;
1337 }
1338
1339 /// \returns true if the data structure is empty.
1340 bool empty() const { return OpsVec.empty(); }
1341
1342 /// Clears the data.
1343 void clear() { OpsVec.clear(); }
1344
1345 /// \Returns true if there are enough operands identical to \p Op to fill
1346 /// the whole vector.
1347 /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1348 bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1349 bool OpAPO = getData(OpIdx, Lane).APO;
1350 for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1351 if (Ln == Lane)
1352 continue;
1353 // This is set to true if we found a candidate for broadcast at Lane.
1354 bool FoundCandidate = false;
1355 for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1356 OperandData &Data = getData(OpI, Ln);
1357 if (Data.APO != OpAPO || Data.IsUsed)
1358 continue;
1359 if (Data.V == Op) {
1360 FoundCandidate = true;
1361 Data.IsUsed = true;
1362 break;
1363 }
1364 }
1365 if (!FoundCandidate)
1366 return false;
1367 }
1368 return true;
1369 }
1370
1371 public:
1372 /// Initialize with all the operands of the instruction vector \p RootVL.
1373 VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1374 ScalarEvolution &SE, const BoUpSLP &R)
1375 : DL(DL), SE(SE), R(R) {
1376 // Append all the operands of RootVL.
1377 appendOperandsOfVL(RootVL);
1378 }
1379
1380 /// \Returns a value vector with the operands across all lanes for the
1381 /// opearnd at \p OpIdx.
1382 ValueList getVL(unsigned OpIdx) const {
1383 ValueList OpVL(OpsVec[OpIdx].size());
1384 assert(OpsVec[OpIdx].size() == getNumLanes() &&(static_cast<void> (0))
1385 "Expected same num of lanes across all operands")(static_cast<void> (0));
1386 for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1387 OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1388 return OpVL;
1389 }
1390
1391 // Performs operand reordering for 2 or more operands.
1392 // The original operands are in OrigOps[OpIdx][Lane].
1393 // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1394 void reorder() {
1395 unsigned NumOperands = getNumOperands();
1396 unsigned NumLanes = getNumLanes();
1397 // Each operand has its own mode. We are using this mode to help us select
1398 // the instructions for each lane, so that they match best with the ones
1399 // we have selected so far.
1400 SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1401
1402 // This is a greedy single-pass algorithm. We are going over each lane
1403 // once and deciding on the best order right away with no back-tracking.
1404 // However, in order to increase its effectiveness, we start with the lane
1405 // that has operands that can move the least. For example, given the
1406 // following lanes:
1407 // Lane 0 : A[0] = B[0] + C[0] // Visited 3rd
1408 // Lane 1 : A[1] = C[1] - B[1] // Visited 1st
1409 // Lane 2 : A[2] = B[2] + C[2] // Visited 2nd
1410 // Lane 3 : A[3] = C[3] - B[3] // Visited 4th
1411 // we will start at Lane 1, since the operands of the subtraction cannot
1412 // be reordered. Then we will visit the rest of the lanes in a circular
1413 // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1414
1415 // Find the first lane that we will start our search from.
1416 unsigned FirstLane = getBestLaneToStartReordering();
1417
1418 // Initialize the modes.
1419 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1420 Value *OpLane0 = getValue(OpIdx, FirstLane);
1421 // Keep track if we have instructions with all the same opcode on one
1422 // side.
1423 if (isa<LoadInst>(OpLane0))
1424 ReorderingModes[OpIdx] = ReorderingMode::Load;
1425 else if (isa<Instruction>(OpLane0)) {
1426 // Check if OpLane0 should be broadcast.
1427 if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1428 ReorderingModes[OpIdx] = ReorderingMode::Splat;
1429 else
1430 ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1431 }
1432 else if (isa<Constant>(OpLane0))
1433 ReorderingModes[OpIdx] = ReorderingMode::Constant;
1434 else if (isa<Argument>(OpLane0))
1435 // Our best hope is a Splat. It may save some cost in some cases.
1436 ReorderingModes[OpIdx] = ReorderingMode::Splat;
1437 else
1438 // NOTE: This should be unreachable.
1439 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1440 }
1441
1442 // If the initial strategy fails for any of the operand indexes, then we
1443 // perform reordering again in a second pass. This helps avoid assigning
1444 // high priority to the failed strategy, and should improve reordering for
1445 // the non-failed operand indexes.
1446 for (int Pass = 0; Pass != 2; ++Pass) {
1447 // Skip the second pass if the first pass did not fail.
1448 bool StrategyFailed = false;
1449 // Mark all operand data as free to use.
1450 clearUsed();
1451 // We keep the original operand order for the FirstLane, so reorder the
1452 // rest of the lanes. We are visiting the nodes in a circular fashion,
1453 // using FirstLane as the center point and increasing the radius
1454 // distance.
1455 for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1456 // Visit the lane on the right and then the lane on the left.
1457 for (int Direction : {+1, -1}) {
1458 int Lane = FirstLane + Direction * Distance;
1459 if (Lane < 0 || Lane >= (int)NumLanes)
1460 continue;
1461 int LastLane = Lane - Direction;
1462 assert(LastLane >= 0 && LastLane < (int)NumLanes &&(static_cast<void> (0))
1463 "Out of bounds")(static_cast<void> (0));
1464 // Look for a good match for each operand.
1465 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1466 // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1467 Optional<unsigned> BestIdx =
1468 getBestOperand(OpIdx, Lane, LastLane, ReorderingModes);
1469 // By not selecting a value, we allow the operands that follow to
1470 // select a better matching value. We will get a non-null value in
1471 // the next run of getBestOperand().
1472 if (BestIdx) {
1473 // Swap the current operand with the one returned by
1474 // getBestOperand().
1475 swap(OpIdx, BestIdx.getValue(), Lane);
1476 } else {
1477 // We failed to find a best operand, set mode to 'Failed'.
1478 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1479 // Enable the second pass.
1480 StrategyFailed = true;
1481 }
1482 }
1483 }
1484 }
1485 // Skip second pass if the strategy did not fail.
1486 if (!StrategyFailed)
1487 break;
1488 }
1489 }
1490
1491#if !defined(NDEBUG1) || defined(LLVM_ENABLE_DUMP)
1492 LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) static StringRef getModeStr(ReorderingMode RMode) {
1493 switch (RMode) {
1494 case ReorderingMode::Load:
1495 return "Load";
1496 case ReorderingMode::Opcode:
1497 return "Opcode";
1498 case ReorderingMode::Constant:
1499 return "Constant";
1500 case ReorderingMode::Splat:
1501 return "Splat";
1502 case ReorderingMode::Failed:
1503 return "Failed";
1504 }
1505 llvm_unreachable("Unimplemented Reordering Type")__builtin_unreachable();
1506 }
1507
1508 LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) static raw_ostream &printMode(ReorderingMode RMode,
1509 raw_ostream &OS) {
1510 return OS << getModeStr(RMode);
1511 }
1512
1513 /// Debug print.
1514 LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) static void dumpMode(ReorderingMode RMode) {
1515 printMode(RMode, dbgs());
1516 }
1517
1518 friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1519 return printMode(RMode, OS);
1520 }
1521
1522 LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) raw_ostream &print(raw_ostream &OS) const {
1523 const unsigned Indent = 2;
1524 unsigned Cnt = 0;
1525 for (const OperandDataVec &OpDataVec : OpsVec) {
1526 OS << "Operand " << Cnt++ << "\n";
1527 for (const OperandData &OpData : OpDataVec) {
1528 OS.indent(Indent) << "{";
1529 if (Value *V = OpData.V)
1530 OS << *V;
1531 else
1532 OS << "null";
1533 OS << ", APO:" << OpData.APO << "}\n";
1534 }
1535 OS << "\n";
1536 }
1537 return OS;
1538 }
1539
1540 /// Debug print.
1541 LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void dump() const { print(dbgs()); }
1542#endif
1543 };
1544
1545 /// Checks if the instruction is marked for deletion.
1546 bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1547
1548 /// Marks values operands for later deletion by replacing them with Undefs.
1549 void eraseInstructions(ArrayRef<Value *> AV);
1550
1551 ~BoUpSLP();
1552
1553private:
1554 /// Checks if all users of \p I are the part of the vectorization tree.
1555 bool areAllUsersVectorized(Instruction *I,
1556 ArrayRef<Value *> VectorizedVals) const;
1557
1558 /// \returns the cost of the vectorizable entry.
1559 InstructionCost getEntryCost(const TreeEntry *E,
1560 ArrayRef<Value *> VectorizedVals);
1561
1562 /// This is the recursive part of buildTree.
1563 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
1564 const EdgeInfo &EI);
1565
1566 /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
1567 /// be vectorized to use the original vector (or aggregate "bitcast" to a
1568 /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
1569 /// returns false, setting \p CurrentOrder to either an empty vector or a
1570 /// non-identity permutation that allows to reuse extract instructions.
1571 bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
1572 SmallVectorImpl<unsigned> &CurrentOrder) const;
1573
1574 /// Vectorize a single entry in the tree.
1575 Value *vectorizeTree(TreeEntry *E);
1576
1577 /// Vectorize a single entry in the tree, starting in \p VL.
1578 Value *vectorizeTree(ArrayRef<Value *> VL);
1579
1580 /// \returns the scalarization cost for this type. Scalarization in this
1581 /// context means the creation of vectors from a group of scalars.
1582 InstructionCost
1583 getGatherCost(FixedVectorType *Ty,
1584 const DenseSet<unsigned> &ShuffledIndices) const;
1585
1586 /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
1587 /// tree entries.
1588 /// \returns ShuffleKind, if gathered values can be represented as shuffles of
1589 /// previous tree entries. \p Mask is filled with the shuffle mask.
1590 Optional<TargetTransformInfo::ShuffleKind>
1591 isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
1592 SmallVectorImpl<const TreeEntry *> &Entries);
1593
1594 /// \returns the scalarization cost for this list of values. Assuming that
1595 /// this subtree gets vectorized, we may need to extract the values from the
1596 /// roots. This method calculates the cost of extracting the values.
1597 InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
1598
1599 /// Set the Builder insert point to one after the last instruction in
1600 /// the bundle
1601 void setInsertPointAfterBundle(const TreeEntry *E);
1602
1603 /// \returns a vector from a collection of scalars in \p VL.
1604 Value *gather(ArrayRef<Value *> VL);
1605
1606 /// \returns whether the VectorizableTree is fully vectorizable and will
1607 /// be beneficial even the tree height is tiny.
1608 bool isFullyVectorizableTinyTree() const;
1609
1610 /// Reorder commutative or alt operands to get better probability of
1611 /// generating vectorized code.
1612 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
1613 SmallVectorImpl<Value *> &Left,
1614 SmallVectorImpl<Value *> &Right,
1615 const DataLayout &DL,
1616 ScalarEvolution &SE,
1617 const BoUpSLP &R);
1618 struct TreeEntry {
1619 using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
1620 TreeEntry(VecTreeTy &Container) : Container(Container) {}
1621
1622 /// \returns true if the scalars in VL are equal to this entry.
1623 bool isSame(ArrayRef<Value *> VL) const {
1624 if (VL.size() == Scalars.size())
1625 return std::equal(VL.begin(), VL.end(), Scalars.begin());
1626 return VL.size() == ReuseShuffleIndices.size() &&
1627 std::equal(
1628 VL.begin(), VL.end(), ReuseShuffleIndices.begin(),
1629 [this](Value *V, int Idx) { return V == Scalars[Idx]; });
1630 }
1631
1632 /// A vector of scalars.
1633 ValueList Scalars;
1634
1635 /// The Scalars are vectorized into this value. It is initialized to Null.
1636 Value *VectorizedValue = nullptr;
1637
1638 /// Do we need to gather this sequence or vectorize it
1639 /// (either with vector instruction or with scatter/gather
1640 /// intrinsics for store/load)?
1641 enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
1642 EntryState State;
1643
1644 /// Does this sequence require some shuffling?
1645 SmallVector<int, 4> ReuseShuffleIndices;
1646
1647 /// Does this entry require reordering?
1648 SmallVector<unsigned, 4> ReorderIndices;
1649
1650 /// Points back to the VectorizableTree.
1651 ///
1652 /// Only used for Graphviz right now. Unfortunately GraphTrait::NodeRef has
1653 /// to be a pointer and needs to be able to initialize the child iterator.
1654 /// Thus we need a reference back to the container to translate the indices
1655 /// to entries.
1656 VecTreeTy &Container;
1657
1658 /// The TreeEntry index containing the user of this entry. We can actually
1659 /// have multiple users so the data structure is not truly a tree.
1660 SmallVector<EdgeInfo, 1> UserTreeIndices;
1661
1662 /// The index of this treeEntry in VectorizableTree.
1663 int Idx = -1;
1664
1665 private:
1666 /// The operands of each instruction in each lane Operands[op_index][lane].
1667 /// Note: This helps avoid the replication of the code that performs the
1668 /// reordering of operands during buildTree_rec() and vectorizeTree().
1669 SmallVector<ValueList, 2> Operands;
1670
1671 /// The main/alternate instruction.
1672 Instruction *MainOp = nullptr;
1673 Instruction *AltOp = nullptr;
1674
1675 public:
1676 /// Set this bundle's \p OpIdx'th operand to \p OpVL.
1677 void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
1678 if (Operands.size() < OpIdx + 1)
1679 Operands.resize(OpIdx + 1);
1680 assert(Operands[OpIdx].empty() && "Already resized?")(static_cast<void> (0));
1681 Operands[OpIdx].resize(Scalars.size());
1682 for (unsigned Lane = 0, E = Scalars.size(); Lane != E; ++Lane)
1683 Operands[OpIdx][Lane] = OpVL[Lane];
1684 }
1685
1686 /// Set the operands of this bundle in their original order.
1687 void setOperandsInOrder() {
1688 assert(Operands.empty() && "Already initialized?")(static_cast<void> (0));
1689 auto *I0 = cast<Instruction>(Scalars[0]);
1690 Operands.resize(I0->getNumOperands());
1691 unsigned NumLanes = Scalars.size();
1692 for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
1693 OpIdx != NumOperands; ++OpIdx) {
1694 Operands[OpIdx].resize(NumLanes);
1695 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1696 auto *I = cast<Instruction>(Scalars[Lane]);
1697 assert(I->getNumOperands() == NumOperands &&(static_cast<void> (0))
1698 "Expected same number of operands")(static_cast<void> (0));
1699 Operands[OpIdx][Lane] = I->getOperand(OpIdx);
1700 }
1701 }
1702 }
1703
1704 /// \returns the \p OpIdx operand of this TreeEntry.
1705 ValueList &getOperand(unsigned OpIdx) {
1706 assert(OpIdx < Operands.size() && "Off bounds")(static_cast<void> (0));
1707 return Operands[OpIdx];
1708 }
1709
1710 /// \returns the number of operands.
1711 unsigned getNumOperands() const { return Operands.size(); }
1712
1713 /// \return the single \p OpIdx operand.
1714 Value *getSingleOperand(unsigned OpIdx) const {
1715 assert(OpIdx < Operands.size() && "Off bounds")(static_cast<void> (0));
1716 assert(!Operands[OpIdx].empty() && "No operand available")(static_cast<void> (0));
1717 return Operands[OpIdx][0];
1718 }
1719
1720 /// Some of the instructions in the list have alternate opcodes.
1721 bool isAltShuffle() const {
1722 return getOpcode() != getAltOpcode();
1723 }
1724
1725 bool isOpcodeOrAlt(Instruction *I) const {
1726 unsigned CheckedOpcode = I->getOpcode();
1727 return (getOpcode() == CheckedOpcode ||
1728 getAltOpcode() == CheckedOpcode);
1729 }
1730
1731 /// Chooses the correct key for scheduling data. If \p Op has the same (or
1732 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
1733 /// \p OpValue.
1734 Value *isOneOf(Value *Op) const {
1735 auto *I = dyn_cast<Instruction>(Op);
1736 if (I && isOpcodeOrAlt(I))
1737 return Op;
1738 return MainOp;
1739 }
1740
1741 void setOperations(const InstructionsState &S) {
1742 MainOp = S.MainOp;
1743 AltOp = S.AltOp;
1744 }
1745
1746 Instruction *getMainOp() const {
1747 return MainOp;
1748 }
1749
1750 Instruction *getAltOp() const {
1751 return AltOp;
1752 }
1753
1754 /// The main/alternate opcodes for the list of instructions.
1755 unsigned getOpcode() const {
1756 return MainOp ? MainOp->getOpcode() : 0;
1757 }
1758
1759 unsigned getAltOpcode() const {
1760 return AltOp ? AltOp->getOpcode() : 0;
1761 }
1762
1763 /// Update operations state of this entry if reorder occurred.
1764 bool updateStateIfReorder() {
1765 if (ReorderIndices.empty())
1766 return false;
1767 InstructionsState S = getSameOpcode(Scalars, ReorderIndices.front());
1768 setOperations(S);
1769 return true;
1770 }
1771 /// When ReuseShuffleIndices is empty it just returns position of \p V
1772 /// within vector of Scalars. Otherwise, try to remap on its reuse index.
1773 int findLaneForValue(Value *V) const {
1774 unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
1775 assert(FoundLane < Scalars.size() && "Couldn't find extract lane")(static_cast<void> (0));
1776 if (!ReuseShuffleIndices.empty()) {
1777 FoundLane = std::distance(ReuseShuffleIndices.begin(),
1778 find(ReuseShuffleIndices, FoundLane));
1779 }
1780 return FoundLane;
1781 }
1782
1783#ifndef NDEBUG1
1784 /// Debug printer.
1785 LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void dump() const {
1786 dbgs() << Idx << ".\n";
1787 for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
1788 dbgs() << "Operand " << OpI << ":\n";
1789 for (const Value *V : Operands[OpI])
1790 dbgs().indent(2) << *V << "\n";
1791 }
1792 dbgs() << "Scalars: \n";
1793 for (Value *V : Scalars)
1794 dbgs().indent(2) << *V << "\n";
1795 dbgs() << "State: ";
1796 switch (State) {
1797 case Vectorize:
1798 dbgs() << "Vectorize\n";
1799 break;
1800 case ScatterVectorize:
1801 dbgs() << "ScatterVectorize\n";
1802 break;
1803 case NeedToGather:
1804 dbgs() << "NeedToGather\n";
1805 break;
1806 }
1807 dbgs() << "MainOp: ";
1808 if (MainOp)
1809 dbgs() << *MainOp << "\n";
1810 else
1811 dbgs() << "NULL\n";
1812 dbgs() << "AltOp: ";
1813 if (AltOp)
1814 dbgs() << *AltOp << "\n";
1815 else
1816 dbgs() << "NULL\n";
1817 dbgs() << "VectorizedValue: ";
1818 if (VectorizedValue)
1819 dbgs() << *VectorizedValue << "\n";
1820 else
1821 dbgs() << "NULL\n";
1822 dbgs() << "ReuseShuffleIndices: ";
1823 if (ReuseShuffleIndices.empty())
1824 dbgs() << "Empty";
1825 else
1826 for (unsigned ReuseIdx : ReuseShuffleIndices)
1827 dbgs() << ReuseIdx << ", ";
1828 dbgs() << "\n";
1829 dbgs() << "ReorderIndices: ";
1830 for (unsigned ReorderIdx : ReorderIndices)
1831 dbgs() << ReorderIdx << ", ";
1832 dbgs() << "\n";
1833 dbgs() << "UserTreeIndices: ";
1834 for (const auto &EInfo : UserTreeIndices)
1835 dbgs() << EInfo << ", ";
1836 dbgs() << "\n";
1837 }
1838#endif
1839 };
1840
1841#ifndef NDEBUG1
1842 void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
1843 InstructionCost VecCost,
1844 InstructionCost ScalarCost) const {
1845 dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
1846 dbgs() << "SLP: Costs:\n";
1847 dbgs() << "SLP: ReuseShuffleCost = " << ReuseShuffleCost << "\n";
1848 dbgs() << "SLP: VectorCost = " << VecCost << "\n";
1849 dbgs() << "SLP: ScalarCost = " << ScalarCost << "\n";
1850 dbgs() << "SLP: ReuseShuffleCost + VecCost - ScalarCost = " <<
1851 ReuseShuffleCost + VecCost - ScalarCost << "\n";
1852 }
1853#endif
1854
1855 /// Create a new VectorizableTree entry.
1856 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
1857 const InstructionsState &S,
1858 const EdgeInfo &UserTreeIdx,
1859 ArrayRef<unsigned> ReuseShuffleIndices = None,
1860 ArrayRef<unsigned> ReorderIndices = None) {
1861 TreeEntry::EntryState EntryState =
1862 Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
1863 return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
1864 ReuseShuffleIndices, ReorderIndices);
1865 }
1866
1867 TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
1868 TreeEntry::EntryState EntryState,
1869 Optional<ScheduleData *> Bundle,
1870 const InstructionsState &S,
1871 const EdgeInfo &UserTreeIdx,
1872 ArrayRef<unsigned> ReuseShuffleIndices = None,
1873 ArrayRef<unsigned> ReorderIndices = None) {
1874 assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||(static_cast<void> (0))
1875 (Bundle && EntryState != TreeEntry::NeedToGather)) &&(static_cast<void> (0))
1876 "Need to vectorize gather entry?")(static_cast<void> (0));
1877 VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
1878 TreeEntry *Last = VectorizableTree.back().get();
1879 Last->Idx = VectorizableTree.size() - 1;
1880 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
1881 Last->State = EntryState;
1882 Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
1883 ReuseShuffleIndices.end());
1884 Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
1885 Last->setOperations(S);
1886 if (Last->State != TreeEntry::NeedToGather) {
1887 for (Value *V : VL) {
1888 assert(!getTreeEntry(V) && "Scalar already in tree!")(static_cast<void> (0));
1889 ScalarToTreeEntry[V] = Last;
1890 }
1891 // Update the scheduler bundle to point to this TreeEntry.
1892 unsigned Lane = 0;
1893 for (ScheduleData *BundleMember = Bundle.getValue(); BundleMember;
1894 BundleMember = BundleMember->NextInBundle) {
1895 BundleMember->TE = Last;
1896 BundleMember->Lane = Lane;
1897 ++Lane;
1898 }
1899 assert((!Bundle.getValue() || Lane == VL.size()) &&(static_cast<void> (0))
1900 "Bundle and VL out of sync")(static_cast<void> (0));
1901 } else {
1902 MustGather.insert(VL.begin(), VL.end());
1903 }
1904
1905 if (UserTreeIdx.UserTE)
1906 Last->UserTreeIndices.push_back(UserTreeIdx);
1907
1908 return Last;
1909 }
1910
1911 /// -- Vectorization State --
1912 /// Holds all of the tree entries.
1913 TreeEntry::VecTreeTy VectorizableTree;
1914
1915#ifndef NDEBUG1
1916 /// Debug printer.
1917 LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void dumpVectorizableTree() const {
1918 for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
1919 VectorizableTree[Id]->dump();
1920 dbgs() << "\n";
1921 }
1922 }
1923#endif
1924
1925 TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
1926
1927 const TreeEntry *getTreeEntry(Value *V) const {
1928 return ScalarToTreeEntry.lookup(V);
1929 }
1930
1931 /// Maps a specific scalar to its tree entry.
1932 SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
1933
1934 /// Maps a value to the proposed vectorizable size.
1935 SmallDenseMap<Value *, unsigned> InstrElementSize;
1936
1937 /// A list of scalars that we found that we need to keep as scalars.
1938 ValueSet MustGather;
1939
1940 /// This POD struct describes one external user in the vectorized tree.
1941 struct ExternalUser {
1942 ExternalUser(Value *S, llvm::User *U, int L)
1943 : Scalar(S), User(U), Lane(L) {}
1944
1945 // Which scalar in our function.
1946 Value *Scalar;
1947
1948 // Which user that uses the scalar.
1949 llvm::User *User;
1950
1951 // Which lane does the scalar belong to.
1952 int Lane;
1953 };
1954 using UserList = SmallVector<ExternalUser, 16>;
1955
1956 /// Checks if two instructions may access the same memory.
1957 ///
1958 /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
1959 /// is invariant in the calling loop.
1960 bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
1961 Instruction *Inst2) {
1962 // First check if the result is already in the cache.
1963 AliasCacheKey key = std::make_pair(Inst1, Inst2);
1964 Optional<bool> &result = AliasCache[key];
1965 if (result.hasValue()) {
1966 return result.getValue();
1967 }
1968 bool aliased = true;
1969 if (Loc1.Ptr && isSimple(Inst1))
1970 aliased = isModOrRefSet(AA->getModRefInfo(Inst2, Loc1));
1971 // Store the result in the cache.
1972 result = aliased;
1973 return aliased;
1974 }
1975
1976 using AliasCacheKey = std::pair<Instruction *, Instruction *>;
1977
1978 /// Cache for alias results.
1979 /// TODO: consider moving this to the AliasAnalysis itself.
1980 DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
1981
1982 /// Removes an instruction from its block and eventually deletes it.
1983 /// It's like Instruction::eraseFromParent() except that the actual deletion
1984 /// is delayed until BoUpSLP is destructed.
1985 /// This is required to ensure that there are no incorrect collisions in the
1986 /// AliasCache, which can happen if a new instruction is allocated at the
1987 /// same address as a previously deleted instruction.
1988 void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
1989 auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
1990 It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
1991 }
1992
1993 /// Temporary store for deleted instructions. Instructions will be deleted
1994 /// eventually when the BoUpSLP is destructed.
1995 DenseMap<Instruction *, bool> DeletedInstructions;
1996
1997 /// A list of values that need to extracted out of the tree.
1998 /// This list holds pairs of (Internal Scalar : External User). External User
1999 /// can be nullptr, it means that this Internal Scalar will be used later,
2000 /// after vectorization.
2001 UserList ExternalUses;
2002
2003 /// Values used only by @llvm.assume calls.
2004 SmallPtrSet<const Value *, 32> EphValues;
2005
2006 /// Holds all of the instructions that we gathered.
2007 SetVector<Instruction *> GatherSeq;
2008
2009 /// A list of blocks that we are going to CSE.
2010 SetVector<BasicBlock *> CSEBlocks;
2011
2012 /// Contains all scheduling relevant data for an instruction.
2013 /// A ScheduleData either represents a single instruction or a member of an
2014 /// instruction bundle (= a group of instructions which is combined into a
2015 /// vector instruction).
2016 struct ScheduleData {
2017 // The initial value for the dependency counters. It means that the
2018 // dependencies are not calculated yet.
2019 enum { InvalidDeps = -1 };
2020
2021 ScheduleData() = default;
2022
2023 void init(int BlockSchedulingRegionID, Value *OpVal) {
2024 FirstInBundle = this;
2025 NextInBundle = nullptr;
2026 NextLoadStore = nullptr;
2027 IsScheduled = false;
2028 SchedulingRegionID = BlockSchedulingRegionID;
2029 UnscheduledDepsInBundle = UnscheduledDeps;
2030 clearDependencies();
2031 OpValue = OpVal;
2032 TE = nullptr;
2033 Lane = -1;
2034 }
2035
2036 /// Returns true if the dependency information has been calculated.
2037 bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2038
2039 /// Returns true for single instructions and for bundle representatives
2040 /// (= the head of a bundle).
2041 bool isSchedulingEntity() const { return FirstInBundle == this; }
2042
2043 /// Returns true if it represents an instruction bundle and not only a
2044 /// single instruction.
2045 bool isPartOfBundle() const {
2046 return NextInBundle != nullptr || FirstInBundle != this;
2047 }
2048
2049 /// Returns true if it is ready for scheduling, i.e. it has no more
2050 /// unscheduled depending instructions/bundles.
2051 bool isReady() const {
2052 assert(isSchedulingEntity() &&(static_cast<void> (0))
2053 "can't consider non-scheduling entity for ready list")(static_cast<void> (0));
2054 return UnscheduledDepsInBundle == 0 && !IsScheduled;
2055 }
2056
2057 /// Modifies the number of unscheduled dependencies, also updating it for
2058 /// the whole bundle.
2059 int incrementUnscheduledDeps(int Incr) {
2060 UnscheduledDeps += Incr;
2061 return FirstInBundle->UnscheduledDepsInBundle += Incr;
2062 }
2063
2064 /// Sets the number of unscheduled dependencies to the number of
2065 /// dependencies.
2066 void resetUnscheduledDeps() {
2067 incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
2068 }
2069
2070 /// Clears all dependency information.
2071 void clearDependencies() {
2072 Dependencies = InvalidDeps;
2073 resetUnscheduledDeps();
2074 MemoryDependencies.clear();
2075 }
2076
2077 void dump(raw_ostream &os) const {
2078 if (!isSchedulingEntity()) {
2079 os << "/ " << *Inst;
2080 } else if (NextInBundle) {
2081 os << '[' << *Inst;
2082 ScheduleData *SD = NextInBundle;
2083 while (SD) {
2084 os << ';' << *SD->Inst;
2085 SD = SD->NextInBundle;
2086 }
2087 os << ']';
2088 } else {
2089 os << *Inst;
2090 }
2091 }
2092
2093 Instruction *Inst = nullptr;
2094
2095 /// Points to the head in an instruction bundle (and always to this for
2096 /// single instructions).
2097 ScheduleData *FirstInBundle = nullptr;
2098
2099 /// Single linked list of all instructions in a bundle. Null if it is a
2100 /// single instruction.
2101 ScheduleData *NextInBundle = nullptr;
2102
2103 /// Single linked list of all memory instructions (e.g. load, store, call)
2104 /// in the block - until the end of the scheduling region.
2105 ScheduleData *NextLoadStore = nullptr;
2106
2107 /// The dependent memory instructions.
2108 /// This list is derived on demand in calculateDependencies().
2109 SmallVector<ScheduleData *, 4> MemoryDependencies;
2110
2111 /// This ScheduleData is in the current scheduling region if this matches
2112 /// the current SchedulingRegionID of BlockScheduling.
2113 int SchedulingRegionID = 0;
2114
2115 /// Used for getting a "good" final ordering of instructions.
2116 int SchedulingPriority = 0;
2117
2118 /// The number of dependencies. Constitutes of the number of users of the
2119 /// instruction plus the number of dependent memory instructions (if any).
2120 /// This value is calculated on demand.
2121 /// If InvalidDeps, the number of dependencies is not calculated yet.
2122 int Dependencies = InvalidDeps;
2123
2124 /// The number of dependencies minus the number of dependencies of scheduled
2125 /// instructions. As soon as this is zero, the instruction/bundle gets ready
2126 /// for scheduling.
2127 /// Note that this is negative as long as Dependencies is not calculated.
2128 int UnscheduledDeps = InvalidDeps;
2129
2130 /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
2131 /// single instructions.
2132 int UnscheduledDepsInBundle = InvalidDeps;
2133
2134 /// True if this instruction is scheduled (or considered as scheduled in the
2135 /// dry-run).
2136 bool IsScheduled = false;
2137
2138 /// Opcode of the current instruction in the schedule data.
2139 Value *OpValue = nullptr;
2140
2141 /// The TreeEntry that this instruction corresponds to.
2142 TreeEntry *TE = nullptr;
2143
2144 /// The lane of this node in the TreeEntry.
2145 int Lane = -1;
2146 };
2147
2148#ifndef NDEBUG1
2149 friend inline raw_ostream &operator<<(raw_ostream &os,
2150 const BoUpSLP::ScheduleData &SD) {
2151 SD.dump(os);
2152 return os;
2153 }
2154#endif
2155
2156 friend struct GraphTraits<BoUpSLP *>;
2157 friend struct DOTGraphTraits<BoUpSLP *>;
2158
2159 /// Contains all scheduling data for a basic block.
2160 struct BlockScheduling {
2161 BlockScheduling(BasicBlock *BB)
2162 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2163
2164 void clear() {
2165 ReadyInsts.clear();
2166 ScheduleStart = nullptr;
2167 ScheduleEnd = nullptr;
2168 FirstLoadStoreInRegion = nullptr;
2169 LastLoadStoreInRegion = nullptr;
2170
2171 // Reduce the maximum schedule region size by the size of the
2172 // previous scheduling run.
2173 ScheduleRegionSizeLimit -= ScheduleRegionSize;
2174 if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2175 ScheduleRegionSizeLimit = MinScheduleRegionSize;
2176 ScheduleRegionSize = 0;
2177
2178 // Make a new scheduling region, i.e. all existing ScheduleData is not
2179 // in the new region yet.
2180 ++SchedulingRegionID;
2181 }
2182
2183 ScheduleData *getScheduleData(Value *V) {
2184 ScheduleData *SD = ScheduleDataMap[V];
15
Value assigned to field 'ScheduleStart', which participates in a condition later
2185 if (SD && SD->SchedulingRegionID == SchedulingRegionID)
5
Assuming 'SD' is null
16
Assuming 'SD' is null
2186 return SD;
2187 return nullptr;
6
Returning null pointer, which participates in a condition later
17
Returning null pointer, which participates in a condition later
2188 }
2189
2190 ScheduleData *getScheduleData(Value *V, Value *Key) {
2191 if (V == Key)
2
Assuming 'V' is equal to 'Key'
3
Taking true branch
2192 return getScheduleData(V);
4
Calling 'BlockScheduling::getScheduleData'
7
Returning from 'BlockScheduling::getScheduleData'
8
Returning null pointer, which participates in a condition later
2193 auto I = ExtraScheduleDataMap.find(V);
2194 if (I != ExtraScheduleDataMap.end()) {
2195 ScheduleData *SD = I->second[Key];
2196 if (SD && SD->SchedulingRegionID == SchedulingRegionID)
2197 return SD;
2198 }
2199 return nullptr;
2200 }
2201
2202 bool isInSchedulingRegion(ScheduleData *SD) const {
2203 return SD->SchedulingRegionID == SchedulingRegionID;
2204 }
2205
2206 /// Marks an instruction as scheduled and puts all dependent ready
2207 /// instructions into the ready-list.
2208 template <typename ReadyListType>
2209 void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2210 SD->IsScheduled = true;
2211 LLVM_DEBUG(dbgs() << "SLP: schedule " << *SD << "\n")do { } while (false);
2212
2213 ScheduleData *BundleMember = SD;
2214 while (BundleMember) {
2215 if (BundleMember->Inst != BundleMember->OpValue) {
2216 BundleMember = BundleMember->NextInBundle;
2217 continue;
2218 }
2219 // Handle the def-use chain dependencies.
2220
2221 // Decrement the unscheduled counter and insert to ready list if ready.
2222 auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2223 doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2224 if (OpDef && OpDef->hasValidDependencies() &&
2225 OpDef->incrementUnscheduledDeps(-1) == 0) {
2226 // There are no more unscheduled dependencies after
2227 // decrementing, so we can put the dependent instruction
2228 // into the ready list.
2229 ScheduleData *DepBundle = OpDef->FirstInBundle;
2230 assert(!DepBundle->IsScheduled &&(static_cast<void> (0))
2231 "already scheduled bundle gets ready")(static_cast<void> (0));
2232 ReadyList.insert(DepBundle);
2233 LLVM_DEBUG(dbgs()do { } while (false)
2234 << "SLP: gets ready (def): " << *DepBundle << "\n")do { } while (false);
2235 }
2236 });
2237 };
2238
2239 // If BundleMember is a vector bundle, its operands may have been
2240 // reordered duiring buildTree(). We therefore need to get its operands
2241 // through the TreeEntry.
2242 if (TreeEntry *TE = BundleMember->TE) {
2243 int Lane = BundleMember->Lane;
2244 assert(Lane >= 0 && "Lane not set")(static_cast<void> (0));
2245
2246 // Since vectorization tree is being built recursively this assertion
2247 // ensures that the tree entry has all operands set before reaching
2248 // this code. Couple of exceptions known at the moment are extracts
2249 // where their second (immediate) operand is not added. Since
2250 // immediates do not affect scheduler behavior this is considered
2251 // okay.
2252 auto *In = TE->getMainOp();
2253 assert(In &&(static_cast<void> (0))
2254 (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||(static_cast<void> (0))
2255 In->getNumOperands() == TE->getNumOperands()) &&(static_cast<void> (0))
2256 "Missed TreeEntry operands?")(static_cast<void> (0));
2257 (void)In; // fake use to avoid build failure when assertions disabled
2258
2259 for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2260 OpIdx != NumOperands; ++OpIdx)
2261 if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2262 DecrUnsched(I);
2263 } else {
2264 // If BundleMember is a stand-alone instruction, no operand reordering
2265 // has taken place, so we directly access its operands.
2266 for (Use &U : BundleMember->Inst->operands())
2267 if (auto *I = dyn_cast<Instruction>(U.get()))
2268 DecrUnsched(I);
2269 }
2270 // Handle the memory dependencies.
2271 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2272 if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2273 // There are no more unscheduled dependencies after decrementing,
2274 // so we can put the dependent instruction into the ready list.
2275 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2276 assert(!DepBundle->IsScheduled &&(static_cast<void> (0))
2277 "already scheduled bundle gets ready")(static_cast<void> (0));
2278 ReadyList.insert(DepBundle);
2279 LLVM_DEBUG(dbgs()do { } while (false)
2280 << "SLP: gets ready (mem): " << *DepBundle << "\n")do { } while (false);
2281 }
2282 }
2283 BundleMember = BundleMember->NextInBundle;
2284 }
2285 }
2286
2287 void doForAllOpcodes(Value *V,
2288 function_ref<void(ScheduleData *SD)> Action) {
2289 if (ScheduleData *SD = getScheduleData(V))
2290 Action(SD);
2291 auto I = ExtraScheduleDataMap.find(V);
2292 if (I != ExtraScheduleDataMap.end())
2293 for (auto &P : I->second)
2294 if (P.second->SchedulingRegionID == SchedulingRegionID)
2295 Action(P.second);
2296 }
2297
2298 /// Put all instructions into the ReadyList which are ready for scheduling.
2299 template <typename ReadyListType>
2300 void initialFillReadyList(ReadyListType &ReadyList) {
2301 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2302 doForAllOpcodes(I, [&](ScheduleData *SD) {
2303 if (SD->isSchedulingEntity() && SD->isReady()) {
2304 ReadyList.insert(SD);
2305 LLVM_DEBUG(dbgs()do { } while (false)
2306 << "SLP: initially in ready list: " << *I << "\n")do { } while (false);
2307 }
2308 });
2309 }
2310 }
2311
2312 /// Checks if a bundle of instructions can be scheduled, i.e. has no
2313 /// cyclic dependencies. This is only a dry-run, no instructions are
2314 /// actually moved at this stage.
2315 /// \returns the scheduling bundle. The returned Optional value is non-None
2316 /// if \p VL is allowed to be scheduled.
2317 Optional<ScheduleData *>
2318 tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2319 const InstructionsState &S);
2320
2321 /// Un-bundles a group of instructions.
2322 void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2323
2324 /// Allocates schedule data chunk.
2325 ScheduleData *allocateScheduleDataChunks();
2326
2327 /// Extends the scheduling region so that V is inside the region.
2328 /// \returns true if the region size is within the limit.
2329 bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2330
2331 /// Initialize the ScheduleData structures for new instructions in the
2332 /// scheduling region.
2333 void initScheduleData(Instruction *FromI, Instruction *ToI,
2334 ScheduleData *PrevLoadStore,
2335 ScheduleData *NextLoadStore);
2336
2337 /// Updates the dependency information of a bundle and of all instructions/
2338 /// bundles which depend on the original bundle.
2339 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2340 BoUpSLP *SLP);
2341
2342 /// Sets all instruction in the scheduling region to un-scheduled.
2343 void resetSchedule();
2344
2345 BasicBlock *BB;
2346
2347 /// Simple memory allocation for ScheduleData.
2348 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2349
2350 /// The size of a ScheduleData array in ScheduleDataChunks.
2351 int ChunkSize;
2352
2353 /// The allocator position in the current chunk, which is the last entry
2354 /// of ScheduleDataChunks.
2355 int ChunkPos;
2356
2357 /// Attaches ScheduleData to Instruction.
2358 /// Note that the mapping survives during all vectorization iterations, i.e.
2359 /// ScheduleData structures are recycled.
2360 DenseMap<Value *, ScheduleData *> ScheduleDataMap;
2361
2362 /// Attaches ScheduleData to Instruction with the leading key.
2363 DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
2364 ExtraScheduleDataMap;
2365
2366 struct ReadyList : SmallVector<ScheduleData *, 8> {
2367 void insert(ScheduleData *SD) { push_back(SD); }
2368 };
2369
2370 /// The ready-list for scheduling (only used for the dry-run).
2371 ReadyList ReadyInsts;
2372
2373 /// The first instruction of the scheduling region.
2374 Instruction *ScheduleStart = nullptr;
2375
2376 /// The first instruction _after_ the scheduling region.
2377 Instruction *ScheduleEnd = nullptr;
2378
2379 /// The first memory accessing instruction in the scheduling region
2380 /// (can be null).
2381 ScheduleData *FirstLoadStoreInRegion = nullptr;
2382
2383 /// The last memory accessing instruction in the scheduling region
2384 /// (can be null).
2385 ScheduleData *LastLoadStoreInRegion = nullptr;
2386
2387 /// The current size of the scheduling region.
2388 int ScheduleRegionSize = 0;
2389
2390 /// The maximum size allowed for the scheduling region.
2391 int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
2392
2393 /// The ID of the scheduling region. For a new vectorization iteration this
2394 /// is incremented which "removes" all ScheduleData from the region.
2395 // Make sure that the initial SchedulingRegionID is greater than the
2396 // initial SchedulingRegionID in ScheduleData (which is 0).
2397 int SchedulingRegionID = 1;
2398 };
2399
2400 /// Attaches the BlockScheduling structures to basic blocks.
2401 MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
2402
2403 /// Performs the "real" scheduling. Done before vectorization is actually
2404 /// performed in a basic block.
2405 void scheduleBlock(BlockScheduling *BS);
2406
2407 /// List of users to ignore during scheduling and that don't need extracting.
2408 ArrayRef<Value *> UserIgnoreList;
2409
2410 /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
2411 /// sorted SmallVectors of unsigned.
2412 struct OrdersTypeDenseMapInfo {
2413 static OrdersType getEmptyKey() {
2414 OrdersType V;
2415 V.push_back(~1U);
2416 return V;
2417 }
2418
2419 static OrdersType getTombstoneKey() {
2420 OrdersType V;
2421 V.push_back(~2U);
2422 return V;
2423 }
2424
2425 static unsigned getHashValue(const OrdersType &V) {
2426 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
2427 }
2428
2429 static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
2430 return LHS == RHS;
2431 }
2432 };
2433
2434 /// Contains orders of operations along with the number of bundles that have
2435 /// operations in this order. It stores only those orders that require
2436 /// reordering, if reordering is not required it is counted using \a
2437 /// NumOpsWantToKeepOriginalOrder.
2438 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo> NumOpsWantToKeepOrder;
2439 /// Number of bundles that do not require reordering.
2440 unsigned NumOpsWantToKeepOriginalOrder = 0;
2441
2442 // Analysis and block reference.
2443 Function *F;
2444 ScalarEvolution *SE;
2445 TargetTransformInfo *TTI;
2446 TargetLibraryInfo *TLI;
2447 AAResults *AA;
2448 LoopInfo *LI;
2449 DominatorTree *DT;
2450 AssumptionCache *AC;
2451 DemandedBits *DB;
2452 const DataLayout *DL;
2453 OptimizationRemarkEmitter *ORE;
2454
2455 unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
2456 unsigned MinVecRegSize; // Set by cl::opt (default: 128).
2457
2458 /// Instruction builder to construct the vectorized tree.
2459 IRBuilder<> Builder;
2460
2461 /// A map of scalar integer values to the smallest bit width with which they
2462 /// can legally be represented. The values map to (width, signed) pairs,
2463 /// where "width" indicates the minimum bit width and "signed" is True if the
2464 /// value must be signed-extended, rather than zero-extended, back to its
2465 /// original width.
2466 MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
2467};
2468
2469} // end namespace slpvectorizer
2470
2471template <> struct GraphTraits<BoUpSLP *> {
2472 using TreeEntry = BoUpSLP::TreeEntry;
2473
2474 /// NodeRef has to be a pointer per the GraphWriter.
2475 using NodeRef = TreeEntry *;
2476
2477 using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
2478
2479 /// Add the VectorizableTree to the index iterator to be able to return
2480 /// TreeEntry pointers.
2481 struct ChildIteratorType
2482 : public iterator_adaptor_base<
2483 ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
2484 ContainerTy &VectorizableTree;
2485
2486 ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
2487 ContainerTy &VT)
2488 : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
2489
2490 NodeRef operator*() { return I->UserTE; }
2491 };
2492
2493 static NodeRef getEntryNode(BoUpSLP &R) {
2494 return R.VectorizableTree[0].get();
2495 }
2496
2497 static ChildIteratorType child_begin(NodeRef N) {
2498 return {N->UserTreeIndices.begin(), N->Container};
2499 }
2500
2501 static ChildIteratorType child_end(NodeRef N) {
2502 return {N->UserTreeIndices.end(), N->Container};
2503 }
2504
2505 /// For the node iterator we just need to turn the TreeEntry iterator into a
2506 /// TreeEntry* iterator so that it dereferences to NodeRef.
2507 class nodes_iterator {
2508 using ItTy = ContainerTy::iterator;
2509 ItTy It;
2510
2511 public:
2512 nodes_iterator(const ItTy &It2) : It(It2) {}
2513 NodeRef operator*() { return It->get(); }
2514 nodes_iterator operator++() {
2515 ++It;
2516 return *this;
2517 }
2518 bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
2519 };
2520
2521 static nodes_iterator nodes_begin(BoUpSLP *R) {
2522 return nodes_iterator(R->VectorizableTree.begin());
2523 }
2524
2525 static nodes_iterator nodes_end(BoUpSLP *R) {
2526 return nodes_iterator(R->VectorizableTree.end());
2527 }
2528
2529 static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
2530};
2531
2532template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
2533 using TreeEntry = BoUpSLP::TreeEntry;
2534
2535 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
2536
2537 std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
2538 std::string Str;
2539 raw_string_ostream OS(Str);
2540 if (isSplat(Entry->Scalars)) {
2541 OS << "<splat> " << *Entry->Scalars[0];
2542 return Str;
2543 }
2544 for (auto V : Entry->Scalars) {
2545 OS << *V;
2546 if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
2547 return EU.Scalar == V;
2548 }))
2549 OS << " <extract>";
2550 OS << "\n";
2551 }
2552 return Str;
2553 }
2554
2555 static std::string getNodeAttributes(const TreeEntry *Entry,
2556 const BoUpSLP *) {
2557 if (Entry->State == TreeEntry::NeedToGather)
2558 return "color=red";
2559 return "";
2560 }
2561};
2562
2563} // end namespace llvm
2564
2565BoUpSLP::~BoUpSLP() {
2566 for (const auto &Pair : DeletedInstructions) {
2567 // Replace operands of ignored instructions with Undefs in case if they were
2568 // marked for deletion.
2569 if (Pair.getSecond()) {
2570 Value *Undef = UndefValue::get(Pair.getFirst()->getType());
2571 Pair.getFirst()->replaceAllUsesWith(Undef);
2572 }
2573 Pair.getFirst()->dropAllReferences();
2574 }
2575 for (const auto &Pair : DeletedInstructions) {
2576 assert(Pair.getFirst()->use_empty() &&(static_cast<void> (0))
2577 "trying to erase instruction with users.")(static_cast<void> (0));
2578 Pair.getFirst()->eraseFromParent();
2579 }
2580#ifdef EXPENSIVE_CHECKS
2581 // If we could guarantee that this call is not extremely slow, we could
2582 // remove the ifdef limitation (see PR47712).
2583 assert(!verifyFunction(*F, &dbgs()))(static_cast<void> (0));
2584#endif
2585}
2586
2587void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
2588 for (auto *V : AV) {
2589 if (auto *I = dyn_cast<Instruction>(V))
2590 eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
2591 };
2592}
2593
2594void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
2595 ArrayRef<Value *> UserIgnoreLst) {
2596 ExtraValueToDebugLocsMap ExternallyUsedValues;
2597 buildTree(Roots, ExternallyUsedValues, UserIgnoreLst);
2598}
2599
2600void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
2601 ExtraValueToDebugLocsMap &ExternallyUsedValues,
2602 ArrayRef<Value *> UserIgnoreLst) {
2603 deleteTree();
2604 UserIgnoreList = UserIgnoreLst;
2605 if (!allSameType(Roots))
2606 return;
2607 buildTree_rec(Roots, 0, EdgeInfo());
2608
2609 // Collect the values that we need to extract from the tree.
2610 for (auto &TEPtr : VectorizableTree) {
2611 TreeEntry *Entry = TEPtr.get();
2612
2613 // No need to handle users of gathered values.
2614 if (Entry->State == TreeEntry::NeedToGather)
2615 continue;
2616
2617 // For each lane:
2618 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2619 Value *Scalar = Entry->Scalars[Lane];
2620 int FoundLane = Entry->findLaneForValue(Scalar);
2621
2622 // Check if the scalar is externally used as an extra arg.
2623 auto ExtI = ExternallyUsedValues.find(Scalar);
2624 if (ExtI != ExternallyUsedValues.end()) {
2625 LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "do { } while (false)
2626 << Lane << " from " << *Scalar << ".\n")do { } while (false);
2627 ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
2628 }
2629 for (User *U : Scalar->users()) {
2630 LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n")do { } while (false);
2631
2632 Instruction *UserInst = dyn_cast<Instruction>(U);
2633 if (!UserInst)
2634 continue;
2635
2636 if (isDeleted(UserInst))
2637 continue;
2638
2639 // Skip in-tree scalars that become vectors
2640 if (TreeEntry *UseEntry = getTreeEntry(U)) {
2641 Value *UseScalar = UseEntry->Scalars[0];
2642 // Some in-tree scalars will remain as scalar in vectorized
2643 // instructions. If that is the case, the one in Lane 0 will
2644 // be used.
2645 if (UseScalar != U ||
2646 UseEntry->State == TreeEntry::ScatterVectorize ||
2647 !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
2648 LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *Udo { } while (false)
2649 << ".\n")do { } while (false);
2650 assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state")(static_cast<void> (0));
2651 continue;
2652 }
2653 }
2654
2655 // Ignore users in the user ignore list.
2656 if (is_contained(UserIgnoreList, UserInst))
2657 continue;
2658
2659 LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "do { } while (false)
2660 << Lane << " from " << *Scalar << ".\n")do { } while (false);
2661 ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
2662 }
2663 }
2664 }
2665}
2666
2667void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
2668 const EdgeInfo &UserTreeIdx) {
2669 assert((allConstant(VL) || allSameType(VL)) && "Invalid types!")(static_cast<void> (0));
2670
2671 InstructionsState S = getSameOpcode(VL);
2672 if (Depth == RecursionMaxDepth) {
2673 LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n")do { } while (false);
2674 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2675 return;
2676 }
2677
2678 // Don't handle scalable vectors
2679 if (S.getOpcode() == Instruction::ExtractElement &&
2680 isa<ScalableVectorType>(
2681 cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
2682 LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n")do { } while (false);
2683 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2684 return;
2685 }
2686
2687 // Don't handle vectors.
2688 if (S.OpValue->getType()->isVectorTy() &&
2689 !isa<InsertElementInst>(S.OpValue)) {
2690 LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n")do { } while (false);
2691 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2692 return;
2693 }
2694
2695 if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
2696 if (SI->getValueOperand()->getType()->isVectorTy()) {
2697 LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n")do { } while (false);
2698 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2699 return;
2700 }
2701
2702 // If all of the operands are identical or constant we have a simple solution.
2703 if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode()) {
2704 LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n")do { } while (false);
2705 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2706 return;
2707 }
2708
2709 // We now know that this is a vector of instructions of the same type from
2710 // the same block.
2711
2712 // Don't vectorize ephemeral values.
2713 for (Value *V : VL) {
2714 if (EphValues.count(V)) {
2715 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *Vdo { } while (false)
2716 << ") is ephemeral.\n")do { } while (false);
2717 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2718 return;
2719 }
2720 }
2721
2722 // Check if this is a duplicate of another entry.
2723 if (TreeEntry *E = getTreeEntry(S.OpValue)) {
2724 LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n")do { } while (false);
2725 if (!E->isSame(VL)) {
2726 LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n")do { } while (false);
2727 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2728 return;
2729 }
2730 // Record the reuse of the tree node. FIXME, currently this is only used to
2731 // properly draw the graph rather than for the actual vectorization.
2732 E->UserTreeIndices.push_back(UserTreeIdx);
2733 LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValuedo { } while (false)
2734 << ".\n")do { } while (false);
2735 return;
2736 }
2737
2738 // Check that none of the instructions in the bundle are already in the tree.
2739 for (Value *V : VL) {
2740 auto *I = dyn_cast<Instruction>(V);
2741 if (!I)
2742 continue;
2743 if (getTreeEntry(I)) {
2744 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *Vdo { } while (false)
2745 << ") is already in tree.\n")do { } while (false);
2746 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2747 return;
2748 }
2749 }
2750
2751 // If any of the scalars is marked as a value that needs to stay scalar, then
2752 // we need to gather the scalars.
2753 // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
2754 for (Value *V : VL) {
2755 if (MustGather.count(V) || is_contained(UserIgnoreList, V)) {
2756 LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n")do { } while (false);
2757 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2758 return;
2759 }
2760 }
2761
2762 // Check that all of the users of the scalars that we want to vectorize are
2763 // schedulable.
2764 auto *VL0 = cast<Instruction>(S.OpValue);
2765 BasicBlock *BB = VL0->getParent();
2766
2767 if (!DT->isReachableFromEntry(BB)) {
2768 // Don't go into unreachable blocks. They may contain instructions with
2769 // dependency cycles which confuse the final scheduling.
2770 LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n")do { } while (false);
2771 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2772 return;
2773 }
2774
2775 // Check that every instruction appears once in this bundle.
2776 SmallVector<unsigned, 4> ReuseShuffleIndicies;
2777 SmallVector<Value *, 4> UniqueValues;
2778 DenseMap<Value *, unsigned> UniquePositions;
2779 for (Value *V : VL) {
2780 auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
2781 ReuseShuffleIndicies.emplace_back(Res.first->second);
2782 if (Res.second)
2783 UniqueValues.emplace_back(V);
2784 }
2785 size_t NumUniqueScalarValues = UniqueValues.size();
2786 if (NumUniqueScalarValues == VL.size()) {
2787 ReuseShuffleIndicies.clear();
2788 } else {
2789 LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n")do { } while (false);
2790 if (NumUniqueScalarValues <= 1 ||
2791 !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
2792 LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n")do { } while (false);
2793 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2794 return;
2795 }
2796 VL = UniqueValues;
2797 }
2798
2799 auto &BSRef = BlocksSchedules[BB];
2800 if (!BSRef)
2801 BSRef = std::make_unique<BlockScheduling>(BB);
2802
2803 BlockScheduling &BS = *BSRef.get();
2804
2805 Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
2806 if (!Bundle) {
2807 LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n")do { } while (false);
2808 assert((!BS.getScheduleData(VL0) ||(static_cast<void> (0))
2809 !BS.getScheduleData(VL0)->isPartOfBundle()) &&(static_cast<void> (0))
2810 "tryScheduleBundle should cancelScheduling on failure")(static_cast<void> (0));
2811 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2812 ReuseShuffleIndicies);
2813 return;
2814 }
2815 LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n")do { } while (false);
2816
2817 unsigned ShuffleOrOp = S.isAltShuffle() ?
2818 (unsigned) Instruction::ShuffleVector : S.getOpcode();
2819 switch (ShuffleOrOp) {
2820 case Instruction::PHI: {
2821 auto *PH = cast<PHINode>(VL0);
2822
2823 // Check for terminator values (e.g. invoke).
2824 for (Value *V : VL)
2825 for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
2826 Instruction *Term = dyn_cast<Instruction>(
2827 cast<PHINode>(V)->getIncomingValueForBlock(
2828 PH->getIncomingBlock(I)));
2829 if (Term && Term->isTerminator()) {
2830 LLVM_DEBUG(dbgs()do { } while (false)
2831 << "SLP: Need to swizzle PHINodes (terminator use).\n")do { } while (false);
2832 BS.cancelScheduling(VL, VL0);
2833 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2834 ReuseShuffleIndicies);
2835 return;
2836 }
2837 }
2838
2839 TreeEntry *TE =
2840 newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
2841 LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n")do { } while (false);
2842
2843 // Keeps the reordered operands to avoid code duplication.
2844 SmallVector<ValueList, 2> OperandsVec;
2845 for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
2846 if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
2847 ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
2848 TE->setOperand(I, Operands);
2849 OperandsVec.push_back(Operands);
2850 continue;
2851 }
2852 ValueList Operands;
2853 // Prepare the operand vector.
2854 for (Value *V : VL)
2855 Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
2856 PH->getIncomingBlock(I)));
2857 TE->setOperand(I, Operands);
2858 OperandsVec.push_back(Operands);
2859 }
2860 for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
2861 buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
2862 return;
2863 }
2864 case Instruction::ExtractValue:
2865 case Instruction::ExtractElement: {
2866 OrdersType CurrentOrder;
2867 bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
2868 if (Reuse) {
2869 LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n")do { } while (false);
2870 ++NumOpsWantToKeepOriginalOrder;
2871 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
2872 ReuseShuffleIndicies);
2873 // This is a special case, as it does not gather, but at the same time
2874 // we are not extending buildTree_rec() towards the operands.
2875 ValueList Op0;
2876 Op0.assign(VL.size(), VL0->getOperand(0));
2877 VectorizableTree.back()->setOperand(0, Op0);
2878 return;
2879 }
2880 if (!CurrentOrder.empty()) {
2881 LLVM_DEBUG({do { } while (false)
2882 dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "do { } while (false)
2883 "with order";do { } while (false)
2884 for (unsigned Idx : CurrentOrder)do { } while (false)
2885 dbgs() << " " << Idx;do { } while (false)
2886 dbgs() << "\n";do { } while (false)
2887 })do { } while (false);
2888 // Insert new order with initial value 0, if it does not exist,
2889 // otherwise return the iterator to the existing one.
2890 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
2891 ReuseShuffleIndicies, CurrentOrder);
2892 findRootOrder(CurrentOrder);
2893 ++NumOpsWantToKeepOrder[CurrentOrder];
2894 // This is a special case, as it does not gather, but at the same time
2895 // we are not extending buildTree_rec() towards the operands.
2896 ValueList Op0;
2897 Op0.assign(VL.size(), VL0->getOperand(0));
2898 VectorizableTree.back()->setOperand(0, Op0);
2899 return;
2900 }
2901 LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n")do { } while (false);
2902 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2903 ReuseShuffleIndicies);
2904 BS.cancelScheduling(VL, VL0);
2905 return;
2906 }
2907 case Instruction::InsertElement: {
2908 assert(ReuseShuffleIndicies.empty() && "All inserts should be unique")(static_cast<void> (0));
2909
2910 // Check that we have a buildvector and not a shuffle of 2 or more
2911 // different vectors.
2912 ValueSet SourceVectors;
2913 for (Value *V : VL)
2914 SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
2915
2916 if (count_if(VL, [&SourceVectors](Value *V) {
2917 return !SourceVectors.contains(V);
2918 }) >= 2) {
2919 // Found 2nd source vector - cancel.
2920 LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "do { } while (false)
2921 "different source vectors.\n")do { } while (false);
2922 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2923 ReuseShuffleIndicies);
2924 BS.cancelScheduling(VL, VL0);
2925 return;
2926 }
2927
2928 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx);
2929 LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n")do { } while (false);
2930
2931 constexpr int NumOps = 2;
2932 ValueList VectorOperands[NumOps];
2933 for (int I = 0; I < NumOps; ++I) {
2934 for (Value *V : VL)
2935 VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
2936
2937 TE->setOperand(I, VectorOperands[I]);
2938 }
2939 buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, 0});
2940 return;
2941 }
2942 case Instruction::Load: {
2943 // Check that a vectorized load would load the same memory as a scalar
2944 // load. For example, we don't want to vectorize loads that are smaller
2945 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
2946 // treats loading/storing it as an i8 struct. If we vectorize loads/stores
2947 // from such a struct, we read/write packed bits disagreeing with the
2948 // unvectorized version.
2949 Type *ScalarTy = VL0->getType();
2950
2951 if (DL->getTypeSizeInBits(ScalarTy) !=
2952 DL->getTypeAllocSizeInBits(ScalarTy)) {
2953 BS.cancelScheduling(VL, VL0);
2954 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2955 ReuseShuffleIndicies);
2956 LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n")do { } while (false);
2957 return;
2958 }
2959
2960 // Make sure all loads in the bundle are simple - we can't vectorize
2961 // atomic or volatile loads.
2962 SmallVector<Value *, 4> PointerOps(VL.size());
2963 auto POIter = PointerOps.begin();
2964 for (Value *V : VL) {
2965 auto *L = cast<LoadInst>(V);
2966 if (!L->isSimple()) {
2967 BS.cancelScheduling(VL, VL0);
2968 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2969 ReuseShuffleIndicies);
2970 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n")do { } while (false);
2971 return;
2972 }
2973 *POIter = L->getPointerOperand();
2974 ++POIter;
2975 }
2976
2977 OrdersType CurrentOrder;
2978 // Check the order of pointer operands.
2979 if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
2980 Value *Ptr0;
2981 Value *PtrN;
2982 if (CurrentOrder.empty()) {
2983 Ptr0 = PointerOps.front();
2984 PtrN = PointerOps.back();
2985 } else {
2986 Ptr0 = PointerOps[CurrentOrder.front()];
2987 PtrN = PointerOps[CurrentOrder.back()];
2988 }
2989 Optional<int> Diff = getPointersDiff(
2990 ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
2991 // Check that the sorted loads are consecutive.
2992 if (static_cast<unsigned>(*Diff) == VL.size() - 1) {
2993 if (CurrentOrder.empty()) {
2994 // Original loads are consecutive and does not require reordering.
2995 ++NumOpsWantToKeepOriginalOrder;
2996 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
2997 UserTreeIdx, ReuseShuffleIndicies);
2998 TE->setOperandsInOrder();
2999 LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n")do { } while (false);
3000 } else {
3001 // Need to reorder.
3002 TreeEntry *TE =
3003 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3004 ReuseShuffleIndicies, CurrentOrder);
3005 TE->setOperandsInOrder();
3006 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n")do { } while (false);
3007 findRootOrder(CurrentOrder);
3008 ++NumOpsWantToKeepOrder[CurrentOrder];
3009 }
3010 return;
3011 }
3012 Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3013 for (Value *V : VL)
3014 CommonAlignment =
3015 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3016 if (TTI->isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3017 CommonAlignment)) {
3018 // Vectorizing non-consecutive loads with `llvm.masked.gather`.
3019 TreeEntry *TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle,
3020 S, UserTreeIdx, ReuseShuffleIndicies);
3021 TE->setOperandsInOrder();
3022 buildTree_rec(PointerOps, Depth + 1, {TE, 0});
3023 LLVM_DEBUG(dbgs()do { } while (false)
3024 << "SLP: added a vector of non-consecutive loads.\n")do { } while (false);
3025 return;
3026 }
3027 }
3028
3029 LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n")do { } while (false);
3030 BS.cancelScheduling(VL, VL0);
3031 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3032 ReuseShuffleIndicies);
3033 return;
3034 }
3035 case Instruction::ZExt:
3036 case Instruction::SExt:
3037 case Instruction::FPToUI:
3038 case Instruction::FPToSI:
3039 case Instruction::FPExt:
3040 case Instruction::PtrToInt:
3041 case Instruction::IntToPtr:
3042 case Instruction::SIToFP:
3043 case Instruction::UIToFP:
3044 case Instruction::Trunc:
3045 case Instruction::FPTrunc:
3046 case Instruction::BitCast: {
3047 Type *SrcTy = VL0->getOperand(0)->getType();
3048 for (Value *V : VL) {
3049 Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
3050 if (Ty != SrcTy || !isValidElementType(Ty)) {
3051 BS.cancelScheduling(VL, VL0);
3052 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3053 ReuseShuffleIndicies);
3054 LLVM_DEBUG(dbgs()do { } while (false)
3055 << "SLP: Gathering casts with different src types.\n")do { } while (false);
3056 return;
3057 }
3058 }
3059 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3060 ReuseShuffleIndicies);
3061 LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n")do { } while (false);
3062
3063 TE->setOperandsInOrder();
3064 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
3065 ValueList Operands;
3066 // Prepare the operand vector.
3067 for (Value *V : VL)
3068 Operands.push_back(cast<Instruction>(V)->getOperand(i));
3069
3070 buildTree_rec(Operands, Depth + 1, {TE, i});
3071 }
3072 return;
3073 }
3074 case Instruction::ICmp:
3075 case Instruction::FCmp: {
3076 // Check that all of the compares have the same predicate.
3077 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
3078 CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
3079 Type *ComparedTy = VL0->getOperand(0)->getType();
3080 for (Value *V : VL) {
3081 CmpInst *Cmp = cast<CmpInst>(V);
3082 if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
3083 Cmp->getOperand(0)->getType() != ComparedTy) {
3084 BS.cancelScheduling(VL, VL0);
3085 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3086 ReuseShuffleIndicies);
3087 LLVM_DEBUG(dbgs()do { } while (false)
3088 << "SLP: Gathering cmp with different predicate.\n")do { } while (false);
3089 return;
3090 }
3091 }
3092
3093 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3094 ReuseShuffleIndicies);
3095 LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n")do { } while (false);
3096
3097 ValueList Left, Right;
3098 if (cast<CmpInst>(VL0)->isCommutative()) {
3099 // Commutative predicate - collect + sort operands of the instructions
3100 // so that each side is more likely to have the same opcode.
3101 assert(P0 == SwapP0 && "Commutative Predicate mismatch")(static_cast<void> (0));
3102 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
3103 } else {
3104 // Collect operands - commute if it uses the swapped predicate.
3105 for (Value *V : VL) {
3106 auto *Cmp = cast<CmpInst>(V);
3107 Value *LHS = Cmp->getOperand(0);
3108 Value *RHS = Cmp->getOperand(1);
3109 if (Cmp->getPredicate() != P0)
3110 std::swap(LHS, RHS);
3111 Left.push_back(LHS);
3112 Right.push_back(RHS);
3113 }
3114 }
3115 TE->setOperand(0, Left);
3116 TE->setOperand(1, Right);
3117 buildTree_rec(Left, Depth + 1, {TE, 0});
3118 buildTree_rec(Right, Depth + 1, {TE, 1});
3119 return;
3120 }
3121 case Instruction::Select:
3122 case Instruction::FNeg:
3123 case Instruction::Add:
3124 case Instruction::FAdd:
3125 case Instruction::Sub:
3126 case Instruction::FSub:
3127 case Instruction::Mul:
3128 case Instruction::FMul:
3129 case Instruction::UDiv:
3130 case Instruction::SDiv:
3131 case Instruction::FDiv:
3132 case Instruction::URem:
3133 case Instruction::SRem:
3134 case Instruction::FRem:
3135 case Instruction::Shl:
3136 case Instruction::LShr:
3137 case Instruction::AShr:
3138 case Instruction::And:
3139 case Instruction::Or:
3140 case Instruction::Xor: {
3141 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3142 ReuseShuffleIndicies);
3143 LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n")do { } while (false);
3144
3145 // Sort operands of the instructions so that each side is more likely to
3146 // have the same opcode.
3147 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
3148 ValueList Left, Right;
3149 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
3150 TE->setOperand(0, Left);
3151 TE->setOperand(1, Right);
3152 buildTree_rec(Left, Depth + 1, {TE, 0});
3153 buildTree_rec(Right, Depth + 1, {TE, 1});
3154 return;
3155 }
3156
3157 TE->setOperandsInOrder();
3158 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
3159 ValueList Operands;
3160 // Prepare the operand vector.
3161 for (Value *V : VL)
3162 Operands.push_back(cast<Instruction>(V)->getOperand(i));
3163
3164 buildTree_rec(Operands, Depth + 1, {TE, i});
3165 }
3166 return;
3167 }
3168 case Instruction::GetElementPtr: {
3169 // We don't combine GEPs with complicated (nested) indexing.
3170 for (Value *V : VL) {
3171 if (cast<Instruction>(V)->getNumOperands() != 2) {
3172 LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n")do { } while (false);
3173 BS.cancelScheduling(VL, VL0);
3174 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3175 ReuseShuffleIndicies);
3176 return;
3177 }
3178 }
3179
3180 // We can't combine several GEPs into one vector if they operate on
3181 // different types.
3182 Type *Ty0 = VL0->getOperand(0)->getType();
3183 for (Value *V : VL) {
3184 Type *CurTy = cast<Instruction>(V)->getOperand(0)->getType();
3185 if (Ty0 != CurTy) {
3186 LLVM_DEBUG(dbgs()do { } while (false)
3187 << "SLP: not-vectorizable GEP (different types).\n")do { } while (false);
3188 BS.cancelScheduling(VL, VL0);
3189 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3190 ReuseShuffleIndicies);
3191 return;
3192 }
3193 }
3194
3195 // We don't combine GEPs with non-constant indexes.
3196 Type *Ty1 = VL0->getOperand(1)->getType();
3197 for (Value *V : VL) {
3198 auto Op = cast<Instruction>(V)->getOperand(1);
3199 if (!isa<ConstantInt>(Op) ||
3200 (Op->getType() != Ty1 &&
3201 Op->getType()->getScalarSizeInBits() >
3202 DL->getIndexSizeInBits(
3203 V->getType()->getPointerAddressSpace()))) {
3204 LLVM_DEBUG(dbgs()do { } while (false)
3205 << "SLP: not-vectorizable GEP (non-constant indexes).\n")do { } while (false);
3206 BS.cancelScheduling(VL, VL0);
3207 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3208 ReuseShuffleIndicies);
3209 return;
3210 }
3211 }
3212
3213 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3214 ReuseShuffleIndicies);
3215 LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n")do { } while (false);
3216 TE->setOperandsInOrder();
3217 for (unsigned i = 0, e = 2; i < e; ++i) {
3218 ValueList Operands;
3219 // Prepare the operand vector.
3220 for (Value *V : VL)
3221 Operands.push_back(cast<Instruction>(V)->getOperand(i));
3222
3223 buildTree_rec(Operands, Depth + 1, {TE, i});
3224 }
3225 return;
3226 }
3227 case Instruction::Store: {
3228 // Check if the stores are consecutive or if we need to swizzle them.
3229 llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
3230 // Avoid types that are padded when being allocated as scalars, while
3231 // being packed together in a vector (such as i1).
3232 if (DL->getTypeSizeInBits(ScalarTy) !=
3233 DL->getTypeAllocSizeInBits(ScalarTy)) {
3234 BS.cancelScheduling(VL, VL0);
3235 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3236 ReuseShuffleIndicies);
3237 LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n")do { } while (false);
3238 return;
3239 }
3240 // Make sure all stores in the bundle are simple - we can't vectorize
3241 // atomic or volatile stores.
3242 SmallVector<Value *, 4> PointerOps(VL.size());
3243 ValueList Operands(VL.size());
3244 auto POIter = PointerOps.begin();
3245 auto OIter = Operands.begin();
3246 for (Value *V : VL) {
3247 auto *SI = cast<StoreInst>(V);
3248 if (!SI->isSimple()) {
3249 BS.cancelScheduling(VL, VL0);
3250 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3251 ReuseShuffleIndicies);
3252 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n")do { } while (false);
3253 return;
3254 }
3255 *POIter = SI->getPointerOperand();
3256 *OIter = SI->getValueOperand();
3257 ++POIter;
3258 ++OIter;
3259 }
3260
3261 OrdersType CurrentOrder;
3262 // Check the order of pointer operands.
3263 if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
3264 Value *Ptr0;
3265 Value *PtrN;
3266 if (CurrentOrder.empty()) {
3267 Ptr0 = PointerOps.front();
3268 PtrN = PointerOps.back();
3269 } else {
3270 Ptr0 = PointerOps[CurrentOrder.front()];
3271 PtrN = PointerOps[CurrentOrder.back()];
3272 }
3273 Optional<int> Dist =
3274 getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
3275 // Check that the sorted pointer operands are consecutive.
3276 if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
3277 if (CurrentOrder.empty()) {
3278 // Original stores are consecutive and does not require reordering.
3279 ++NumOpsWantToKeepOriginalOrder;
3280 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
3281 UserTreeIdx, ReuseShuffleIndicies);
3282 TE->setOperandsInOrder();
3283 buildTree_rec(Operands, Depth + 1, {TE, 0});
3284 LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n")do { } while (false);
3285 } else {
3286 TreeEntry *TE =
3287 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3288 ReuseShuffleIndicies, CurrentOrder);
3289 TE->setOperandsInOrder();
3290 buildTree_rec(Operands, Depth + 1, {TE, 0});
3291 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n")do { } while (false);
3292 findRootOrder(CurrentOrder);
3293 ++NumOpsWantToKeepOrder[CurrentOrder];
3294 }
3295 return;
3296 }
3297 }
3298
3299 BS.cancelScheduling(VL, VL0);
3300 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3301 ReuseShuffleIndicies);
3302 LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n")do { } while (false);
3303 return;
3304 }
3305 case Instruction::Call: {
3306 // Check if the calls are all to the same vectorizable intrinsic or
3307 // library function.
3308 CallInst *CI = cast<CallInst>(VL0);
3309 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3310
3311 VFShape Shape = VFShape::get(
3312 *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
3313 false /*HasGlobalPred*/);
3314 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
3315
3316 if (!VecFunc && !isTriviallyVectorizable(ID)) {
3317 BS.cancelScheduling(VL, VL0);
3318 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3319 ReuseShuffleIndicies);
3320 LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n")do { } while (false);
3321 return;
3322 }
3323 Function *F = CI->getCalledFunction();
3324 unsigned NumArgs = CI->getNumArgOperands();
3325 SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
3326 for (unsigned j = 0; j != NumArgs; ++j)
3327 if (hasVectorInstrinsicScalarOpd(ID, j))
3328 ScalarArgs[j] = CI->getArgOperand(j);
3329 for (Value *V : VL) {
3330 CallInst *CI2 = dyn_cast<CallInst>(V);
3331 if (!CI2 || CI2->getCalledFunction() != F ||
3332 getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
3333 (VecFunc &&
3334 VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
3335 !CI->hasIdenticalOperandBundleSchema(*CI2)) {
3336 BS.cancelScheduling(VL, VL0);
3337 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3338 ReuseShuffleIndicies);
3339 LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *Vdo { } while (false)
3340 << "\n")do { } while (false);
3341 return;
3342 }
3343 // Some intrinsics have scalar arguments and should be same in order for
3344 // them to be vectorized.
3345 for (unsigned j = 0; j != NumArgs; ++j) {
3346 if (hasVectorInstrinsicScalarOpd(ID, j)) {
3347 Value *A1J = CI2->getArgOperand(j);
3348 if (ScalarArgs[j] != A1J) {
3349 BS.cancelScheduling(VL, VL0);
3350 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3351 ReuseShuffleIndicies);
3352 LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CIdo { } while (false)
3353 << " argument " << ScalarArgs[j] << "!=" << A1Jdo { } while (false)
3354 << "\n")do { } while (false);
3355 return;
3356 }
3357 }
3358 }
3359 // Verify that the bundle operands are identical between the two calls.
3360 if (CI->hasOperandBundles() &&
3361 !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
3362 CI->op_begin() + CI->getBundleOperandsEndIndex(),
3363 CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
3364 BS.cancelScheduling(VL, VL0);
3365 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3366 ReuseShuffleIndicies);
3367 LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"do { } while (false)
3368 << *CI << "!=" << *V << '\n')do { } while (false);
3369 return;
3370 }
3371 }
3372
3373 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3374 ReuseShuffleIndicies);
3375 TE->setOperandsInOrder();
3376 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
3377 ValueList Operands;
3378 // Prepare the operand vector.
3379 for (Value *V : VL) {
3380 auto *CI2 = cast<CallInst>(V);
3381 Operands.push_back(CI2->getArgOperand(i));
3382 }
3383 buildTree_rec(Operands, Depth + 1, {TE, i});
3384 }
3385 return;
3386 }
3387 case Instruction::ShuffleVector: {
3388 // If this is not an alternate sequence of opcode like add-sub
3389 // then do not vectorize this instruction.
3390 if (!S.isAltShuffle()) {
3391 BS.cancelScheduling(VL, VL0);
3392 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3393 ReuseShuffleIndicies);
3394 LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n")do { } while (false);
3395 return;
3396 }
3397 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3398 ReuseShuffleIndicies);
3399 LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n")do { } while (false);
3400
3401 // Reorder operands if reordering would enable vectorization.
3402 if (isa<BinaryOperator>(VL0)) {
3403 ValueList Left, Right;
3404 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
3405 TE->setOperand(0, Left);
3406 TE->setOperand(1, Right);
3407 buildTree_rec(Left, Depth + 1, {TE, 0});
3408 buildTree_rec(Right, Depth + 1, {TE, 1});
3409 return;
3410 }
3411
3412 TE->setOperandsInOrder();
3413 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
3414 ValueList Operands;
3415 // Prepare the operand vector.
3416 for (Value *V : VL)
3417 Operands.push_back(cast<Instruction>(V)->getOperand(i));
3418
3419 buildTree_rec(Operands, Depth + 1, {TE, i});
3420 }
3421 return;
3422 }
3423 default:
3424 BS.cancelScheduling(VL, VL0);
3425 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3426 ReuseShuffleIndicies);
3427 LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n")do { } while (false);
3428 return;
3429 }
3430}
3431
3432unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
3433 unsigned N = 1;
3434 Type *EltTy = T;
3435
3436 while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
3437 isa<VectorType>(EltTy)) {
3438 if (auto *ST = dyn_cast<StructType>(EltTy)) {
3439 // Check that struct is homogeneous.
3440 for (const auto *Ty : ST->elements())
3441 if (Ty != *ST->element_begin())
3442 return 0;
3443 N *= ST->getNumElements();
3444 EltTy = *ST->element_begin();
3445 } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
3446 N *= AT->getNumElements();
3447 EltTy = AT->getElementType();
3448 } else {
3449 auto *VT = cast<FixedVectorType>(EltTy);
3450 N *= VT->getNumElements();
3451 EltTy = VT->getElementType();
3452 }
3453 }
3454
3455 if (!isValidElementType(EltTy))
3456 return 0;
3457 uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
3458 if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
3459 return 0;
3460 return N;
3461}
3462
3463bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
3464 SmallVectorImpl<unsigned> &CurrentOrder) const {
3465 Instruction *E0 = cast<Instruction>(OpValue);
3466 assert(E0->getOpcode() == Instruction::ExtractElement ||(static_cast<void> (0))
3467 E0->getOpcode() == Instruction::ExtractValue)(static_cast<void> (0));
3468 assert(E0->getOpcode() == getSameOpcode(VL).getOpcode() && "Invalid opcode")(static_cast<void> (0));
3469 // Check if all of the extracts come from the same vector and from the
3470 // correct offset.
3471 Value *Vec = E0->getOperand(0);
3472
3473 CurrentOrder.clear();
3474
3475 // We have to extract from a vector/aggregate with the same number of elements.
3476 unsigned NElts;
3477 if (E0->getOpcode() == Instruction::ExtractValue) {
3478 const DataLayout &DL = E0->getModule()->getDataLayout();
3479 NElts = canMapToVector(Vec->getType(), DL);
3480 if (!NElts)
3481 return false;
3482 // Check if load can be rewritten as load of vector.
3483 LoadInst *LI = dyn_cast<LoadInst>(Vec);
3484 if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
3485 return false;
3486 } else {
3487 NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
3488 }
3489
3490 if (NElts != VL.size())
3491 return false;
3492
3493 // Check that all of the indices extract from the correct offset.
3494 bool ShouldKeepOrder = true;
3495 unsigned E = VL.size();
3496 // Assign to all items the initial value E + 1 so we can check if the extract
3497 // instruction index was used already.
3498 // Also, later we can check that all the indices are used and we have a
3499 // consecutive access in the extract instructions, by checking that no
3500 // element of CurrentOrder still has value E + 1.
3501 CurrentOrder.assign(E, E + 1);
3502 unsigned I = 0;
3503 for (; I < E; ++I) {
3504 auto *Inst = cast<Instruction>(VL[I]);
3505 if (Inst->getOperand(0) != Vec)
3506 break;
3507 Optional<unsigned> Idx = getExtractIndex(Inst);
3508 if (!Idx)
3509 break;
3510 const unsigned ExtIdx = *Idx;
3511 if (ExtIdx != I) {
3512 if (ExtIdx >= E || CurrentOrder[ExtIdx] != E + 1)
3513 break;
3514 ShouldKeepOrder = false;
3515 CurrentOrder[ExtIdx] = I;
3516 } else {
3517 if (CurrentOrder[I] != E + 1)
3518 break;
3519 CurrentOrder[I] = I;
3520 }
3521 }
3522 if (I < E) {
3523 CurrentOrder.clear();
3524 return false;
3525 }
3526
3527 return ShouldKeepOrder;
3528}
3529
3530bool BoUpSLP::areAllUsersVectorized(Instruction *I,
3531 ArrayRef<Value *> VectorizedVals) const {
3532 return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
3533 llvm::all_of(I->users(), [this](User *U) {
3534 return ScalarToTreeEntry.count(U) > 0;
3535 });
3536}
3537
3538static std::pair<InstructionCost, InstructionCost>
3539getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
3540 TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
3541 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3542
3543 // Calculate the cost of the scalar and vector calls.
3544 SmallVector<Type *, 4> VecTys;
3545 for (Use &Arg : CI->args())
3546 VecTys.push_back(
3547 FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
3548 FastMathFlags FMF;
3549 if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
3550 FMF = FPCI->getFastMathFlags();
3551 SmallVector<const Value *> Arguments(CI->arg_begin(), CI->arg_end());
3552 IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
3553 dyn_cast<IntrinsicInst>(CI));
3554 auto IntrinsicCost =
3555 TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
3556
3557 auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
3558 VecTy->getNumElements())),
3559 false /*HasGlobalPred*/);
3560 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
3561 auto LibCost = IntrinsicCost;
3562 if (!CI->isNoBuiltin() && VecFunc) {
3563 // Calculate the cost of the vector library call.
3564 // If the corresponding vector call is cheaper, return its cost.
3565 LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
3566 TTI::TCK_RecipThroughput);
3567 }
3568 return {IntrinsicCost, LibCost};
3569}
3570
3571/// Compute the cost of creating a vector of type \p VecTy containing the
3572/// extracted values from \p VL.
3573static InstructionCost
3574computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
3575 TargetTransformInfo::ShuffleKind ShuffleKind,
3576 ArrayRef<int> Mask, TargetTransformInfo &TTI) {
3577 unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
3578
3579 if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
3580 VecTy->getNumElements() < NumOfParts)
3581 return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
3582
3583 bool AllConsecutive = true;
3584 unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
3585 unsigned Idx = -1;
3586 InstructionCost Cost = 0;
3587
3588 // Process extracts in blocks of EltsPerVector to check if the source vector
3589 // operand can be re-used directly. If not, add the cost of creating a shuffle
3590 // to extract the values into a vector register.
3591 for (auto *V : VL) {
3592 ++Idx;
3593
3594 // Reached the start of a new vector registers.
3595 if (Idx % EltsPerVector == 0) {
3596 AllConsecutive = true;
3597 continue;
3598 }
3599
3600 // Check all extracts for a vector register on the target directly
3601 // extract values in order.
3602 unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
3603 unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
3604 AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
3605 CurrentIdx % EltsPerVector == Idx % EltsPerVector;
3606
3607 if (AllConsecutive)
3608 continue;
3609
3610 // Skip all indices, except for the last index per vector block.
3611 if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
3612 continue;
3613
3614 // If we have a series of extracts which are not consecutive and hence
3615 // cannot re-use the source vector register directly, compute the shuffle
3616 // cost to extract the a vector with EltsPerVector elements.
3617 Cost += TTI.getShuffleCost(
3618 TargetTransformInfo::SK_PermuteSingleSrc,
3619 FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
3620 }
3621 return Cost;
3622}
3623
3624/// Shuffles \p Mask in accordance with the given \p SubMask.
3625static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
3626 if (SubMask.empty())
3627 return;
3628 if (Mask.empty()) {
3629 Mask.append(SubMask.begin(), SubMask.end());
3630 return;
3631 }
3632 SmallVector<int, 4> NewMask(SubMask.size(), SubMask.size());
3633 int TermValue = std::min(Mask.size(), SubMask.size());
3634 for (int I = 0, E = SubMask.size(); I < E; ++I) {
3635 if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
3636 Mask[SubMask[I]] >= TermValue) {
3637 NewMask[I] = UndefMaskElem;
3638 continue;
3639 }
3640 NewMask[I] = Mask[SubMask[I]];
3641 }
3642 Mask.swap(NewMask);
3643}
3644
3645InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
3646 ArrayRef<Value *> VectorizedVals) {
3647 ArrayRef<Value*> VL = E->Scalars;
3648
3649 Type *ScalarTy = VL[0]->getType();
3650 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
3651 ScalarTy = SI->getValueOperand()->getType();
3652 else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
3653 ScalarTy = CI->getOperand(0)->getType();
3654 else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
3655 ScalarTy = IE->getOperand(1)->getType();
3656 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
3657 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
3658
3659 // If we have computed a smaller type for the expression, update VecTy so
3660 // that the costs will be accurate.
3661 if (MinBWs.count(VL[0]))
3662 VecTy = FixedVectorType::get(
3663 IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
3664 auto *FinalVecTy = VecTy;
3665
3666 unsigned ReuseShuffleNumbers = E->ReuseShuffleIndices.size();
3667 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
3668 if (NeedToShuffleReuses)
3669 FinalVecTy =
3670 FixedVectorType::get(VecTy->getElementType(), ReuseShuffleNumbers);
3671 // FIXME: it tries to fix a problem with MSVC buildbots.
3672 TargetTransformInfo &TTIRef = *TTI;
3673 auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
3674 VectorizedVals](InstructionCost &Cost,
3675 bool IsGather) {
3676 DenseMap<Value *, int> ExtractVectorsTys;
3677 for (auto *V : VL) {
3678 // If all users of instruction are going to be vectorized and this
3679 // instruction itself is not going to be vectorized, consider this
3680 // instruction as dead and remove its cost from the final cost of the
3681 // vectorized tree.
3682 if (!areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
3683 (IsGather && ScalarToTreeEntry.count(V)))
3684 continue;
3685 auto *EE = cast<ExtractElementInst>(V);
3686 unsigned Idx = *getExtractIndex(EE);
3687 if (TTIRef.getNumberOfParts(VecTy) !=
3688 TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
3689 auto It =
3690 ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
3691 It->getSecond() = std::min<int>(It->second, Idx);
3692 }
3693 // Take credit for instruction that will become dead.
3694 if (EE->hasOneUse()) {
3695 Instruction *Ext = EE->user_back();
3696 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3697 all_of(Ext->users(),
3698 [](User *U) { return isa<GetElementPtrInst>(U); })) {
3699 // Use getExtractWithExtendCost() to calculate the cost of
3700 // extractelement/ext pair.
3701 Cost -=
3702 TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
3703 EE->getVectorOperandType(), Idx);
3704 // Add back the cost of s|zext which is subtracted separately.
3705 Cost += TTIRef.getCastInstrCost(
3706 Ext->getOpcode(), Ext->getType(), EE->getType(),
3707 TTI::getCastContextHint(Ext), CostKind, Ext);
3708 continue;
3709 }
3710 }
3711 Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
3712 EE->getVectorOperandType(), Idx);
3713 }
3714 // Add a cost for subvector extracts/inserts if required.
3715 for (const auto &Data : ExtractVectorsTys) {
3716 auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
3717 unsigned NumElts = VecTy->getNumElements();
3718 if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
3719 unsigned Idx = (Data.second / NumElts) * NumElts;
3720 unsigned EENumElts = EEVTy->getNumElements();
3721 if (Idx + NumElts <= EENumElts) {
3722 Cost +=
3723 TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
3724 EEVTy, None, Idx, VecTy);
3725 } else {
3726 // Need to round up the subvector type vectorization factor to avoid a
3727 // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
3728 // <= EENumElts.
3729 auto *SubVT =
3730 FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
3731 Cost +=
3732 TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
3733 EEVTy, None, Idx, SubVT);
3734 }
3735 } else {
3736 Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
3737 VecTy, None, 0, EEVTy);
3738 }
3739 }
3740 };
3741 if (E->State == TreeEntry::NeedToGather) {
3742 if (allConstant(VL))
3743 return 0;
3744 if (isa<InsertElementInst>(VL[0]))
3745 return InstructionCost::getInvalid();
3746 SmallVector<int> Mask;
3747 SmallVector<const TreeEntry *> Entries;
3748 Optional<TargetTransformInfo::ShuffleKind> Shuffle =
3749 isGatherShuffledEntry(E, Mask, Entries);
3750 if (Shuffle.hasValue()) {
3751 InstructionCost GatherCost = 0;
3752 if (ShuffleVectorInst::isIdentityMask(Mask)) {
3753 // Perfect match in the graph, will reuse the previously vectorized
3754 // node. Cost is 0.
3755 LLVM_DEBUG(do { } while (false)
3756 dbgs()do { } while (false)
3757 << "SLP: perfect diamond match for gather bundle that starts with "do { } while (false)
3758 << *VL.front() << ".\n")do { } while (false);
3759 if (NeedToShuffleReuses)
3760 GatherCost =
3761 TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
3762 FinalVecTy, E->ReuseShuffleIndices);
3763 } else {
3764 LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()do { } while (false)
3765 << " entries for bundle that starts with "do { } while (false)
3766 << *VL.front() << ".\n")do { } while (false);
3767 // Detected that instead of gather we can emit a shuffle of single/two
3768 // previously vectorized nodes. Add the cost of the permutation rather
3769 // than gather.
3770 ::addMask(Mask, E->ReuseShuffleIndices);
3771 GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
3772 }
3773 return GatherCost;
3774 }
3775 if (isSplat(VL)) {
3776 // Found the broadcasting of the single scalar, calculate the cost as the
3777 // broadcast.
3778 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy);
3779 }
3780 if (E->getOpcode() == Instruction::ExtractElement && allSameType(VL) &&
3781 allSameBlock(VL) &&
3782 !isa<ScalableVectorType>(
3783 cast<ExtractElementInst>(E->getMainOp())->getVectorOperandType())) {
3784 // Check that gather of extractelements can be represented as just a
3785 // shuffle of a single/two vectors the scalars are extracted from.
3786 SmallVector<int> Mask;
3787 Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
3788 isShuffle(VL, Mask);
3789 if (ShuffleKind.hasValue()) {
3790 // Found the bunch of extractelement instructions that must be gathered
3791 // into a vector and can be represented as a permutation elements in a
3792 // single input vector or of 2 input vectors.
3793 InstructionCost Cost =
3794 computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
3795 AdjustExtractsCost(Cost, /*IsGather=*/true);
3796 if (NeedToShuffleReuses)
3797 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
3798 FinalVecTy, E->ReuseShuffleIndices);
3799 return Cost;
3800 }
3801 }
3802 InstructionCost ReuseShuffleCost = 0;
3803 if (NeedToShuffleReuses)
3804 ReuseShuffleCost = TTI->getShuffleCost(
3805 TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
3806 return ReuseShuffleCost + getGatherCost(VL);
3807 }
3808 InstructionCost CommonCost = 0;
3809 SmallVector<int> Mask;
3810 if (!E->ReorderIndices.empty()) {
3811 SmallVector<int> NewMask;
3812 if (E->getOpcode() == Instruction::Store) {
3813 // For stores the order is actually a mask.
3814 NewMask.resize(E->ReorderIndices.size());
3815 copy(E->ReorderIndices, NewMask.begin());
3816 } else {
3817 inversePermutation(E->ReorderIndices, NewMask);
3818 }
3819 ::addMask(Mask, NewMask);
3820 }
3821 if (NeedToShuffleReuses)
3822 ::addMask(Mask, E->ReuseShuffleIndices);
3823 if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
3824 CommonCost =
3825 TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
3826 assert((E->State == TreeEntry::Vectorize ||(static_cast<void> (0))
3827 E->State == TreeEntry::ScatterVectorize) &&(static_cast<void> (0))
3828 "Unhandled state")(static_cast<void> (0));
3829 assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL")(static_cast<void> (0));
3830 Instruction *VL0 = E->getMainOp();
3831 unsigned ShuffleOrOp =
3832 E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
3833 switch (ShuffleOrOp) {
3834 case Instruction::PHI:
3835 return 0;
3836
3837 case Instruction::ExtractValue:
3838 case Instruction::ExtractElement: {
3839 // The common cost of removal ExtractElement/ExtractValue instructions +
3840 // the cost of shuffles, if required to resuffle the original vector.
3841 if (NeedToShuffleReuses) {
3842 unsigned Idx = 0;
3843 for (unsigned I : E->ReuseShuffleIndices) {
3844 if (ShuffleOrOp == Instruction::ExtractElement) {
3845 auto *EE = cast<ExtractElementInst>(VL[I]);
3846 CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
3847 EE->getVectorOperandType(),
3848 *getExtractIndex(EE));
3849 } else {
3850 CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
3851 VecTy, Idx);
3852 ++Idx;
3853 }
3854 }
3855 Idx = ReuseShuffleNumbers;
3856 for (Value *V : VL) {
3857 if (ShuffleOrOp == Instruction::ExtractElement) {
3858 auto *EE = cast<ExtractElementInst>(V);
3859 CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
3860 EE->getVectorOperandType(),
3861 *getExtractIndex(EE));
3862 } else {
3863 --Idx;
3864 CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
3865 VecTy, Idx);
3866 }
3867 }
3868 }
3869 if (ShuffleOrOp == Instruction::ExtractValue) {
3870 for (unsigned I = 0, E = VL.size(); I < E; ++I) {
3871 auto *EI = cast<Instruction>(VL[I]);
3872 // Take credit for instruction that will become dead.
3873 if (EI->hasOneUse()) {
3874 Instruction *Ext = EI->user_back();
3875 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3876 all_of(Ext->users(),
3877 [](User *U) { return isa<GetElementPtrInst>(U); })) {
3878 // Use getExtractWithExtendCost() to calculate the cost of
3879 // extractelement/ext pair.
3880 CommonCost -= TTI->getExtractWithExtendCost(
3881 Ext->getOpcode(), Ext->getType(), VecTy, I);
3882 // Add back the cost of s|zext which is subtracted separately.
3883 CommonCost += TTI->getCastInstrCost(
3884 Ext->getOpcode(), Ext->getType(), EI->getType(),
3885 TTI::getCastContextHint(Ext), CostKind, Ext);
3886 continue;
3887 }
3888 }
3889 CommonCost -=
3890 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
3891 }
3892 } else {
3893 AdjustExtractsCost(CommonCost, /*IsGather=*/false);
3894 }
3895 return CommonCost;
3896 }
3897 case Instruction::InsertElement: {
3898 auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
3899
3900 unsigned const NumElts = SrcVecTy->getNumElements();
3901 unsigned const NumScalars = VL.size();
3902 APInt DemandedElts = APInt::getNullValue(NumElts);
3903 // TODO: Add support for Instruction::InsertValue.
3904 unsigned Offset = UINT_MAX(2147483647 *2U +1U);
3905 bool IsIdentity = true;
3906 SmallVector<int> ShuffleMask(NumElts, UndefMaskElem);
3907 for (unsigned I = 0; I < NumScalars; ++I) {
3908 Optional<int> InsertIdx = getInsertIndex(VL[I], 0);
3909 if (!InsertIdx || *InsertIdx == UndefMaskElem)
3910 continue;
3911 unsigned Idx = *InsertIdx;
3912 DemandedElts.setBit(Idx);
3913 if (Idx < Offset) {
3914 Offset = Idx;
3915 IsIdentity &= I == 0;
3916 } else {
3917 assert(Idx >= Offset && "Failed to find vector index offset")(static_cast<void> (0));
3918 IsIdentity &= Idx - Offset == I;
3919 }
3920 ShuffleMask[Idx] = I;
3921 }
3922 assert(Offset < NumElts && "Failed to find vector index offset")(static_cast<void> (0));
3923
3924 InstructionCost Cost = 0;
3925 Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
3926 /*Insert*/ true, /*Extract*/ false);
3927
3928 if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
3929 // FIXME: Replace with SK_InsertSubvector once it is properly supported.
3930 unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
3931 Cost += TTI->getShuffleCost(
3932 TargetTransformInfo::SK_PermuteSingleSrc,
3933 FixedVectorType::get(SrcVecTy->getElementType(), Sz));
3934 } else if (!IsIdentity) {
3935 Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy,
3936 ShuffleMask);
3937 }
3938
3939 return Cost;
3940 }
3941 case Instruction::ZExt:
3942 case Instruction::SExt:
3943 case Instruction::FPToUI:
3944 case Instruction::FPToSI:
3945 case Instruction::FPExt:
3946 case Instruction::PtrToInt:
3947 case Instruction::IntToPtr:
3948 case Instruction::SIToFP:
3949 case Instruction::UIToFP:
3950 case Instruction::Trunc:
3951 case Instruction::FPTrunc:
3952 case Instruction::BitCast: {
3953 Type *SrcTy = VL0->getOperand(0)->getType();
3954 InstructionCost ScalarEltCost =
3955 TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
3956 TTI::getCastContextHint(VL0), CostKind, VL0);
3957 if (NeedToShuffleReuses) {
3958 CommonCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
3959 }
3960
3961 // Calculate the cost of this instruction.
3962 InstructionCost ScalarCost = VL.size() * ScalarEltCost;
3963
3964 auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
3965 InstructionCost VecCost = 0;
3966 // Check if the values are candidates to demote.
3967 if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
3968 VecCost = CommonCost + TTI->getCastInstrCost(
3969 E->getOpcode(), VecTy, SrcVecTy,
3970 TTI::getCastContextHint(VL0), CostKind, VL0);
3971 }
3972 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost))do { } while (false);
3973 return VecCost - ScalarCost;
3974 }
3975 case Instruction::FCmp:
3976 case Instruction::ICmp:
3977 case Instruction::Select: {
3978 // Calculate the cost of this instruction.
3979 InstructionCost ScalarEltCost =
3980 TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
3981 CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
3982 if (NeedToShuffleReuses) {
3983 CommonCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
3984 }
3985 auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
3986 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
3987
3988 // Check if all entries in VL are either compares or selects with compares
3989 // as condition that have the same predicates.
3990 CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
3991 bool First = true;
3992 for (auto *V : VL) {
3993 CmpInst::Predicate CurrentPred;
3994 auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
3995 if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
3996 !match(V, MatchCmp)) ||
3997 (!First && VecPred != CurrentPred)) {
3998 VecPred = CmpInst::BAD_ICMP_PREDICATE;
3999 break;
4000 }
4001 First = false;
4002 VecPred = CurrentPred;
4003 }
4004
4005 InstructionCost VecCost = TTI->getCmpSelInstrCost(
4006 E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
4007 // Check if it is possible and profitable to use min/max for selects in
4008 // VL.
4009 //
4010 auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
4011 if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
4012 IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
4013 {VecTy, VecTy});
4014 InstructionCost IntrinsicCost =
4015 TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
4016 // If the selects are the only uses of the compares, they will be dead
4017 // and we can adjust the cost by removing their cost.
4018 if (IntrinsicAndUse.second)
4019 IntrinsicCost -=
4020 TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, MaskTy,
4021 CmpInst::BAD_ICMP_PREDICATE, CostKind);
4022 VecCost = std::min(VecCost, IntrinsicCost);
4023 }
4024 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost))do { } while (false);
4025 return CommonCost + VecCost - ScalarCost;
4026 }
4027 case Instruction::FNeg:
4028 case Instruction::Add:
4029 case Instruction::FAdd:
4030 case Instruction::Sub:
4031 case Instruction::FSub:
4032 case Instruction::Mul:
4033 case Instruction::FMul:
4034 case Instruction::UDiv:
4035 case Instruction::SDiv:
4036 case Instruction::FDiv:
4037 case Instruction::URem:
4038 case Instruction::SRem:
4039 case Instruction::FRem:
4040 case Instruction::Shl:
4041 case Instruction::LShr:
4042 case Instruction::AShr:
4043 case Instruction::And:
4044 case Instruction::Or:
4045 case Instruction::Xor: {
4046 // Certain instructions can be cheaper to vectorize if they have a
4047 // constant second vector operand.
4048 TargetTransformInfo::OperandValueKind Op1VK =
4049 TargetTransformInfo::OK_AnyValue;
4050 TargetTransformInfo::OperandValueKind Op2VK =
4051 TargetTransformInfo::OK_UniformConstantValue;
4052 TargetTransformInfo::OperandValueProperties Op1VP =
4053 TargetTransformInfo::OP_None;
4054 TargetTransformInfo::OperandValueProperties Op2VP =
4055 TargetTransformInfo::OP_PowerOf2;
4056
4057 // If all operands are exactly the same ConstantInt then set the
4058 // operand kind to OK_UniformConstantValue.
4059 // If instead not all operands are constants, then set the operand kind
4060 // to OK_AnyValue. If all operands are constants but not the same,
4061 // then set the operand kind to OK_NonUniformConstantValue.
4062 ConstantInt *CInt0 = nullptr;
4063 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
4064 const Instruction *I = cast<Instruction>(VL[i]);
4065 unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
4066 ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
4067 if (!CInt) {
4068 Op2VK = TargetTransformInfo::OK_AnyValue;
4069 Op2VP = TargetTransformInfo::OP_None;
4070 break;
4071 }
4072 if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
4073 !CInt->getValue().isPowerOf2())
4074 Op2VP = TargetTransformInfo::OP_None;
4075 if (i == 0) {
4076 CInt0 = CInt;
4077 continue;
4078 }
4079 if (CInt0 != CInt)
4080 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
4081 }
4082
4083 SmallVector<const Value *, 4> Operands(VL0->operand_values());
4084 InstructionCost ScalarEltCost =
4085 TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
4086 Op2VK, Op1VP, Op2VP, Operands, VL0);
4087 if (NeedToShuffleReuses) {
4088 CommonCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
4089 }
4090 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
4091 InstructionCost VecCost =
4092 TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
4093 Op2VK, Op1VP, Op2VP, Operands, VL0);
4094 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost))do { } while (false);
4095 return CommonCost + VecCost - ScalarCost;
4096 }
4097 case Instruction::GetElementPtr: {
4098 TargetTransformInfo::OperandValueKind Op1VK =
4099 TargetTransformInfo::OK_AnyValue;
4100 TargetTransformInfo::OperandValueKind Op2VK =
4101 TargetTransformInfo::OK_UniformConstantValue;
4102
4103 InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
4104 Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
4105 if (NeedToShuffleReuses) {
4106 CommonCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
4107 }
4108 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
4109 InstructionCost VecCost = TTI->getArithmeticInstrCost(
4110 Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
4111 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost))do { } while (false);
4112 return CommonCost + VecCost - ScalarCost;
4113 }
4114 case Instruction::Load: {
4115 // Cost of wide load - cost of scalar loads.
4116 Align Alignment = cast<LoadInst>(VL0)->getAlign();
4117 InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
4118 Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
4119 if (NeedToShuffleReuses) {
4120 CommonCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
4121 }
4122 InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
4123 InstructionCost VecLdCost;
4124 if (E->State == TreeEntry::Vectorize) {
4125 VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
4126 CostKind, VL0);
4127 } else {
4128 assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState")(static_cast<void> (0));
4129 Align CommonAlignment = Alignment;
4130 for (Value *V : VL)
4131 CommonAlignment =
4132 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
4133 VecLdCost = TTI->getGatherScatterOpCost(
4134 Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
4135 /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
4136 }
4137 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost))do { } while (false);
4138 return CommonCost + VecLdCost - ScalarLdCost;
4139 }
4140 case Instruction::Store: {
4141 // We know that we can merge the stores. Calculate the cost.
4142 bool IsReorder = !E->ReorderIndices.empty();
4143 auto *SI =
4144 cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
4145 Align Alignment = SI->getAlign();
4146 InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
4147 Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
4148 InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
4149 InstructionCost VecStCost = TTI->getMemoryOpCost(
4150 Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
4151 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost))do { } while (false);
4152 return CommonCost + VecStCost - ScalarStCost;
4153 }
4154 case Instruction::Call: {
4155 CallInst *CI = cast<CallInst>(VL0);
4156 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4157
4158 // Calculate the cost of the scalar and vector calls.
4159 IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
4160 InstructionCost ScalarEltCost =
4161 TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
4162 if (NeedToShuffleReuses) {
4163 CommonCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
4164 }
4165 InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
4166
4167 auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
4168 InstructionCost VecCallCost =
4169 std::min(VecCallCosts.first, VecCallCosts.second);
4170
4171 LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCostdo { } while (false)
4172 << " (" << VecCallCost << "-" << ScalarCallCost << ")"do { } while (false)
4173 << " for " << *CI << "\n")do { } while (false);
4174
4175 return CommonCost + VecCallCost - ScalarCallCost;
4176 }
4177 case Instruction::ShuffleVector: {
4178 assert(E->isAltShuffle() &&(static_cast<void> (0))
4179 ((Instruction::isBinaryOp(E->getOpcode()) &&(static_cast<void> (0))
4180 Instruction::isBinaryOp(E->getAltOpcode())) ||(static_cast<void> (0))
4181 (Instruction::isCast(E->getOpcode()) &&(static_cast<void> (0))
4182 Instruction::isCast(E->getAltOpcode()))) &&(static_cast<void> (0))
4183 "Invalid Shuffle Vector Operand")(static_cast<void> (0));
4184 InstructionCost ScalarCost = 0;
4185 if (NeedToShuffleReuses) {
4186 for (unsigned Idx : E->ReuseShuffleIndices) {
4187 Instruction *I = cast<Instruction>(VL[Idx]);
4188 CommonCost -= TTI->getInstructionCost(I, CostKind);
4189 }
4190 for (Value *V : VL) {
4191 Instruction *I = cast<Instruction>(V);
4192 CommonCost += TTI->getInstructionCost(I, CostKind);
4193 }
4194 }
4195 for (Value *V : VL) {
4196 Instruction *I = cast<Instruction>(V);
4197 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode")(static_cast<void> (0));
4198 ScalarCost += TTI->getInstructionCost(I, CostKind);
4199 }
4200 // VecCost is equal to sum of the cost of creating 2 vectors
4201 // and the cost of creating shuffle.
4202 InstructionCost VecCost = 0;
4203 if (Instruction::isBinaryOp(E->getOpcode())) {
4204 VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
4205 VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
4206 CostKind);
4207 } else {
4208 Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
4209 Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
4210 auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
4211 auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
4212 VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
4213 TTI::CastContextHint::None, CostKind);
4214 VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
4215 TTI::CastContextHint::None, CostKind);
4216 }
4217
4218 SmallVector<int> Mask(E->Scalars.size());
4219 for (unsigned I = 0, End = E->Scalars.size(); I < End; ++I) {
4220 auto *OpInst = cast<Instruction>(E->Scalars[I]);
4221 assert(E->isOpcodeOrAlt(OpInst) && "Unexpected main/alternate opcode")(static_cast<void> (0));
4222 Mask[I] = I + (OpInst->getOpcode() == E->getAltOpcode() ? End : 0);
4223 }
4224 VecCost +=
4225 TTI->getShuffleCost(TargetTransformInfo::SK_Select, VecTy, Mask, 0);
4226 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost))do { } while (false);
4227 return CommonCost + VecCost - ScalarCost;
4228 }
4229 default:
4230 llvm_unreachable("Unknown instruction")__builtin_unreachable();
4231 }
4232}
4233
4234bool BoUpSLP::isFullyVectorizableTinyTree() const {
4235 LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "do { } while (false)
4236 << VectorizableTree.size() << " is fully vectorizable .\n")do { } while (false);
4237
4238 // We only handle trees of heights 1 and 2.
4239 if (VectorizableTree.size() == 1 &&
4240 VectorizableTree[0]->State == TreeEntry::Vectorize)
4241 return true;
4242
4243 if (VectorizableTree.size() != 2)
4244 return false;
4245
4246 // Handle splat and all-constants stores. Also try to vectorize tiny trees
4247 // with the second gather nodes if they have less scalar operands rather than
4248 // the initial tree element (may be profitable to shuffle the second gather)
4249 // or they are extractelements, which form shuffle.
4250 SmallVector<int> Mask;
4251 if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
4252 (allConstant(VectorizableTree[1]->Scalars) ||
4253 isSplat(VectorizableTree[1]->Scalars) ||
4254 (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
4255 VectorizableTree[1]->Scalars.size() <
4256 VectorizableTree[0]->Scalars.size()) ||
4257 (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
4258 VectorizableTree[1]->getOpcode() == Instruction::ExtractElement &&
4259 isShuffle(VectorizableTree[1]->Scalars, Mask))))
4260 return true;
4261
4262 // Gathering cost would be too much for tiny trees.
4263 if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
4264 VectorizableTree[1]->State == TreeEntry::NeedToGather)
4265 return false;
4266
4267 return true;
4268}
4269
4270static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
4271 TargetTransformInfo *TTI,
4272 bool MustMatchOrInst) {
4273 // Look past the root to find a source value. Arbitrarily follow the
4274 // path through operand 0 of any 'or'. Also, peek through optional
4275 // shift-left-by-multiple-of-8-bits.
4276 Value *ZextLoad = Root;
4277 const APInt *ShAmtC;
4278 bool FoundOr = false;
4279 while (!isa<ConstantExpr>(ZextLoad) &&
4280 (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
4281 (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
4282 ShAmtC->urem(8) == 0))) {
4283 auto *BinOp = cast<BinaryOperator>(ZextLoad);
4284 ZextLoad = BinOp->getOperand(0);
4285 if (BinOp->getOpcode() == Instruction::Or)
4286 FoundOr = true;
4287 }
4288 // Check if the input is an extended load of the required or/shift expression.
4289 Value *LoadPtr;
4290 if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
4291 !match(ZextLoad, m_ZExt(m_Load(m_Value(LoadPtr)))))
4292 return false;
4293
4294 // Require that the total load bit width is a legal integer type.
4295 // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
4296 // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
4297 Type *SrcTy = LoadPtr->getType()->getPointerElementType();
4298 unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
4299 if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
4300 return false;
4301
4302 // Everything matched - assume that we can fold the whole sequence using
4303 // load combining.
4304 LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "do { } while (false)
4305 << *(cast<Instruction>(Root)) << "\n")do { } while (false);
4306
4307 return true;
4308}
4309
4310bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
4311 if (RdxKind != RecurKind::Or)
4312 return false;
4313
4314 unsigned NumElts = VectorizableTree[0]->Scalars.size();
4315 Value *FirstReduced = VectorizableTree[0]->Scalars[0];
4316 return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
4317 /* MatchOr */ false);
4318}
4319
4320bool BoUpSLP::isLoadCombineCandidate() const {
4321 // Peek through a final sequence of stores and check if all operations are
4322 // likely to be load-combined.
4323 unsigned NumElts = VectorizableTree[0]->Scalars.size();
4324 for (Value *Scalar : VectorizableTree[0]->Scalars) {
4325 Value *X;
4326 if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
4327 !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
4328 return false;
4329 }
4330 return true;
4331}
4332
4333bool BoUpSLP::isTreeTinyAndNotFullyVectorizable() const {
4334 // No need to vectorize inserts of gathered values.
4335 if (VectorizableTree.size() == 2 &&
4336 isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
4337 VectorizableTree[1]->State == TreeEntry::NeedToGather)
4338 return true;
4339
4340 // We can vectorize the tree if its size is greater than or equal to the
4341 // minimum size specified by the MinTreeSize command line option.
4342 if (VectorizableTree.size() >= MinTreeSize)
4343 return false;
4344
4345 // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
4346 // can vectorize it if we can prove it fully vectorizable.
4347 if (isFullyVectorizableTinyTree())
4348 return false;
4349
4350 assert(VectorizableTree.empty()(static_cast<void> (0))
4351 ? ExternalUses.empty()(static_cast<void> (0))
4352 : true && "We shouldn't have any external users")(static_cast<void> (0));
4353
4354 // Otherwise, we can't vectorize the tree. It is both tiny and not fully
4355 // vectorizable.
4356 return true;
4357}
4358
4359InstructionCost BoUpSLP::getSpillCost() const {
4360 // Walk from the bottom of the tree to the top, tracking which values are
4361 // live. When we see a call instruction that is not part of our tree,
4362 // query TTI to see if there is a cost to keeping values live over it
4363 // (for example, if spills and fills are required).
4364 unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
4365 InstructionCost Cost = 0;
4366
4367 SmallPtrSet<Instruction*, 4> LiveValues;
4368 Instruction *PrevInst = nullptr;
4369
4370 // The entries in VectorizableTree are not necessarily ordered by their
4371 // position in basic blocks. Collect them and order them by dominance so later
4372 // instructions are guaranteed to be visited first. For instructions in
4373 // different basic blocks, we only scan to the beginning of the block, so
4374 // their order does not matter, as long as all instructions in a basic block
4375 // are grouped together. Using dominance ensures a deterministic order.
4376 SmallVector<Instruction *, 16> OrderedScalars;
4377 for (const auto &TEPtr : VectorizableTree) {
4378 Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
4379 if (!Inst)
4380 continue;
4381 OrderedScalars.push_back(Inst);
4382 }
4383 llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
4384 auto *NodeA = DT->getNode(A->getParent());
4385 auto *NodeB = DT->getNode(B->getParent());
4386 assert(NodeA && "Should only process reachable instructions")(static_cast<void> (0));
4387 assert(NodeB && "Should only process reachable instructions")(static_cast<void> (0));
4388 assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&(static_cast<void> (0))
4389 "Different nodes should have different DFS numbers")(static_cast<void> (0));
4390 if (NodeA != NodeB)
4391 return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
4392 return B->comesBefore(A);
4393 });
4394
4395 for (Instruction *Inst : OrderedScalars) {
4396 if (!PrevInst) {
4397 PrevInst = Inst;
4398 continue;
4399 }
4400
4401 // Update LiveValues.
4402 LiveValues.erase(PrevInst);
4403 for (auto &J : PrevInst->operands()) {
4404 if (isa<Instruction>(&*J) && getTreeEntry(&*J))
4405 LiveValues.insert(cast<Instruction>(&*J));
4406 }
4407
4408 LLVM_DEBUG({do { } while (false)
4409 dbgs() << "SLP: #LV: " << LiveValues.size();do { } while (false)
4410 for (auto *X : LiveValues)do { } while (false)
4411 dbgs() << " " << X->getName();do { } while (false)
4412 dbgs() << ", Looking at ";do { } while (false)
4413 Inst->dump();do { } while (false)
4414 })do { } while (false);
4415
4416 // Now find the sequence of instructions between PrevInst and Inst.
4417 unsigned NumCalls = 0;
4418 BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
4419 PrevInstIt =
4420 PrevInst->getIterator().getReverse();
4421 while (InstIt != PrevInstIt) {
4422 if (PrevInstIt == PrevInst->getParent()->rend()) {
4423 PrevInstIt = Inst->getParent()->rbegin();
4424 continue;
4425 }
4426
4427 // Debug information does not impact spill cost.
4428 if ((isa<CallInst>(&*PrevInstIt) &&
4429 !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
4430 &*PrevInstIt != PrevInst)
4431 NumCalls++;
4432
4433 ++PrevInstIt;
4434 }
4435
4436 if (NumCalls) {
4437 SmallVector<Type*, 4> V;
4438 for (auto *II : LiveValues) {
4439 auto *ScalarTy = II->getType();
4440 if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
4441 ScalarTy = VectorTy->getElementType();
4442 V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
4443 }
4444 Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
4445 }
4446
4447 PrevInst = Inst;
4448 }
4449
4450 return Cost;
4451}
4452
4453InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
4454 InstructionCost Cost = 0;
4455 LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "do { } while (false)
4456 << VectorizableTree.size() << ".\n")do { } while (false);
4457
4458 unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
4459
4460 for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
4461 TreeEntry &TE = *VectorizableTree[I].get();
4462
4463 InstructionCost C = getEntryCost(&TE, VectorizedVals);
4464 Cost += C;
4465 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << Cdo { } while (false)
4466 << " for bundle that starts with " << *TE.Scalars[0]do { } while (false)
4467 << ".\n"do { } while (false)
4468 << "SLP: Current total cost = " << Cost << "\n")do { } while (false);
4469 }
4470
4471 SmallPtrSet<Value *, 16> ExtractCostCalculated;
4472 InstructionCost ExtractCost = 0;
4473 SmallVector<unsigned> VF;
4474 SmallVector<SmallVector<int>> ShuffleMask;
4475 SmallVector<Value *> FirstUsers;
4476 SmallVector<APInt> DemandedElts;
4477 for (ExternalUser &EU : ExternalUses) {
4478 // We only add extract cost once for the same scalar.
4479 if (!ExtractCostCalculated.insert(EU.Scalar).second)
4480 continue;
4481
4482 // Uses by ephemeral values are free (because the ephemeral value will be
4483 // removed prior to code generation, and so the extraction will be
4484 // removed as well).
4485 if (EphValues.count(EU.User))
4486 continue;
4487
4488 // No extract cost for vector "scalar"
4489 if (isa<FixedVectorType>(EU.Scalar->getType()))
4490 continue;
4491
4492 // Already counted the cost for external uses when tried to adjust the cost
4493 // for extractelements, no need to add it again.
4494 if (isa<ExtractElementInst>(EU.Scalar))
4495 continue;
4496
4497 // If found user is an insertelement, do not calculate extract cost but try
4498 // to detect it as a final shuffled/identity match.
4499 if (EU.User && isa<InsertElementInst>(EU.User)) {
4500 if (auto *FTy = dyn_cast<FixedVectorType>(EU.User->getType())) {
4501 Optional<int> InsertIdx = getInsertIndex(EU.User, 0);
4502 if (!InsertIdx || *InsertIdx == UndefMaskElem)
4503 continue;
4504 Value *VU = EU.User;
4505 auto *It = find_if(FirstUsers, [VU](Value *V) {
4506 // Checks if 2 insertelements are from the same buildvector.
4507 if (VU->getType() != V->getType())
4508 return false;
4509 auto *IE1 = cast<InsertElementInst>(VU);
4510 auto *IE2 = cast<InsertElementInst>(V);
4511 // Go though of insertelement instructions trying to find either VU as
4512 // the original vector for IE2 or V as the original vector for IE1.
4513 do {
4514 if (IE1 == VU || IE2 == V)
4515 return true;
4516 if (IE1)
4517 IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
4518 if (IE2)
4519 IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
4520 } while (IE1 || IE2);
4521 return false;
4522 });
4523 int VecId = -1;
4524 if (It == FirstUsers.end()) {
4525 VF.push_back(FTy->getNumElements());
4526 ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
4527 FirstUsers.push_back(EU.User);
4528 DemandedElts.push_back(APInt::getNullValue(VF.back()));
4529 VecId = FirstUsers.size() - 1;
4530 } else {
4531 VecId = std::distance(FirstUsers.begin(), It);
4532 }
4533 int Idx = *InsertIdx;
4534 ShuffleMask[VecId][Idx] = EU.Lane;
4535 DemandedElts[VecId].setBit(Idx);
4536 }
4537 }
4538
4539 // If we plan to rewrite the tree in a smaller type, we will need to sign
4540 // extend the extracted value back to the original type. Here, we account
4541 // for the extract and the added cost of the sign extend if needed.
4542 auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
4543 auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
4544 if (MinBWs.count(ScalarRoot)) {
4545 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
4546 auto Extend =
4547 MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
4548 VecTy = FixedVectorType::get(MinTy, BundleWidth);
4549 ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
4550 VecTy, EU.Lane);
4551 } else {
4552 ExtractCost +=
4553 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
4554 }
4555 }
4556
4557 InstructionCost SpillCost = getSpillCost();
4558 Cost += SpillCost + ExtractCost;
4559 for (int I = 0, E = FirstUsers.size(); I < E; ++I) {
4560 // For the very first element - simple shuffle of the source vector.
4561 int Limit = ShuffleMask[I].size() * 2;
4562 if (I == 0 &&
4563 all_of(ShuffleMask[I], [Limit](int Idx) { return Idx < Limit; }) &&
4564 !ShuffleVectorInst::isIdentityMask(ShuffleMask[I])) {
4565 InstructionCost C = TTI->getShuffleCost(
4566 TTI::SK_PermuteSingleSrc,
4567 cast<FixedVectorType>(FirstUsers[I]->getType()), ShuffleMask[I]);
4568 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << Cdo { } while (false)
4569 << " for final shuffle of insertelement external users "do { } while (false)
4570 << *VectorizableTree.front()->Scalars.front() << ".\n"do { } while (false)
4571 << "SLP: Current total cost = " << Cost << "\n")do { } while (false);
4572 Cost += C;
4573 continue;
4574 }
4575 // Other elements - permutation of 2 vectors (the initial one and the next
4576 // Ith incoming vector).
4577 unsigned VF = ShuffleMask[I].size();
4578 for (unsigned Idx = 0; Idx < VF; ++Idx) {
4579 int &Mask = ShuffleMask[I][Idx];
4580 Mask = Mask == UndefMaskElem ? Idx : VF + Mask;
4581 }
4582 InstructionCost C = TTI->getShuffleCost(
4583 TTI::SK_PermuteTwoSrc, cast<FixedVectorType>(FirstUsers[I]->getType()),
4584 ShuffleMask[I]);
4585 LLVM_DEBUG(do { } while (false)
4586 dbgs()do { } while (false)
4587 << "SLP: Adding cost " << Cdo { } while (false)
4588 << " for final shuffle of vector node and external insertelement users "do { } while (false)
4589 << *VectorizableTree.front()->Scalars.front() << ".\n"do { } while (false)
4590 << "SLP: Current total cost = " << Cost << "\n")do { } while (false);
4591 Cost += C;
4592 InstructionCost InsertCost = TTI->getScalarizationOverhead(
4593 cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
4594 /*Insert*/ true,
4595 /*Extract*/ false);
4596 Cost -= InsertCost;
4597 LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCostdo { } while (false)
4598 << " for insertelements gather.\n"do { } while (false)
4599 << "SLP: Current total cost = " << Cost << "\n")do { } while (false);
4600 }
4601
4602#ifndef NDEBUG1
4603 SmallString<256> Str;
4604 {
4605 raw_svector_ostream OS(Str);
4606 OS << "SLP: Spill Cost = " << SpillCost << ".\n"
4607 << "SLP: Extract Cost = " << ExtractCost << ".\n"
4608 << "SLP: Total Cost = " << Cost << ".\n";
4609 }
4610 LLVM_DEBUG(dbgs() << Str)do { } while (false);
4611 if (ViewSLPTree)
4612 ViewGraph(this, "SLP" + F->getName(), false, Str);
4613#endif
4614
4615 return Cost;
4616}
4617
4618Optional<TargetTransformInfo::ShuffleKind>
4619BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
4620 SmallVectorImpl<const TreeEntry *> &Entries) {
4621 // TODO: currently checking only for Scalars in the tree entry, need to count
4622 // reused elements too for better cost estimation.
4623 Mask.assign(TE->Scalars.size(), UndefMaskElem);
4624 Entries.clear();
4625 // Build a lists of values to tree entries.
4626 DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
4627 for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
4628 if (EntryPtr.get() == TE)
4629 break;
4630 if (EntryPtr->State != TreeEntry::NeedToGather)
4631 continue;
4632 for (Value *V : EntryPtr->Scalars)
4633 ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
4634 }
4635 // Find all tree entries used by the gathered values. If no common entries
4636 // found - not a shuffle.
4637 // Here we build a set of tree nodes for each gathered value and trying to
4638 // find the intersection between these sets. If we have at least one common
4639 // tree node for each gathered value - we have just a permutation of the
4640 // single vector. If we have 2 different sets, we're in situation where we
4641 // have a permutation of 2 input vectors.
4642 SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
4643 DenseMap<Value *, int> UsedValuesEntry;
4644 for (Value *V : TE->Scalars) {
4645 if (isa<UndefValue>(V))
4646 continue;
4647 // Build a list of tree entries where V is used.
4648 SmallPtrSet<const TreeEntry *, 4> VToTEs;
4649 auto It = ValueToTEs.find(V);
4650 if (It != ValueToTEs.end())
4651 VToTEs = It->second;
4652 if (const TreeEntry *VTE = getTreeEntry(V))
4653 VToTEs.insert(VTE);
4654 if (VToTEs.empty())
4655 return None;
4656 if (UsedTEs.empty()) {
4657 // The first iteration, just insert the list of nodes to vector.
4658 UsedTEs.push_back(VToTEs);
4659 } else {
4660 // Need to check if there are any previously used tree nodes which use V.
4661 // If there are no such nodes, consider that we have another one input
4662 // vector.
4663 SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
4664 unsigned Idx = 0;
4665 for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
4666 // Do we have a non-empty intersection of previously listed tree entries
4667 // and tree entries using current V?
4668 set_intersect(VToTEs, Set);
4669 if (!VToTEs.empty()) {
4670 // Yes, write the new subset and continue analysis for the next
4671 // scalar.
4672 Set.swap(VToTEs);
4673 break;
4674 }
4675 VToTEs = SavedVToTEs;
4676 ++Idx;
4677 }
4678 // No non-empty intersection found - need to add a second set of possible
4679 // source vectors.
4680 if (Idx == UsedTEs.size()) {
4681 // If the number of input vectors is greater than 2 - not a permutation,
4682 // fallback to the regular gather.
4683 if (UsedTEs.size() == 2)
4684 return None;
4685 UsedTEs.push_back(SavedVToTEs);
4686 Idx = UsedTEs.size() - 1;
4687 }
4688 UsedValuesEntry.try_emplace(V, Idx);
4689 }
4690 }
4691
4692 unsigned VF = 0;
4693 if (UsedTEs.size() == 1) {
4694 // Try to find the perfect match in another gather node at first.
4695 auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
4696 return EntryPtr->isSame(TE->Scalars);
4697 });
4698 if (It != UsedTEs.front().end()) {
4699 Entries.push_back(*It);
4700 std::iota(Mask.begin(), Mask.end(), 0);
4701 return TargetTransformInfo::SK_PermuteSingleSrc;
4702 }
4703 // No perfect match, just shuffle, so choose the first tree node.
4704 Entries.push_back(*UsedTEs.front().begin());
4705 } else {
4706 // Try to find nodes with the same vector factor.
4707 assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.")(static_cast<void> (0));
4708 // FIXME: Shall be replaced by GetVF function once non-power-2 patch is
4709 // landed.
4710 auto &&GetVF = [](const TreeEntry *TE) {
4711 if (!TE->ReuseShuffleIndices.empty())
4712 return TE->ReuseShuffleIndices.size();
4713 return TE->Scalars.size();
4714 };
4715 DenseMap<int, const TreeEntry *> VFToTE;
4716 for (const TreeEntry *TE : UsedTEs.front())
4717 VFToTE.try_emplace(GetVF(TE), TE);
4718 for (const TreeEntry *TE : UsedTEs.back()) {
4719 auto It = VFToTE.find(GetVF(TE));
4720 if (It != VFToTE.end()) {
4721 VF = It->first;
4722 Entries.push_back(It->second);
4723 Entries.push_back(TE);
4724 break;
4725 }
4726 }
4727 // No 2 source vectors with the same vector factor - give up and do regular
4728 // gather.
4729 if (Entries.empty())
4730 return None;
4731 }
4732
4733 // Build a shuffle mask for better cost estimation and vector emission.
4734 for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
4735 Value *V = TE->Scalars[I];
4736 if (isa<UndefValue>(V))
4737 continue;
4738 unsigned Idx = UsedValuesEntry.lookup(V);
4739 const TreeEntry *VTE = Entries[Idx];
4740 int FoundLane = VTE->findLaneForValue(V);
4741 Mask[I] = Idx * VF + FoundLane;
4742 // Extra check required by isSingleSourceMaskImpl function (called by
4743 // ShuffleVectorInst::isSingleSourceMask).
4744 if (Mask[I] >= 2 * E)
4745 return None;
4746 }
4747 switch (Entries.size()) {
4748 case 1:
4749 return TargetTransformInfo::SK_PermuteSingleSrc;
4750 case 2:
4751 return TargetTransformInfo::SK_PermuteTwoSrc;
4752 default:
4753 break;
4754 }
4755 return None;
4756}
4757
4758InstructionCost
4759BoUpSLP::getGatherCost(FixedVectorType *Ty,
4760 const DenseSet<unsigned> &ShuffledIndices) const {
4761 unsigned NumElts = Ty->getNumElements();
4762 APInt DemandedElts = APInt::getNullValue(NumElts);
4763 for (unsigned I = 0; I < NumElts; ++I)
4764 if (!ShuffledIndices.count(I))
4765 DemandedElts.setBit(I);
4766 InstructionCost Cost =
4767 TTI->getScalarizationOverhead(Ty, DemandedElts, /*Insert*/ true,
4768 /*Extract*/ false);
4769 if (!ShuffledIndices.empty())
4770 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
4771 return Cost;
4772}
4773
4774InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
4775 // Find the type of the operands in VL.
4776 Type *ScalarTy = VL[0]->getType();
4777 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
4778 ScalarTy = SI->getValueOperand()->getType();
4779 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
4780 // Find the cost of inserting/extracting values from the vector.
4781 // Check if the same elements are inserted several times and count them as
4782 // shuffle candidates.
4783 DenseSet<unsigned> ShuffledElements;
4784 DenseSet<Value *> UniqueElements;
4785 // Iterate in reverse order to consider insert elements with the high cost.
4786 for (unsigned I = VL.size(); I > 0; --I) {
4787 unsigned Idx = I - 1;
4788 if (isConstant(VL[Idx]))
4789 continue;
4790 if (!UniqueElements.insert(VL[Idx]).second)
4791 ShuffledElements.insert(Idx);
4792 }
4793 return getGatherCost(VecTy, ShuffledElements);
4794}
4795
4796// Perform operand reordering on the instructions in VL and return the reordered
4797// operands in Left and Right.
4798void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
4799 SmallVectorImpl<Value *> &Left,
4800 SmallVectorImpl<Value *> &Right,
4801 const DataLayout &DL,
4802 ScalarEvolution &SE,
4803 const BoUpSLP &R) {
4804 if (VL.empty())
4805 return;
4806 VLOperands Ops(VL, DL, SE, R);
4807 // Reorder the operands in place.
4808 Ops.reorder();
4809 Left = Ops.getVL(0);
4810 Right = Ops.getVL(1);
4811}
4812
4813void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
4814 // Get the basic block this bundle is in. All instructions in the bundle
4815 // should be in this block.
4816 auto *Front = E->getMainOp();
4817 auto *BB = Front->getParent();
4818 assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {(static_cast<void> (0))
4819 auto *I = cast<Instruction>(V);(static_cast<void> (0))
4820 return !E->isOpcodeOrAlt(I) || I->getParent() == BB;(static_cast<void> (0))
4821 }))(static_cast<void> (0));
4822
4823 // The last instruction in the bundle in program order.
4824 Instruction *LastInst = nullptr;
4825
4826 // Find the last instruction. The common case should be that BB has been
4827 // scheduled, and the last instruction is VL.back(). So we start with
4828 // VL.back() and iterate over schedule data until we reach the end of the
4829 // bundle. The end of the bundle is marked by null ScheduleData.
4830 if (BlocksSchedules.count(BB)) {
4831 auto *Bundle =
4832 BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
4833 if (Bundle && Bundle->isPartOfBundle())
4834 for (; Bundle; Bundle = Bundle->NextInBundle)
4835 if (Bundle->OpValue == Bundle->Inst)
4836 LastInst = Bundle->Inst;
4837 }
4838
4839 // LastInst can still be null at this point if there's either not an entry
4840 // for BB in BlocksSchedules or there's no ScheduleData available for
4841 // VL.back(). This can be the case if buildTree_rec aborts for various
4842 // reasons (e.g., the maximum recursion depth is reached, the maximum region
4843 // size is reached, etc.). ScheduleData is initialized in the scheduling
4844 // "dry-run".
4845 //
4846 // If this happens, we can still find the last instruction by brute force. We
4847 // iterate forwards from Front (inclusive) until we either see all
4848 // instructions in the bundle or reach the end of the block. If Front is the
4849 // last instruction in program order, LastInst will be set to Front, and we
4850 // will visit all the remaining instructions in the block.
4851 //
4852 // One of the reasons we exit early from buildTree_rec is to place an upper
4853 // bound on compile-time. Thus, taking an additional compile-time hit here is
4854 // not ideal. However, this should be exceedingly rare since it requires that
4855 // we both exit early from buildTree_rec and that the bundle be out-of-order
4856 // (causing us to iterate all the way to the end of the block).
4857 if (!LastInst) {
4858 SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
4859 for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
4860 if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
4861 LastInst = &I;
4862 if (Bundle.empty())
4863 break;
4864 }
4865 }
4866 assert(LastInst && "Failed to find last instruction in bundle")(static_cast<void> (0));
4867
4868 // Set the insertion point after the last instruction in the bundle. Set the
4869 // debug location to Front.
4870 Builder.SetInsertPoint(BB, ++LastInst->getIterator());
4871 Builder.SetCurrentDebugLocation(Front->getDebugLoc());
4872}
4873
4874Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
4875 // List of instructions/lanes from current block and/or the blocks which are
4876 // part of the current loop. These instructions will be inserted at the end to
4877 // make it possible to optimize loops and hoist invariant instructions out of
4878 // the loops body with better chances for success.
4879 SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
4880 SmallSet<int, 4> PostponedIndices;
4881 Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
4882 auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
4883 SmallPtrSet<BasicBlock *, 4> Visited;
4884 while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
4885 InsertBB = InsertBB->getSinglePredecessor();
4886 return InsertBB && InsertBB == InstBB;
4887 };
4888 for (int I = 0, E = VL.size(); I < E; ++I) {
4889 if (auto *Inst = dyn_cast<Instruction>(VL[I]))
4890 if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
4891 getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
4892 PostponedIndices.insert(I).second)
4893 PostponedInsts.emplace_back(Inst, I);
4894 }
4895
4896 auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
4897 Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
4898 auto *InsElt = dyn_cast<InsertElementInst>(Vec);
4899 if (!InsElt)
4900 return Vec;
4901 GatherSeq.insert(InsElt);
4902 CSEBlocks.insert(InsElt->getParent());
4903 // Add to our 'need-to-extract' list.
4904 if (TreeEntry *Entry = getTreeEntry(V)) {
4905 // Find which lane we need to extract.
4906 unsigned FoundLane = Entry->findLaneForValue(V);
4907 ExternalUses.emplace_back(V, InsElt, FoundLane);
4908 }
4909 return Vec;
4910 };
4911 Value *Val0 =
4912 isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
4913 FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
4914 Value *Vec = PoisonValue::get(VecTy);
4915 SmallVector<int> NonConsts;
4916 // Insert constant values at first.
4917 for (int I = 0, E = VL.size(); I < E; ++I) {
4918 if (PostponedIndices.contains(I))
4919 continue;
4920 if (!isConstant(VL[I])) {
4921 NonConsts.push_back(I);
4922 continue;
4923 }
4924 Vec = CreateInsertElement(Vec, VL[I], I);
4925 }
4926 // Insert non-constant values.
4927 for (int I : NonConsts)
4928 Vec = CreateInsertElement(Vec, VL[I], I);
4929 // Append instructions, which are/may be part of the loop, in the end to make
4930 // it possible to hoist non-loop-based instructions.
4931 for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
4932 Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
4933
4934 return Vec;
4935}
4936
4937namespace {
4938/// Merges shuffle masks and emits final shuffle instruction, if required.
4939class ShuffleInstructionBuilder {
4940 IRBuilderBase &Builder;
4941 const unsigned VF = 0;
4942 bool IsFinalized = false;
4943 SmallVector<int, 4> Mask;
4944
4945public:
4946 ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF)
4947 : Builder(Builder), VF(VF) {}
4948
4949 /// Adds a mask, inverting it before applying.
4950 void addInversedMask(ArrayRef<unsigned> SubMask) {
4951 if (SubMask.empty())
4952 return;
4953 SmallVector<int, 4> NewMask;
4954 inversePermutation(SubMask, NewMask);
4955 addMask(NewMask);
4956 }
4957
4958 /// Functions adds masks, merging them into single one.
4959 void addMask(ArrayRef<unsigned> SubMask) {
4960 SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
4961 addMask(NewMask);
4962 }
4963
4964 void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
4965
4966 Value *finalize(Value *V) {
4967 IsFinalized = true;
4968 unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
4969 if (VF == ValueVF && Mask.empty())
4970 return V;
4971 SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
4972 std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
4973 addMask(NormalizedMask);
4974
4975 if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
4976 return V;
4977 return Builder.CreateShuffleVector(V, Mask, "shuffle");
4978 }
4979
4980 ~ShuffleInstructionBuilder() {
4981 assert((IsFinalized || Mask.empty()) &&(static_cast<void> (0))
4982 "Shuffle construction must be finalized.")(static_cast<void> (0));
4983 }
4984};
4985} // namespace
4986
4987Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
4988 unsigned VF = VL.size();
4989 InstructionsState S = getSameOpcode(VL);
4990 if (S.getOpcode()) {
4991 if (TreeEntry *E = getTreeEntry(S.OpValue))
4992 if (E->isSame(VL)) {
4993 Value *V = vectorizeTree(E);
4994 if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
4995 if (!E->ReuseShuffleIndices.empty()) {
4996 // Reshuffle to get only unique values.
4997 // If some of the scalars are duplicated in the vectorization tree
4998 // entry, we do not vectorize them but instead generate a mask for
4999 // the reuses. But if there are several users of the same entry,
5000 // they may have different vectorization factors. This is especially
5001 // important for PHI nodes. In this case, we need to adapt the
5002 // resulting instruction for the user vectorization factor and have
5003 // to reshuffle it again to take only unique elements of the vector.
5004 // Without this code the function incorrectly returns reduced vector
5005 // instruction with the same elements, not with the unique ones.
5006
5007 // block:
5008 // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
5009 // %2 = shuffle <2 x > %phi, %poison, <4 x > <0, 0, 1, 1>
5010 // ... (use %2)
5011 // %shuffle = shuffle <2 x> %2, poison, <2 x> {0, 2}
5012 // br %block
5013 SmallVector<int> UniqueIdxs;
5014 SmallSet<int, 4> UsedIdxs;
5015 int Pos = 0;
5016 int Sz = VL.size();
5017 for (int Idx : E->ReuseShuffleIndices) {
5018 if (Idx != Sz && UsedIdxs.insert(Idx).second)
5019 UniqueIdxs.emplace_back(Pos);
5020 ++Pos;
5021 }
5022 assert(VF >= UsedIdxs.size() && "Expected vectorization factor "(static_cast<void> (0))
5023 "less than original vector size.")(static_cast<void> (0));
5024 UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
5025 V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
5026 } else {
5027 assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&(static_cast<void> (0))
5028 "Expected vectorization factor less "(static_cast<void> (0))
5029 "than original vector size.")(static_cast<void> (0));
5030 SmallVector<int> UniformMask(VF, 0);
5031 std::iota(UniformMask.begin(), UniformMask.end(), 0);
5032 V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
5033 }
5034 }
5035 return V;
5036 }
5037 }
5038
5039 // Check that every instruction appears once in this bundle.
5040 SmallVector<int> ReuseShuffleIndicies;
5041 SmallVector<Value *> UniqueValues;
5042 if (VL.size() > 2) {
5043 DenseMap<Value *, unsigned> UniquePositions;
5044 unsigned NumValues =
5045 std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
5046 return !isa<UndefValue>(V);
5047 }).base());
5048 VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
5049 int UniqueVals = 0;
5050 for (Value *V : VL.drop_back(VL.size() - VF)) {
5051 if (isa<UndefValue>(V)) {
5052 ReuseShuffleIndicies.emplace_back(UndefMaskElem);
5053 continue;
5054 }
5055 if (isConstant(V)) {
5056 ReuseShuffleIndicies.emplace_back(UniqueValues.size());
5057 UniqueValues.emplace_back(V);
5058 continue;
5059 }
5060 auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
5061 ReuseShuffleIndicies.emplace_back(Res.first->second);
5062 if (Res.second) {
5063 UniqueValues.emplace_back(V);
5064 ++UniqueVals;
5065 }
5066 }
5067 if (UniqueVals == 1 && UniqueValues.size() == 1) {
5068 // Emit pure splat vector.
5069 ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
5070 UndefMaskElem);
5071 } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
5072 ReuseShuffleIndicies.clear();
5073 UniqueValues.clear();
5074 UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
5075 }
5076 UniqueValues.append(VF - UniqueValues.size(),
5077 PoisonValue::get(VL[0]->getType()));
5078 VL = UniqueValues;
5079 }
5080
5081 ShuffleInstructionBuilder ShuffleBuilder(Builder, VF);
5082 Value *Vec = gather(VL);
5083 if (!ReuseShuffleIndicies.empty()) {
5084 ShuffleBuilder.addMask(ReuseShuffleIndicies);
5085 Vec = ShuffleBuilder.finalize(Vec);
5086 if (auto *I = dyn_cast<Instruction>(Vec)) {
5087 GatherSeq.insert(I);
5088 CSEBlocks.insert(I->getParent());
5089 }
5090 }
5091 return Vec;
5092}
5093
5094Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
5095 IRBuilder<>::InsertPointGuard Guard(Builder);
5096
5097 if (E->VectorizedValue) {
5098 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n")do { } while (false);
5099 return E->VectorizedValue;
5100 }
5101
5102 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5103 unsigned VF = E->Scalars.size();
5104 if (NeedToShuffleReuses)
5105 VF = E->ReuseShuffleIndices.size();
5106 ShuffleInstructionBuilder ShuffleBuilder(Builder, VF);
5107 if (E->State == TreeEntry::NeedToGather) {
5108 setInsertPointAfterBundle(E);
5109 Value *Vec;
5110 SmallVector<int> Mask;
5111 SmallVector<const TreeEntry *> Entries;
5112 Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5113 isGatherShuffledEntry(E, Mask, Entries);
5114 if (Shuffle.hasValue()) {
5115 assert((Entries.size() == 1 || Entries.size() == 2) &&(static_cast<void> (0))
5116 "Expected shuffle of 1 or 2 entries.")(static_cast<void> (0));
5117 Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
5118 Entries.back()->VectorizedValue, Mask);
5119 } else {
5120 Vec = gather(E->Scalars);
5121 }
5122 if (NeedToShuffleReuses) {
5123 ShuffleBuilder.addMask(E->ReuseShuffleIndices);
5124 Vec = ShuffleBuilder.finalize(Vec);
5125 if (auto *I = dyn_cast<Instruction>(Vec)) {
5126 GatherSeq.insert(I);
5127 CSEBlocks.insert(I->getParent());
5128 }
5129 }
5130 E->VectorizedValue = Vec;
5131 return Vec;
5132 }
5133
5134 assert((E->State == TreeEntry::Vectorize ||(static_cast<void> (0))
5135 E->State == TreeEntry::ScatterVectorize) &&(static_cast<void> (0))
5136 "Unhandled state")(static_cast<void> (0));
5137 unsigned ShuffleOrOp =
5138 E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5139 Instruction *VL0 = E->getMainOp();
5140 Type *ScalarTy = VL0->getType();
5141 if (auto *Store = dyn_cast<StoreInst>(VL0))
5142 ScalarTy = Store->getValueOperand()->getType();
5143 else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
5144 ScalarTy = IE->getOperand(1)->getType();
5145 auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
5146 switch (ShuffleOrOp) {
5147 case Instruction::PHI: {
5148 auto *PH = cast<PHINode>(VL0);
5149 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
5150 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
5151 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
5152 Value *V = NewPhi;
5153 if (NeedToShuffleReuses)
5154 V = Builder.CreateShuffleVector(V, E->ReuseShuffleIndices, "shuffle");
5155
5156 E->VectorizedValue = V;
5157
5158 // PHINodes may have multiple entries from the same block. We want to
5159 // visit every block once.
5160 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
5161
5162 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
5163 ValueList Operands;
5164 BasicBlock *IBB = PH->getIncomingBlock(i);
5165
5166 if (!VisitedBBs.insert(IBB).second) {
5167 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
5168 continue;
5169 }
5170
5171 Builder.SetInsertPoint(IBB->getTerminator());
5172 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
5173 Value *Vec = vectorizeTree(E->getOperand(i));
5174 NewPhi->addIncoming(Vec, IBB);
5175 }
5176
5177 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&(static_cast<void> (0))
5178 "Invalid number of incoming values")(static_cast<void> (0));
5179 return V;
5180 }
5181
5182 case Instruction::ExtractElement: {
5183 Value *V = E->getSingleOperand(0);
5184 Builder.SetInsertPoint(VL0);
5185 ShuffleBuilder.addInversedMask(E->ReorderIndices);
5186 ShuffleBuilder.addMask(E->ReuseShuffleIndices);
5187 V = ShuffleBuilder.finalize(V);
5188 E->VectorizedValue = V;
5189 return V;
5190 }
5191 case Instruction::ExtractValue: {
5192 auto *LI = cast<LoadInst>(E->getSingleOperand(0));
5193 Builder.SetInsertPoint(LI);
5194 auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
5195 Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
5196 LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
5197 Value *NewV = propagateMetadata(V, E->Scalars);
5198 ShuffleBuilder.addInversedMask(E->ReorderIndices);
5199 ShuffleBuilder.addMask(E->ReuseShuffleIndices);
5200 NewV = ShuffleBuilder.finalize(NewV);
5201 E->VectorizedValue = NewV;
5202 return NewV;
5203 }
5204 case Instruction::InsertElement: {
5205 Builder.SetInsertPoint(VL0);
5206 Value *V = vectorizeTree(E->getOperand(1));
5207
5208 const unsigned NumElts =
5209 cast<FixedVectorType>(VL0->getType())->getNumElements();
5210 const unsigned NumScalars = E->Scalars.size();
5211
5212 // Create InsertVector shuffle if necessary
5213 Instruction *FirstInsert = nullptr;
5214 bool IsIdentity = true;
5215 unsigned Offset = UINT_MAX(2147483647 *2U +1U);
5216 for (unsigned I = 0; I < NumScalars; ++I) {
5217 Value *Scalar = E->Scalars[I];
5218 if (!FirstInsert &&
5219 !is_contained(E->Scalars, cast<Instruction>(Scalar)->getOperand(0)))
5220 FirstInsert = cast<Instruction>(Scalar);
5221 Optional<int> InsertIdx = getInsertIndex(Scalar, 0);
5222 if (!InsertIdx || *InsertIdx == UndefMaskElem)
5223 continue;
5224 unsigned Idx = *InsertIdx;
5225 if (Idx < Offset) {
5226 Offset = Idx;
5227 IsIdentity &= I == 0;
5228 } else {
5229 assert(Idx >= Offset && "Failed to find vector index offset")(static_cast<void> (0));
5230 IsIdentity &= Idx - Offset == I;
5231 }
5232 }
5233 assert(Offset < NumElts && "Failed to find vector index offset")(static_cast<void> (0));
5234
5235 // Create shuffle to resize vector
5236 SmallVector<int> Mask(NumElts, UndefMaskElem);
5237 if (!IsIdentity) {
5238 for (unsigned I = 0; I < NumScalars; ++I) {
5239 Value *Scalar = E->Scalars[I];
5240 Optional<int> InsertIdx = getInsertIndex(Scalar, 0);
5241 if (!InsertIdx || *InsertIdx == UndefMaskElem)
5242 continue;
5243 Mask[*InsertIdx - Offset] = I;
5244 }
5245 } else {
5246 std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5247 }
5248 if (!IsIdentity || NumElts != NumScalars)
5249 V = Builder.CreateShuffleVector(V, Mask);
5250
5251 if ((!IsIdentity || Offset != 0 ||
5252 !isa<UndefValue>(FirstInsert->getOperand(0))) &&
5253 NumElts != NumScalars) {
5254 SmallVector<int> InsertMask(NumElts);
5255 std::iota(InsertMask.begin(), InsertMask.end(), 0);
5256 for (unsigned I = 0; I < NumElts; I++) {
5257 if (Mask[I] != UndefMaskElem)
5258 InsertMask[Offset + I] = NumElts + I;
5259 }
5260
5261 V = Builder.CreateShuffleVector(
5262 FirstInsert->getOperand(0), V, InsertMask,
5263 cast<Instruction>(E->Scalars.back())->getName());
5264 }
5265
5266 ++NumVectorInstructions;
5267 E->VectorizedValue = V;
5268 return V;
5269 }
5270 case Instruction::ZExt:
5271 case Instruction::SExt:
5272 case Instruction::FPToUI:
5273 case Instruction::FPToSI:
5274 case Instruction::FPExt:
5275 case Instruction::PtrToInt:
5276 case Instruction::IntToPtr:
5277 case Instruction::SIToFP:
5278 case Instruction::UIToFP:
5279 case Instruction::Trunc:
5280 case Instruction::FPTrunc:
5281 case Instruction::BitCast: {
5282 setInsertPointAfterBundle(E);
5283
5284 Value *InVec = vectorizeTree(E->getOperand(0));
5285
5286 if (E->VectorizedValue) {
5287 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { } while (false);
5288 return E->VectorizedValue;
5289 }
5290
5291 auto *CI = cast<CastInst>(VL0);
5292 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
5293 ShuffleBuilder.addMask(E->ReuseShuffleIndices);
5294 V = ShuffleBuilder.finalize(V);
5295
5296 E->VectorizedValue = V;
5297 ++NumVectorInstructions;
5298 return V;
5299 }
5300 case Instruction::FCmp:
5301 case Instruction::ICmp: {
5302 setInsertPointAfterBundle(E);
5303
5304 Value *L = vectorizeTree(E->getOperand(0));
5305 Value *R = vectorizeTree(E->getOperand(1));
5306
5307 if (E->VectorizedValue) {
5308 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { } while (false);
5309 return E->VectorizedValue;
5310 }
5311
5312 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
5313 Value *V = Builder.CreateCmp(P0, L, R);
5314 propagateIRFlags(V, E->Scalars, VL0);
5315 ShuffleBuilder.addMask(E->ReuseShuffleIndices);
5316 V = ShuffleBuilder.finalize(V);
5317
5318 E->VectorizedValue = V;
5319 ++NumVectorInstructions;
5320 return V;
5321 }
5322 case Instruction::Select: {
5323 setInsertPointAfterBundle(E);
5324
5325 Value *Cond = vectorizeTree(E->getOperand(0));
5326 Value *True = vectorizeTree(E->getOperand(1));
5327 Value *False = vectorizeTree(E->getOperand(2));
5328
5329 if (E->VectorizedValue) {
5330 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { } while (false);
5331 return E->VectorizedValue;
5332 }
5333
5334 Value *V = Builder.CreateSelect(Cond, True, False);
5335 ShuffleBuilder.addMask(E->ReuseShuffleIndices);
5336 V = ShuffleBuilder.finalize(V);
5337
5338 E->VectorizedValue = V;
5339 ++NumVectorInstructions;
5340 return V;
5341 }
5342 case Instruction::FNeg: {
5343 setInsertPointAfterBundle(E);
5344
5345 Value *Op = vectorizeTree(E->getOperand(0));
5346
5347 if (E->VectorizedValue) {
5348 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { } while (false);
5349 return E->VectorizedValue;
5350 }
5351
5352 Value *V = Builder.CreateUnOp(
5353 static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
5354 propagateIRFlags(V, E->Scalars, VL0);
5355 if (auto *I = dyn_cast<Instruction>(V))
5356 V = propagateMetadata(I, E->Scalars);
5357
5358 ShuffleBuilder.addMask(E->ReuseShuffleIndices);
5359 V = ShuffleBuilder.finalize(V);
5360
5361 E->VectorizedValue = V;
5362 ++NumVectorInstructions;
5363
5364 return V;
5365 }
5366 case Instruction::Add:
5367 case Instruction::FAdd:
5368 case Instruction::Sub:
5369 case Instruction::FSub:
5370 case Instruction::Mul:
5371 case Instruction::FMul:
5372 case Instruction::UDiv:
5373 case Instruction::SDiv:
5374 case Instruction::FDiv:
5375 case Instruction::URem:
5376 case Instruction::SRem:
5377 case Instruction::FRem:
5378 case Instruction::Shl:
5379 case Instruction::LShr:
5380 case Instruction::AShr:
5381 case Instruction::And:
5382 case Instruction::Or:
5383 case Instruction::Xor: {
5384 setInsertPointAfterBundle(E);
5385
5386 Value *LHS = vectorizeTree(E->getOperand(0));
5387 Value *RHS = vectorizeTree(E->getOperand(1));
5388
5389 if (E->VectorizedValue) {
5390 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { } while (false);
5391 return E->VectorizedValue;
5392 }
5393
5394 Value *V = Builder.CreateBinOp(
5395 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
5396 RHS);
5397 propagateIRFlags(V, E->Scalars, VL0);
5398 if (auto *I = dyn_cast<Instruction>(V))
5399 V = propagateMetadata(I, E->Scalars);
5400
5401 ShuffleBuilder.addMask(E->ReuseShuffleIndices);
5402 V = ShuffleBuilder.finalize(V);
5403
5404 E->VectorizedValue = V;
5405 ++NumVectorInstructions;
5406
5407 return V;
5408 }
5409 case Instruction::Load: {
5410 // Loads are inserted at the head of the tree because we don't want to
5411 // sink them all the way down past store instructions.
5412 bool IsReorder = E->updateStateIfReorder();
5413 if (IsReorder)
5414 VL0 = E->getMainOp();
5415 setInsertPointAfterBundle(E);
5416
5417 LoadInst *LI = cast<LoadInst>(VL0);
5418 Instruction *NewLI;
5419 unsigned AS = LI->getPointerAddressSpace();
5420 Value *PO = LI->getPointerOperand();
5421 if (E->State == TreeEntry::Vectorize) {
5422
5423 Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
5424
5425 // The pointer operand uses an in-tree scalar so we add the new BitCast
5426 // to ExternalUses list to make sure that an extract will be generated
5427 // in the future.
5428 if (getTreeEntry(PO))
5429 ExternalUses.emplace_back(PO, cast<User>(VecPtr), 0);
5430
5431 NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
5432 } else {
5433 assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state")(static_cast<void> (0));
5434 Value *VecPtr = vectorizeTree(E->getOperand(0));
5435 // Use the minimum alignment of the gathered loads.
5436 Align CommonAlignment = LI->getAlign();
5437 for (Value *V : E->Scalars)
5438 CommonAlignment =
5439 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5440 NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
5441 }
5442 Value *V = propagateMetadata(NewLI, E->Scalars);
5443
5444 ShuffleBuilder.addInversedMask(E->ReorderIndices);
5445 ShuffleBuilder.addMask(E->ReuseShuffleIndices);
5446 V = ShuffleBuilder.finalize(V);
5447 E->VectorizedValue = V;
5448 ++NumVectorInstructions;
5449 return V;
5450 }
5451 case Instruction::Store: {
5452 bool IsReorder = !E->ReorderIndices.empty();
5453 auto *SI = cast<StoreInst>(
5454 IsReorder ? E->Scalars[E->ReorderIndices.front()] : VL0);
5455 unsigned AS = SI->getPointerAddressSpace();
5456
5457 setInsertPointAfterBundle(E);
5458
5459 Value *VecValue = vectorizeTree(E->getOperand(0));
5460 ShuffleBuilder.addMask(E->ReorderIndices);
5461 VecValue = ShuffleBuilder.finalize(VecValue);
5462
5463 Value *ScalarPtr = SI->getPointerOperand();
5464 Value *VecPtr = Builder.CreateBitCast(
5465 ScalarPtr, VecValue->getType()->getPointerTo(AS));
5466 StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr,
5467 SI->getAlign());
5468
5469 // The pointer operand uses an in-tree scalar, so add the new BitCast to
5470 // ExternalUses to make sure that an extract will be generated in the
5471 // future.
5472 if (getTreeEntry(ScalarPtr))
5473 ExternalUses.push_back(ExternalUser(ScalarPtr, cast<User>(VecPtr), 0));
5474
5475 Value *V = propagateMetadata(ST, E->Scalars);
5476
5477 E->VectorizedValue = V;
5478 ++NumVectorInstructions;
5479 return V;
5480 }
5481 case Instruction::GetElementPtr: {
5482 setInsertPointAfterBundle(E);
5483
5484 Value *Op0 = vectorizeTree(E->getOperand(0));
5485
5486 std::vector<Value *> OpVecs;
5487 for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
5488 ++j) {
5489 ValueList &VL = E->getOperand(j);
5490 // Need to cast all elements to the same type before vectorization to
5491 // avoid crash.
5492 Type *VL0Ty = VL0->getOperand(j)->getType();
5493 Type *Ty = llvm::all_of(
5494 VL, [VL0Ty](Value *V) { return VL0Ty == V->getType(); })
5495 ? VL0Ty
5496 : DL->getIndexType(cast<GetElementPtrInst>(VL0)
5497 ->getPointerOperandType()
5498 ->getScalarType());
5499 for (Value *&V : VL) {
5500 auto *CI = cast<ConstantInt>(V);
5501 V = ConstantExpr::getIntegerCast(CI, Ty,
5502 CI->getValue().isSignBitSet());
5503 }
5504 Value *OpVec = vectorizeTree(VL);
5505 OpVecs.push_back(OpVec);
5506 }
5507
5508 Value *V = Builder.CreateGEP(
5509 cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs);
5510 if (Instruction *I = dyn_cast<Instruction>(V))
5511 V = propagateMetadata(I, E->Scalars);
5512
5513 ShuffleBuilder.addMask(E->ReuseShuffleIndices);
5514 V = ShuffleBuilder.finalize(V);
5515
5516 E->VectorizedValue = V;
5517 ++NumVectorInstructions;
5518
5519 return V;
5520 }
5521 case Instruction::Call: {
5522 CallInst *CI = cast<CallInst>(VL0);
5523 setInsertPointAfterBundle(E);
5524
5525 Intrinsic::ID IID = Intrinsic::not_intrinsic;
5526 if (Function *FI = CI->getCalledFunction())
5527 IID = FI->getIntrinsicID();
5528
5529 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5530
5531 auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5532 bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
5533 VecCallCosts.first <= VecCallCosts.second;
5534
5535 Value *ScalarArg = nullptr;
5536 std::vector<Value *> OpVecs;
5537 SmallVector<Type *, 2> TysForDecl =
5538 {FixedVectorType::get(CI->getType(), E->Scalars.size())};
5539 for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
5540 ValueList OpVL;
5541 // Some intrinsics have scalar arguments. This argument should not be
5542 // vectorized.
5543 if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
5544 CallInst *CEI = cast<CallInst>(VL0);
5545 ScalarArg = CEI->getArgOperand(j);
5546 OpVecs.push_back(CEI->getArgOperand(j));
5547 if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
5548 TysForDecl.push_back(ScalarArg->getType());
5549 continue;
5550 }
5551
5552 Value *OpVec = vectorizeTree(E->getOperand(j));
5553 LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n")do { } while (false);
5554 OpVecs.push_back(OpVec);
5555 }
5556
5557 Function *CF;
5558 if (!UseIntrinsic) {
5559 VFShape Shape =
5560 VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
5561 VecTy->getNumElements())),
5562 false /*HasGlobalPred*/);
5563 CF = VFDatabase(*CI).getVectorizedFunction(Shape);
5564 } else {
5565 CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
5566 }
5567
5568 SmallVector<OperandBundleDef, 1> OpBundles;
5569 CI->getOperandBundlesAsDefs(OpBundles);
5570 Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
5571
5572 // The scalar argument uses an in-tree scalar so we add the new vectorized
5573 // call to ExternalUses list to make sure that an extract will be
5574 // generated in the future.
5575 if (ScalarArg && getTreeEntry(ScalarArg))
5576 ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
5577
5578 propagateIRFlags(V, E->Scalars, VL0);
5579 ShuffleBuilder.addMask(E->ReuseShuffleIndices);
5580 V = ShuffleBuilder.finalize(V);
5581
5582 E->VectorizedValue = V;
5583 ++NumVectorInstructions;
5584 return V;
5585 }
5586 case Instruction::ShuffleVector: {
5587 assert(E->isAltShuffle() &&(static_cast<void> (0))
5588 ((Instruction::isBinaryOp(E->getOpcode()) &&(static_cast<void> (0))
5589 Instruction::isBinaryOp(E->getAltOpcode())) ||(static_cast<void> (0))
5590 (Instruction::isCast(E->getOpcode()) &&(static_cast<void> (0))
5591 Instruction::isCast(E->getAltOpcode()))) &&(static_cast<void> (0))
5592 "Invalid Shuffle Vector Operand")(static_cast<void> (0));
5593
5594 Value *LHS = nullptr, *RHS = nullptr;
5595 if (Instruction::isBinaryOp(E->getOpcode())) {
5596 setInsertPointAfterBundle(E);
5597 LHS = vectorizeTree(E->getOperand(0));
5598 RHS = vectorizeTree(E->getOperand(1));
5599 } else {
5600 setInsertPointAfterBundle(E);
5601 LHS = vectorizeTree(E->getOperand(0));
5602 }
5603
5604 if (E->VectorizedValue) {
5605 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { } while (false);
5606 return E->VectorizedValue;
5607 }
5608
5609 Value *V0, *V1;
5610 if (Instruction::isBinaryOp(E->getOpcode())) {
5611 V0 = Builder.CreateBinOp(
5612 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
5613 V1 = Builder.CreateBinOp(
5614 static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
5615 } else {
5616 V0 = Builder.CreateCast(
5617 static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
5618 V1 = Builder.CreateCast(
5619 static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
5620 }
5621
5622 // Create shuffle to take alternate operations from the vector.
5623 // Also, gather up main and alt scalar ops to propagate IR flags to
5624 // each vector operation.
5625 ValueList OpScalars, AltScalars;
5626 unsigned Sz = E->Scalars.size();
5627 SmallVector<int> Mask(Sz);
5628 for (unsigned I = 0; I < Sz; ++I) {
5629 auto *OpInst = cast<Instruction>(E->Scalars[I]);
5630 assert(E->isOpcodeOrAlt(OpInst) && "Unexpected main/alternate opcode")(static_cast<void> (0));
5631 if (OpInst->getOpcode() == E->getAltOpcode()) {
5632 Mask[I] = Sz + I;
5633 AltScalars.push_back(E->Scalars[I]);
5634 } else {
5635 Mask[I] = I;
5636 OpScalars.push_back(E->Scalars[I]);
5637 }
5638 }
5639
5640 propagateIRFlags(V0, OpScalars);
5641 propagateIRFlags(V1, AltScalars);
5642
5643 Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
5644 if (Instruction *I = dyn_cast<Instruction>(V))
5645 V = propagateMetadata(I, E->Scalars);
5646 ShuffleBuilder.addMask(E->ReuseShuffleIndices);
5647 V = ShuffleBuilder.finalize(V);
5648
5649 E->VectorizedValue = V;
5650 ++NumVectorInstructions;
5651
5652 return V;
5653 }
5654 default:
5655 llvm_unreachable("unknown inst")__builtin_unreachable();
5656 }
5657 return nullptr;
5658}
5659
5660Value *BoUpSLP::vectorizeTree() {
5661 ExtraValueToDebugLocsMap ExternallyUsedValues;
5662 return vectorizeTree(ExternallyUsedValues);
5663}
5664
5665Value *
5666BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
5667 // All blocks must be scheduled before any instructions are inserted.
5668 for (auto &BSIter : BlocksSchedules) {
5669 scheduleBlock(BSIter.second.get());
5670 }
5671
5672 Builder.SetInsertPoint(&F->getEntryBlock().front());
5673 auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
5674
5675 // If the vectorized tree can be rewritten in a smaller type, we truncate the
5676 // vectorized root. InstCombine will then rewrite the entire expression. We
5677 // sign extend the extracted values below.
5678 auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
5679 if (MinBWs.count(ScalarRoot)) {
5680 if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
5681 // If current instr is a phi and not the last phi, insert it after the
5682 // last phi node.
5683 if (isa<PHINode>(I))
5684 Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
5685 else
5686 Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
5687 }
5688 auto BundleWidth = VectorizableTree[0]->Scalars.size();
5689 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
5690 auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
5691 auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
5692 VectorizableTree[0]->VectorizedValue = Trunc;
5693 }
5694
5695 LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()do { } while (false)
5696 << " values .\n")do { } while (false);
5697
5698 // Extract all of the elements with the external uses.
5699 for (const auto &ExternalUse : ExternalUses) {
5700 Value *Scalar = ExternalUse.Scalar;
5701 llvm::User *User = ExternalUse.User;
5702
5703 // Skip users that we already RAUW. This happens when one instruction
5704 // has multiple uses of the same value.
5705 if (User && !is_contained(Scalar->users(), User))
5706 continue;
5707 TreeEntry *E = getTreeEntry(Scalar);
5708 assert(E && "Invalid scalar")(static_cast<void> (0));
5709 assert(E->State != TreeEntry::NeedToGather &&(static_cast<void> (0))
5710 "Extracting from a gather list")(static_cast<void> (0));
5711
5712 Value *Vec = E->VectorizedValue;
5713 assert(Vec && "Can't find vectorizable value")(static_cast<void> (0));
5714
5715 Value *Lane = Builder.getInt32(ExternalUse.Lane);
5716 auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
5717 if (Scalar->getType() != Vec->getType()) {
5718 Value *Ex;
5719 // "Reuse" the existing extract to improve final codegen.
5720 if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
5721 Ex = Builder.CreateExtractElement(ES->getOperand(0),
5722 ES->getOperand(1));
5723 } else {
5724 Ex = Builder.CreateExtractElement(Vec, Lane);
5725 }
5726 // If necessary, sign-extend or zero-extend ScalarRoot
5727 // to the larger type.
5728 if (!MinBWs.count(ScalarRoot))
5729 return Ex;
5730 if (MinBWs[ScalarRoot].second)
5731 return Builder.CreateSExt(Ex, Scalar->getType());
5732 return Builder.CreateZExt(Ex, Scalar->getType());
5733 }
5734 assert(isa<FixedVectorType>(Scalar->getType()) &&(static_cast<void> (0))
5735 isa<InsertElementInst>(Scalar) &&(static_cast<void> (0))
5736 "In-tree scalar of vector type is not insertelement?")(static_cast<void> (0));
5737 return Vec;
5738 };
5739 // If User == nullptr, the Scalar is used as extra arg. Generate
5740 // ExtractElement instruction and update the record for this scalar in
5741 // ExternallyUsedValues.
5742 if (!User) {
5743 assert(ExternallyUsedValues.count(Scalar) &&(static_cast<void> (0))
5744 "Scalar with nullptr as an external user must be registered in "(static_cast<void> (0))
5745 "ExternallyUsedValues map")(static_cast<void> (0));
5746 if (auto *VecI = dyn_cast<Instruction>(Vec)) {
5747 Builder.SetInsertPoint(VecI->getParent(),
5748 std::next(VecI->getIterator()));
5749 } else {
5750 Builder.SetInsertPoint(&F->getEntryBlock().front());
5751 }
5752 Value *NewInst = ExtractAndExtendIfNeeded(Vec);
5753 CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
5754 auto &NewInstLocs = ExternallyUsedValues[NewInst];
5755 auto It = ExternallyUsedValues.find(Scalar);
5756 assert(It != ExternallyUsedValues.end() &&(static_cast<void> (0))
5757 "Externally used scalar is not found in ExternallyUsedValues")(static_cast<void> (0));
5758 NewInstLocs.append(It->second);
5759 ExternallyUsedValues.erase(Scalar);
5760 // Required to update internally referenced instructions.
5761 Scalar->replaceAllUsesWith(NewInst);
5762 continue;
5763 }
5764
5765 // Generate extracts for out-of-tree users.
5766 // Find the insertion point for the extractelement lane.
5767 if (auto *VecI = dyn_cast<Instruction>(Vec)) {
5768 if (PHINode *PH = dyn_cast<PHINode>(User)) {
5769 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
5770 if (PH->getIncomingValue(i) == Scalar) {
5771 Instruction *IncomingTerminator =
5772 PH->getIncomingBlock(i)->getTerminator();
5773 if (isa<CatchSwitchInst>(IncomingTerminator)) {
5774 Builder.SetInsertPoint(VecI->getParent(),
5775 std::next(VecI->getIterator()));
5776 } else {
5777 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
5778 }
5779 Value *NewInst = ExtractAndExtendIfNeeded(Vec);
5780 CSEBlocks.insert(PH->getIncomingBlock(i));
5781 PH->setOperand(i, NewInst);
5782 }
5783 }
5784 } else {
5785 Builder.SetInsertPoint(cast<Instruction>(User));
5786 Value *NewInst = ExtractAndExtendIfNeeded(Vec);
5787 CSEBlocks.insert(cast<Instruction>(User)->getParent());
5788 User->replaceUsesOfWith(Scalar, NewInst);
5789 }
5790 } else {
5791 Builder.SetInsertPoint(&F->getEntryBlock().front());
5792 Value *NewInst = ExtractAndExtendIfNeeded(Vec);
5793 CSEBlocks.insert(&F->getEntryBlock());
5794 User->replaceUsesOfWith(Scalar, NewInst);
5795 }
5796
5797 LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n")do { } while (false);
5798 }
5799
5800 // For each vectorized value:
5801 for (auto &TEPtr : VectorizableTree) {
5802 TreeEntry *Entry = TEPtr.get();
5803
5804 // No need to handle users of gathered values.
5805 if (Entry->State == TreeEntry::NeedToGather)
5806 continue;
5807
5808 assert(Entry->VectorizedValue && "Can't find vectorizable value")(static_cast<void> (0));
5809
5810 // For each lane:
5811 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
5812 Value *Scalar = Entry->Scalars[Lane];
5813
5814#ifndef NDEBUG1
5815 Type *Ty = Scalar->getType();
5816 if (!Ty->isVoidTy()) {
5817 for (User *U : Scalar->users()) {
5818 LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n")do { } while (false);
5819
5820 // It is legal to delete users in the ignorelist.
5821 assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||(static_cast<void> (0))
5822 (isa_and_nonnull<Instruction>(U) &&(static_cast<void> (0))
5823 isDeleted(cast<Instruction>(U)))) &&(static_cast<void> (0))
5824 "Deleting out-of-tree value")(static_cast<void> (0));
5825 }
5826 }
5827#endif
5828 LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n")do { } while (false);
5829 eraseInstruction(cast<Instruction>(Scalar));
5830 }
5831 }
5832
5833 Builder.ClearInsertionPoint();
5834 InstrElementSize.clear();
5835
5836 return VectorizableTree[0]->VectorizedValue;
5837}
5838
5839void BoUpSLP::optimizeGatherSequence() {
5840 LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()do { } while (false)
5841 << " gather sequences instructions.\n")do { } while (false);
5842 // LICM InsertElementInst sequences.
5843 for (Instruction *I : GatherSeq) {
5844 if (isDeleted(I))
5845 continue;
5846
5847 // Check if this block is inside a loop.
5848 Loop *L = LI->getLoopFor(I->getParent());
5849 if (!L)
5850 continue;
5851
5852 // Check if it has a preheader.
5853 BasicBlock *PreHeader = L->getLoopPreheader();
5854 if (!PreHeader)
5855 continue;
5856
5857 // If the vector or the element that we insert into it are
5858 // instructions that are defined in this basic block then we can't
5859 // hoist this instruction.
5860 auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
5861 auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
5862 if (Op0 && L->contains(Op0))
5863 continue;
5864 if (Op1 && L->contains(Op1))
5865 continue;
5866
5867 // We can hoist this instruction. Move it to the pre-header.
5868 I->moveBefore(PreHeader->getTerminator());
5869 }
5870
5871 // Make a list of all reachable blocks in our CSE queue.
5872 SmallVector<const DomTreeNode *, 8> CSEWorkList;
5873 CSEWorkList.reserve(CSEBlocks.size());
5874 for (BasicBlock *BB : CSEBlocks)
5875 if (DomTreeNode *N = DT->getNode(BB)) {
5876 assert(DT->isReachableFromEntry(N))(static_cast<void> (0));
5877 CSEWorkList.push_back(N);
5878 }
5879
5880 // Sort blocks by domination. This ensures we visit a block after all blocks
5881 // dominating it are visited.
5882 llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
5883 assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&(static_cast<void> (0))
5884 "Different nodes should have different DFS numbers")(static_cast<void> (0));
5885 return A->getDFSNumIn() < B->getDFSNumIn();
5886 });
5887
5888 // Perform O(N^2) search over the gather sequences and merge identical
5889 // instructions. TODO: We can further optimize this scan if we split the
5890 // instructions into different buckets based on the insert lane.
5891 SmallVector<Instruction *, 16> Visited;
5892 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
5893 assert(*I &&(static_cast<void> (0))
5894 (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&(static_cast<void> (0))
5895 "Worklist not sorted properly!")(static_cast<void> (0));
5896 BasicBlock *BB = (*I)->getBlock();
5897 // For all instructions in blocks containing gather sequences:
5898 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
5899 Instruction *In = &*it++;
5900 if (isDeleted(In))
5901 continue;
5902 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In) &&
5903 !isa<ShuffleVectorInst>(In))
5904 continue;
5905
5906 // Check if we can replace this instruction with any of the
5907 // visited instructions.
5908 for (Instruction *v : Visited) {
5909 if (In->isIdenticalTo(v) &&
5910 DT->dominates(v->getParent(), In->getParent())) {
5911 In->replaceAllUsesWith(v);
5912 eraseInstruction(In);
5913 In = nullptr;
5914 break;
5915 }
5916 }
5917 if (In) {
5918 assert(!is_contained(Visited, In))(static_cast<void> (0));
5919 Visited.push_back(In);
5920 }
5921 }
5922 }
5923 CSEBlocks.clear();
5924 GatherSeq.clear();
5925}
5926
5927// Groups the instructions to a bundle (which is then a single scheduling entity)
5928// and schedules instructions until the bundle gets ready.
5929Optional<BoUpSLP::ScheduleData *>
5930BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
5931 const InstructionsState &S) {
5932 if (isa<PHINode>(S.OpValue) || isa<InsertElementInst>(S.OpValue))
5933 return nullptr;
5934
5935 // Initialize the instruction bundle.
5936 Instruction *OldScheduleEnd = ScheduleEnd;
5937 ScheduleData *PrevInBundle = nullptr;
5938 ScheduleData *Bundle = nullptr;
5939 bool ReSchedule = false;
5940 LLVM_DEBUG(dbgs() << "SLP: bundle: " << *S.OpValue << "\n")do { } while (false);
5941
5942 auto &&TryScheduleBundle = [this, OldScheduleEnd, SLP](bool ReSchedule,
5943 ScheduleData *Bundle) {
5944 // The scheduling region got new instructions at the lower end (or it is a
5945 // new region for the first bundle). This makes it necessary to
5946 // recalculate all dependencies.
5947 // It is seldom that this needs to be done a second time after adding the
5948 // initial bundle to the region.
5949 if (ScheduleEnd != OldScheduleEnd) {
5950 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
5951 doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
5952 ReSchedule = true;
5953 }
5954 if (ReSchedule) {
5955 resetSchedule();
5956 initialFillReadyList(ReadyInsts);
5957 }
5958 if (Bundle) {
5959 LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundledo { } while (false)
5960 << " in block " << BB->getName() << "\n")do { } while (false);
5961 calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
5962 }
5963
5964 // Now try to schedule the new bundle or (if no bundle) just calculate
5965 // dependencies. As soon as the bundle is "ready" it means that there are no
5966 // cyclic dependencies and we can schedule it. Note that's important that we
5967 // don't "schedule" the bundle yet (see cancelScheduling).
5968 while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
5969 !ReadyInsts.empty()) {
5970 ScheduleData *Picked = ReadyInsts.pop_back_val();
5971 if (Picked->isSchedulingEntity() && Picked->isReady())
5972 schedule(Picked, ReadyInsts);
5973 }
5974 };
5975
5976 // Make sure that the scheduling region contains all
5977 // instructions of the bundle.
5978 for (Value *V : VL) {
5979 if (!extendSchedulingRegion(V, S)) {
5980 // If the scheduling region got new instructions at the lower end (or it
5981 // is a new region for the first bundle). This makes it necessary to
5982 // recalculate all dependencies.
5983 // Otherwise the compiler may crash trying to incorrectly calculate
5984 // dependencies and emit instruction in the wrong order at the actual
5985 // scheduling.
5986 TryScheduleBundle(/*ReSchedule=*/false, nullptr);
5987 return None;
5988 }
5989 }
5990
5991 for (Value *V : VL) {
5992 ScheduleData *BundleMember = getScheduleData(V);
5993 assert(BundleMember &&(static_cast<void> (0))
5994 "no ScheduleData for bundle member (maybe not in same basic block)")(static_cast<void> (0));
5995 if (BundleMember->IsScheduled) {
5996 // A bundle member was scheduled as single instruction before and now
5997 // needs to be scheduled as part of the bundle. We just get rid of the
5998 // existing schedule.
5999 LLVM_DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMemberdo { } while (false)
6000 << " was already scheduled\n")do { } while (false);
6001 ReSchedule = true;
6002 }
6003 assert(BundleMember->isSchedulingEntity() &&(static_cast<void> (0))
6004 "bundle member already part of other bundle")(static_cast<void> (0));
6005 if (PrevInBundle) {
6006 PrevInBundle->NextInBundle = BundleMember;
6007 } else {
6008 Bundle = BundleMember;
6009 }
6010 BundleMember->UnscheduledDepsInBundle = 0;
6011 Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
6012
6013 // Group the instructions to a bundle.
6014 BundleMember->FirstInBundle = Bundle;
6015 PrevInBundle = BundleMember;
6016 }
6017 assert(Bundle && "Failed to find schedule bundle")(static_cast<void> (0));
6018 TryScheduleBundle(ReSchedule, Bundle);
6019 if (!Bundle->isReady()) {
6020 cancelScheduling(VL, S.OpValue);
6021 return None;
6022 }
6023 return Bundle;
6024}
6025
6026void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
6027 Value *OpValue) {
6028 if (isa<PHINode>(OpValue) || isa<InsertElementInst>(OpValue))
6029 return;
6030
6031 ScheduleData *Bundle = getScheduleData(OpValue);
6032 LLVM_DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n")do { } while (false);
6033 assert(!Bundle->IsScheduled &&(static_cast<void> (0))
6034 "Can't cancel bundle which is already scheduled")(static_cast<void> (0));
6035 assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&(static_cast<void> (0))
6036 "tried to unbundle something which is not a bundle")(static_cast<void> (0));
6037
6038 // Un-bundle: make single instructions out of the bundle.
6039 ScheduleData *BundleMember = Bundle;
6040 while (BundleMember) {
6041 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links")(static_cast<void> (0));
6042 BundleMember->FirstInBundle = BundleMember;
6043 ScheduleData *Next = BundleMember->NextInBundle;
6044 BundleMember->NextInBundle = nullptr;
6045 BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
6046 if (BundleMember->UnscheduledDepsInBundle == 0) {
6047 ReadyInsts.insert(BundleMember);
6048 }
6049 BundleMember = Next;
6050 }
6051}
6052
6053BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
6054 // Allocate a new ScheduleData for the instruction.
6055 if (ChunkPos >= ChunkSize) {
6056 ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
6057 ChunkPos = 0;
6058 }
6059 return &(ScheduleDataChunks.back()[ChunkPos++]);
6060}
6061
6062bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
6063 const InstructionsState &S) {
6064 if (getScheduleData(V, isOneOf(S, V)))
1
Calling 'BlockScheduling::getScheduleData'
9
Returning from 'BlockScheduling::getScheduleData'
10
Taking false branch
6065 return true;
6066 Instruction *I = dyn_cast<Instruction>(V);
11
'V' is not a 'Instruction'
12
'I' initialized to a null pointer value
6067 assert(I && "bundle member must be an instruction")(static_cast<void> (0));
6068 assert(!isa<PHINode>(I) && !isa<InsertElementInst>(I) &&(static_cast<void> (0))
6069 "phi nodes/insertelements don't need to be scheduled")(static_cast<void> (0));
6070 auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
6071 ScheduleData *ISD = getScheduleData(I);
14
Calling 'BlockScheduling::getScheduleData'
18
Returning from 'BlockScheduling::getScheduleData'
6072 if (!ISD
18.1
'ISD' is null
18.1
'ISD' is null
)
19
Taking true branch
6073 return false;
20
Returning zero, which participates in a condition later
6074 assert(isInSchedulingRegion(ISD) &&(static_cast<void> (0))
6075 "ScheduleData not in scheduling region")(static_cast<void> (0));
6076 ScheduleData *SD = allocateScheduleDataChunks();
6077 SD->Inst = I;
6078 SD->init(SchedulingRegionID, S.OpValue);
6079 ExtraScheduleDataMap[I][S.OpValue] = SD;
6080 return true;
6081 };
6082 if (CheckSheduleForI(I))
13
Calling 'operator()'
21
Returning from 'operator()'
22
Taking false branch
6083 return true;
6084 if (!ScheduleStart) {
23
Assuming field 'ScheduleStart' is non-null
24
Taking false branch
6085 // It's the first instruction in the new region.
6086 initScheduleData(I, I->getNextNode(), nullptr, nullptr);
6087 ScheduleStart = I;
6088 ScheduleEnd = I->getNextNode();
6089 if (isOneOf(S, I) != I)
6090 CheckSheduleForI(I);
6091 assert(ScheduleEnd && "tried to vectorize a terminator?")(static_cast<void> (0));
6092 LLVM_DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n")do { } while (false);
6093 return true;
6094 }
6095 // Search up and down at the same time, because we don't know if the new
6096 // instruction is above or below the existing scheduling region.
6097 BasicBlock::reverse_iterator UpIter =
6098 ++ScheduleStart->getIterator().getReverse();
6099 BasicBlock::reverse_iterator UpperEnd = BB->rend();
6100 BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
6101 BasicBlock::iterator LowerEnd = BB->end();
6102 while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
25
Calling 'operator!='
28
Returning from 'operator!='
6103 &*DownIter != I) {
6104 if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
6105 LLVM_DEBUG(dbgs() << "SLP: exceeded schedule region size limit\n")do { } while (false);
6106 return false;
6107 }
6108
6109 ++UpIter;
6110 ++DownIter;
6111 }
6112 if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
29
Calling 'operator=='
32
Returning from 'operator=='
6113 assert(I->getParent() == ScheduleStart->getParent() &&(static_cast<void> (0))
6114 "Instruction is in wrong basic block.")(static_cast<void> (0));
6115 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
33
Passing null pointer value via 1st parameter 'FromI'
34
Calling 'BlockScheduling::initScheduleData'
6116 ScheduleStart = I;
6117 if (isOneOf(S, I) != I)
6118 CheckSheduleForI(I);
6119 LLVM_DEBUG(dbgs() << "SLP: extend schedule region start to " << *Ido { } while (false)
6120 << "\n")do { } while (false);
6121 return true;
6122 }
6123 assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&(static_cast<void> (0))
6124 "Expected to reach top of the basic block or instruction down the "(static_cast<void> (0))
6125 "lower end.")(static_cast<void> (0));
6126 assert(I->getParent() == ScheduleEnd->getParent() &&(static_cast<void> (0))
6127 "Instruction is in wrong basic block.")(static_cast<void> (0));
6128 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
6129 nullptr);
6130 ScheduleEnd = I->getNextNode();
6131 if (isOneOf(S, I) != I)
6132 CheckSheduleForI(I);
6133 assert(ScheduleEnd && "tried to vectorize a terminator?")(static_cast<void> (0));
6134 LLVM_DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n")do { } while (false);
6135 return true;
6136}
6137
6138void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
6139 Instruction *ToI,
6140 ScheduleData *PrevLoadStore,
6141 ScheduleData *NextLoadStore) {
6142 ScheduleData *CurrentLoadStore = PrevLoadStore;
6143 for (Instruction *I = FromI; I
35.1
'I' is not equal to 'ToI'
35.1
'I' is not equal to 'ToI'
!= ToI; I = I->getNextNode()) {
35
'I' initialized to a null pointer value
36
Loop condition is true. Entering loop body
6144 ScheduleData *SD = ScheduleDataMap[I];
6145 if (!SD) {
37
Assuming 'SD' is non-null
38
Taking false branch
6146 SD = allocateScheduleDataChunks();
6147 ScheduleDataMap[I] = SD;
6148 SD->Inst = I;
6149 }
6150 assert(!isInSchedulingRegion(SD) &&(static_cast<void> (0))
6151 "new ScheduleData already in scheduling region")(static_cast<void> (0));
6152 SD->init(SchedulingRegionID, I);
6153
6154 if (I->mayReadOrWriteMemory() &&
39
Called C++ object pointer is null
6155 (!isa<IntrinsicInst>(I) ||
6156 (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
6157 cast<IntrinsicInst>(I)->getIntrinsicID() !=
6158 Intrinsic::pseudoprobe))) {
6159 // Update the linked list of memory accessing instructions.
6160 if (CurrentLoadStore) {
6161 CurrentLoadStore->NextLoadStore = SD;
6162 } else {
6163 FirstLoadStoreInRegion = SD;
6164 }
6165 CurrentLoadStore = SD;
6166 }
6167 }
6168 if (NextLoadStore) {
6169 if (CurrentLoadStore)
6170 CurrentLoadStore->NextLoadStore = NextLoadStore;
6171 } else {
6172 LastLoadStoreInRegion = CurrentLoadStore;
6173 }
6174}
6175
6176void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
6177 bool InsertInReadyList,
6178 BoUpSLP *SLP) {
6179 assert(SD->isSchedulingEntity())(static_cast<void> (0));
6180
6181 SmallVector<ScheduleData *, 10> WorkList;
6182 WorkList.push_back(SD);
6183
6184 while (!WorkList.empty()) {
6185 ScheduleData *SD = WorkList.pop_back_val();
6186
6187 ScheduleData *BundleMember = SD;
6188 while (BundleMember) {
6189 assert(isInSchedulingRegion(BundleMember))(static_cast<void> (0));
6190 if (!BundleMember->hasValidDependencies()) {
6191
6192 LLVM_DEBUG(dbgs() << "SLP: update deps of " << *BundleMemberdo { } while (false)
6193 << "\n")do { } while (false);
6194 BundleMember->Dependencies = 0;
6195 BundleMember->resetUnscheduledDeps();
6196
6197 // Handle def-use chain dependencies.
6198 if (BundleMember->OpValue != BundleMember->Inst) {
6199 ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
6200 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
6201 BundleMember->Dependencies++;
6202 ScheduleData *DestBundle = UseSD->FirstInBundle;
6203 if (!DestBundle->IsScheduled)
6204 BundleMember->incrementUnscheduledDeps(1);
6205 if (!DestBundle->hasValidDependencies())
6206 WorkList.push_back(DestBundle);
6207 }
6208 } else {
6209 for (User *U : BundleMember->Inst->users()) {
6210 if (isa<Instruction>(U)) {
6211 ScheduleData *UseSD = getScheduleData(U);
6212 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
6213 BundleMember->Dependencies++;
6214 ScheduleData *DestBundle = UseSD->FirstInBundle;
6215 if (!DestBundle->IsScheduled)
6216 BundleMember->incrementUnscheduledDeps(1);
6217 if (!DestBundle->hasValidDependencies())
6218 WorkList.push_back(DestBundle);
6219 }
6220 } else {
6221 // I'm not sure if this can ever happen. But we need to be safe.
6222 // This lets the instruction/bundle never be scheduled and
6223 // eventually disable vectorization.
6224 BundleMember->Dependencies++;
6225 BundleMember->incrementUnscheduledDeps(1);
6226 }
6227 }
6228 }
6229
6230 // Handle the memory dependencies.
6231 ScheduleData *DepDest = BundleMember->NextLoadStore;
6232 if (DepDest) {
6233 Instruction *SrcInst = BundleMember->Inst;
6234 MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
6235 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
6236 unsigned numAliased = 0;
6237 unsigned DistToSrc = 1;
6238
6239 while (DepDest) {
6240 assert(isInSchedulingRegion(DepDest))(static_cast<void> (0));
6241
6242 // We have two limits to reduce the complexity:
6243 // 1) AliasedCheckLimit: It's a small limit to reduce calls to
6244 // SLP->isAliased (which is the expensive part in this loop).
6245 // 2) MaxMemDepDistance: It's for very large blocks and it aborts
6246 // the whole loop (even if the loop is fast, it's quadratic).
6247 // It's important for the loop break condition (see below) to
6248 // check this limit even between two read-only instructions.
6249 if (DistToSrc >= MaxMemDepDistance ||
6250 ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
6251 (numAliased >= AliasedCheckLimit ||
6252 SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
6253
6254 // We increment the counter only if the locations are aliased
6255 // (instead of counting all alias checks). This gives a better
6256 // balance between reduced runtime and accurate dependencies.
6257 numAliased++;
6258
6259 DepDest->MemoryDependencies.push_back(BundleMember);
6260 BundleMember->Dependencies++;
6261 ScheduleData *DestBundle = DepDest->FirstInBundle;
6262 if (!DestBundle->IsScheduled) {
6263 BundleMember->incrementUnscheduledDeps(1);
6264 }
6265 if (!DestBundle->hasValidDependencies()) {
6266 WorkList.push_back(DestBundle);
6267 }
6268 }
6269 DepDest = DepDest->NextLoadStore;
6270
6271 // Example, explaining the loop break condition: Let's assume our
6272 // starting instruction is i0 and MaxMemDepDistance = 3.
6273 //
6274 // +--------v--v--v
6275 // i0,i1,i2,i3,i4,i5,i6,i7,i8
6276 // +--------^--^--^
6277 //
6278 // MaxMemDepDistance let us stop alias-checking at i3 and we add
6279 // dependencies from i0 to i3,i4,.. (even if they are not aliased).
6280 // Previously we already added dependencies from i3 to i6,i7,i8
6281 // (because of MaxMemDepDistance). As we added a dependency from
6282 // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
6283 // and we can abort this loop at i6.
6284 if (DistToSrc >= 2 * MaxMemDepDistance)
6285 break;
6286 DistToSrc++;
6287 }
6288 }
6289 }
6290 BundleMember = BundleMember->NextInBundle;
6291 }
6292 if (InsertInReadyList && SD->isReady()) {
6293 ReadyInsts.push_back(SD);
6294 LLVM_DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Instdo { } while (false)
6295 << "\n")do { } while (false);
6296 }
6297 }
6298}
6299
6300void BoUpSLP::BlockScheduling::resetSchedule() {
6301 assert(ScheduleStart &&(static_cast<void> (0))
6302 "tried to reset schedule on block which has not been scheduled")(static_cast<void> (0));
6303 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
6304 doForAllOpcodes(I, [&](ScheduleData *SD) {
6305 assert(isInSchedulingRegion(SD) &&(static_cast<void> (0))
6306 "ScheduleData not in scheduling region")(static_cast<void> (0));
6307 SD->IsScheduled = false;
6308 SD->resetUnscheduledDeps();
6309 });
6310 }
6311 ReadyInsts.clear();
6312}
6313
6314void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
6315 if (!BS->ScheduleStart)
6316 return;
6317
6318 LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n")do { } while (false);
6319
6320 BS->resetSchedule();
6321
6322 // For the real scheduling we use a more sophisticated ready-list: it is
6323 // sorted by the original instruction location. This lets the final schedule
6324 // be as close as possible to the original instruction order.
6325 struct ScheduleDataCompare {
6326 bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
6327 return SD2->SchedulingPriority < SD1->SchedulingPriority;
6328 }
6329 };
6330 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
6331
6332 // Ensure that all dependency data is updated and fill the ready-list with
6333 // initial instructions.
6334 int Idx = 0;
6335 int NumToSchedule = 0;
6336 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
6337 I = I->getNextNode()) {
6338 BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
6339 assert((isa<InsertElementInst>(SD->Inst) ||(static_cast<void> (0))
6340 SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) &&(static_cast<void> (0))
6341 "scheduler and vectorizer bundle mismatch")(static_cast<void> (0));
6342 SD->FirstInBundle->SchedulingPriority = Idx++;
6343 if (SD->isSchedulingEntity()) {
6344 BS->calculateDependencies(SD, false, this);
6345 NumToSchedule++;
6346 }
6347 });
6348 }
6349 BS->initialFillReadyList(ReadyInsts);
6350
6351 Instruction *LastScheduledInst = BS->ScheduleEnd;
6352
6353 // Do the "real" scheduling.
6354 while (!ReadyInsts.empty()) {
6355 ScheduleData *picked = *ReadyInsts.begin();
6356 ReadyInsts.erase(ReadyInsts.begin());
6357
6358 // Move the scheduled instruction(s) to their dedicated places, if not
6359 // there yet.
6360 ScheduleData *BundleMember = picked;
6361 while (BundleMember) {
6362 Instruction *pickedInst = BundleMember->Inst;
6363 if (pickedInst->getNextNode() != LastScheduledInst) {
6364 BS->BB->getInstList().remove(pickedInst);
6365 BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
6366 pickedInst);
6367 }
6368 LastScheduledInst = pickedInst;
6369 BundleMember = BundleMember->NextInBundle;
6370 }
6371
6372 BS->schedule(picked, ReadyInsts);
6373 NumToSchedule--;
6374 }
6375 assert(NumToSchedule == 0 && "could not schedule all instructions")(static_cast<void> (0));
6376
6377 // Avoid duplicate scheduling of the block.
6378 BS->ScheduleStart = nullptr;
6379}
6380
6381unsigned BoUpSLP::getVectorElementSize(Value *V) {
6382 // If V is a store, just return the width of the stored value (or value
6383 // truncated just before storing) without traversing the expression tree.
6384 // This is the common case.
6385 if (auto *Store = dyn_cast<StoreInst>(V)) {
6386 if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
6387 return DL->getTypeSizeInBits(Trunc->getSrcTy());
6388 return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
6389 }
6390
6391 if (auto *IEI = dyn_cast<InsertElementInst>(V))
6392 return getVectorElementSize(IEI->getOperand(1));
6393
6394 auto E = InstrElementSize.find(V);
6395 if (E != InstrElementSize.end())
6396 return E->second;
6397
6398 // If V is not a store, we can traverse the expression tree to find loads
6399 // that feed it. The type of the loaded value may indicate a more suitable
6400 // width than V's type. We want to base the vector element size on the width
6401 // of memory operations where possible.
6402 SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
6403 SmallPtrSet<Instruction *, 16> Visited;
6404 if (auto *I = dyn_cast<Instruction>(V)) {
6405 Worklist.emplace_back(I, I->getParent());
6406 Visited.insert(I);
6407 }
6408
6409 // Traverse the expression tree in bottom-up order looking for loads. If we
6410 // encounter an instruction we don't yet handle, we give up.
6411 auto Width = 0u;
6412 while (!Worklist.empty()) {
6413 Instruction *I;
6414 BasicBlock *Parent;
6415 std::tie(I, Parent) = Worklist.pop_back_val();
6416
6417 // We should only be looking at scalar instructions here. If the current
6418 // instruction has a vector type, skip.
6419 auto *Ty = I->getType();
6420 if (isa<VectorType>(Ty))
6421 continue;
6422
6423 // If the current instruction is a load, update MaxWidth to reflect the
6424 // width of the loaded value.
6425 if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
6426 isa<ExtractValueInst>(I))
6427 Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
6428
6429 // Otherwise, we need to visit the operands of the instruction. We only
6430 // handle the interesting cases from buildTree here. If an operand is an
6431 // instruction we haven't yet visited and from the same basic block as the
6432 // user or the use is a PHI node, we add it to the worklist.
6433 else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
6434 isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
6435 isa<UnaryOperator>(I)) {
6436 for (Use &U : I->operands())
6437 if (auto *J = dyn_cast<Instruction>(U.get()))
6438 if (Visited.insert(J).second &&
6439 (isa<PHINode>(I) || J->getParent() == Parent))
6440 Worklist.emplace_back(J, J->getParent());
6441 } else {
6442 break;
6443 }
6444 }
6445
6446 // If we didn't encounter a memory access in the expression tree, or if we
6447 // gave up for some reason, just return the width of V. Otherwise, return the
6448 // maximum width we found.
6449 if (!Width) {
6450 if (auto *CI = dyn_cast<CmpInst>(V))
6451 V = CI->getOperand(0);
6452 Width = DL->getTypeSizeInBits(V->getType());
6453 }
6454
6455 for (Instruction *I : Visited)
6456 InstrElementSize[I] = Width;
6457
6458 return Width;
6459}
6460
6461// Determine if a value V in a vectorizable expression Expr can be demoted to a
6462// smaller type with a truncation. We collect the values that will be demoted
6463// in ToDemote and additional roots that require investigating in Roots.
6464static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
6465 SmallVectorImpl<Value *> &ToDemote,
6466 SmallVectorImpl<Value *> &Roots) {
6467 // We can always demote constants.
6468 if (isa<Constant>(V)) {
6469 ToDemote.push_back(V);
6470 return true;
6471 }
6472
6473 // If the value is not an instruction in the expression with only one use, it
6474 // cannot be demoted.
6475 auto *I = dyn_cast<Instruction>(V);
6476 if (!I || !I->hasOneUse() || !Expr.count(I))
6477 return false;
6478
6479 switch (I->getOpcode()) {
6480
6481 // We can always demote truncations and extensions. Since truncations can
6482 // seed additional demotion, we save the truncated value.
6483 case Instruction::Trunc:
6484 Roots.push_back(I->getOperand(0));
6485 break;
6486 case Instruction::ZExt:
6487 case Instruction::SExt:
6488 if (isa<ExtractElementInst>(I->getOperand(0)) ||
6489 isa<InsertElementInst>(I->getOperand(0)))
6490 return false;
6491 break;
6492
6493 // We can demote certain binary operations if we can demote both of their
6494 // operands.
6495 case Instruction::Add:
6496 case Instruction::Sub:
6497 case Instruction::Mul:
6498 case Instruction::And:
6499 case Instruction::Or:
6500 case Instruction::Xor:
6501 if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
6502 !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
6503 return false;
6504 break;
6505
6506 // We can demote selects if we can demote their true and false values.
6507 case Instruction::Select: {
6508 SelectInst *SI = cast<SelectInst>(I);
6509 if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
6510 !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
6511 return false;
6512 break;
6513 }
6514
6515 // We can demote phis if we can demote all their incoming operands. Note that
6516 // we don't need to worry about cycles since we ensure single use above.
6517 case Instruction::PHI: {
6518 PHINode *PN = cast<PHINode>(I);
6519 for (Value *IncValue : PN->incoming_values())
6520 if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
6521 return false;
6522 break;
6523 }
6524
6525 // Otherwise, conservatively give up.
6526 default:
6527 return false;
6528 }
6529
6530 // Record the value that we can demote.
6531 ToDemote.push_back(V);
6532 return true;
6533}
6534
6535void BoUpSLP::computeMinimumValueSizes() {
6536 // If there are no external uses, the expression tree must be rooted by a
6537 // store. We can't demote in-memory values, so there is nothing to do here.
6538 if (ExternalUses.empty())
6539 return;
6540
6541 // We only attempt to truncate integer expressions.
6542 auto &TreeRoot = VectorizableTree[0]->Scalars;
6543 auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
6544 if (!TreeRootIT)
6545 return;
6546
6547 // If the expression is not rooted by a store, these roots should have
6548 // external uses. We will rely on InstCombine to rewrite the expression in
6549 // the narrower type. However, InstCombine only rewrites single-use values.
6550 // This means that if a tree entry other than a root is used externally, it
6551 // must have multiple uses and InstCombine will not rewrite it. The code
6552 // below ensures that only the roots are used externally.
6553 SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
6554 for (auto &EU : ExternalUses)
6555 if (!Expr.erase(EU.Scalar))
6556 return;
6557 if (!Expr.empty())
6558 return;
6559
6560 // Collect the scalar values of the vectorizable expression. We will use this
6561 // context to determine which values can be demoted. If we see a truncation,
6562 // we mark it as seeding another demotion.
6563 for (auto &EntryPtr : VectorizableTree)
6564 Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
6565
6566 // Ensure the roots of the vectorizable tree don't form a cycle. They must
6567 // have a single external user that is not in the vectorizable tree.
6568 for (auto *Root : TreeRoot)
6569 if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
6570 return;
6571
6572 // Conservatively determine if we can actually truncate the roots of the
6573 // expression. Collect the values that can be demoted in ToDemote and
6574 // additional roots that require investigating in Roots.
6575 SmallVector<Value *, 32> ToDemote;
6576 SmallVector<Value *, 4> Roots;
6577 for (auto *Root : TreeRoot)
6578 if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
6579 return;
6580
6581 // The maximum bit width required to represent all the values that can be
6582 // demoted without loss of precision. It would be safe to truncate the roots
6583 // of the expression to this width.
6584 auto MaxBitWidth = 8u;
6585
6586 // We first check if all the bits of the roots are demanded. If they're not,
6587 // we can truncate the roots to this narrower type.
6588 for (auto *Root : TreeRoot) {
6589 auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
6590 MaxBitWidth = std::max<unsigned>(
6591 Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
6592 }
6593
6594 // True if the roots can be zero-extended back to their original type, rather
6595 // than sign-extended. We know that if the leading bits are not demanded, we
6596 // can safely zero-extend. So we initialize IsKnownPositive to True.
6597 bool IsKnownPositive = true;
6598
6599 // If all the bits of the roots are demanded, we can try a little harder to
6600 // compute a narrower type. This can happen, for example, if the roots are
6601 // getelementptr indices. InstCombine promotes these indices to the pointer
6602 // width. Thus, all their bits are technically demanded even though the
6603 // address computation might be vectorized in a smaller type.
6604 //
6605 // We start by looking at each entry that can be demoted. We compute the
6606 // maximum bit width required to store the scalar by using ValueTracking to
6607 // compute the number of high-order bits we can truncate.
6608 if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
6609 llvm::all_of(TreeRoot, [](Value *R) {
6610 assert(R->hasOneUse() && "Root should have only one use!")(static_cast<void> (0));
6611 return isa<GetElementPtrInst>(R->user_back());
6612 })) {
6613 MaxBitWidth = 8u;
6614
6615 // Determine if the sign bit of all the roots is known to be zero. If not,
6616 // IsKnownPositive is set to False.
6617 IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
6618 KnownBits Known = computeKnownBits(R, *DL);
6619 return Known.isNonNegative();
6620 });
6621
6622 // Determine the maximum number of bits required to store the scalar
6623 // values.
6624 for (auto *Scalar : ToDemote) {
6625 auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
6626 auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
6627 MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
6628 }
6629
6630 // If we can't prove that the sign bit is zero, we must add one to the
6631 // maximum bit width to account for the unknown sign bit. This preserves
6632 // the existing sign bit so we can safely sign-extend the root back to the
6633 // original type. Otherwise, if we know the sign bit is zero, we will
6634 // zero-extend the root instead.
6635 //
6636 // FIXME: This is somewhat suboptimal, as there will be cases where adding
6637 // one to the maximum bit width will yield a larger-than-necessary
6638 // type. In general, we need to add an extra bit only if we can't
6639 // prove that the upper bit of the original type is equal to the
6640 // upper bit of the proposed smaller type. If these two bits are the
6641 // same (either zero or one) we know that sign-extending from the
6642 // smaller type will result in the same value. Here, since we can't
6643 // yet prove this, we are just making the proposed smaller type
6644 // larger to ensure correctness.
6645 if (!IsKnownPositive)
6646 ++MaxBitWidth;
6647 }
6648
6649 // Round MaxBitWidth up to the next power-of-two.
6650 if (!isPowerOf2_64(MaxBitWidth))
6651 MaxBitWidth = NextPowerOf2(MaxBitWidth);
6652
6653 // If the maximum bit width we compute is less than the with of the roots'
6654 // type, we can proceed with the narrowing. Otherwise, do nothing.
6655 if (MaxBitWidth >= TreeRootIT->getBitWidth())
6656 return;
6657
6658 // If we can truncate the root, we must collect additional values that might
6659 // be demoted as a result. That is, those seeded by truncations we will
6660 // modify.
6661 while (!Roots.empty())
6662 collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
6663
6664 // Finally, map the values we can demote to the maximum bit with we computed.
6665 for (auto *Scalar : ToDemote)
6666 MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
6667}
6668
6669namespace {
6670
6671/// The SLPVectorizer Pass.
6672struct SLPVectorizer : public FunctionPass {
6673 SLPVectorizerPass Impl;
6674
6675 /// Pass identification, replacement for typeid
6676 static char ID;
6677
6678 explicit SLPVectorizer() : FunctionPass(ID) {
6679 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
6680 }
6681
6682 bool doInitialization(Module &M) override {
6683 return false;
6684 }
6685
6686 bool runOnFunction(Function &F) override {
6687 if (skipFunction(F))
6688 return false;
6689
6690 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
6691 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
6692 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
6693 auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
6694 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
6695 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
6696 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
6697 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
6698 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
6699 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
6700
6701 return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
6702 }
6703
6704 void getAnalysisUsage(AnalysisUsage &AU) const override {
6705 FunctionPass::getAnalysisUsage(AU);
6706 AU.addRequired<AssumptionCacheTracker>();
6707 AU.addRequired<ScalarEvolutionWrapperPass>();
6708 AU.addRequired<AAResultsWrapperPass>();
6709 AU.addRequired<TargetTransformInfoWrapperPass>();
6710 AU.addRequired<LoopInfoWrapperPass>();
6711 AU.addRequired<DominatorTreeWrapperPass>();
6712 AU.addRequired<DemandedBitsWrapperPass>();
6713 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
6714 AU.addRequired<InjectTLIMappingsLegacy>();
6715 AU.addPreserved<LoopInfoWrapperPass>();
6716 AU.addPreserved<DominatorTreeWrapperPass>();
6717 AU.addPreserved<AAResultsWrapperPass>();
6718 AU.addPreserved<GlobalsAAWrapperPass>();
6719 AU.setPreservesCFG();
6720 }
6721};
6722
6723} // end anonymous namespace
6724
6725PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
6726 auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
6727 auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
6728 auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
6729 auto *AA = &AM.getResult<AAManager>(F);
6730 auto *LI = &AM.getResult<LoopAnalysis>(F);
6731 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
6732 auto *AC = &AM.getResult<AssumptionAnalysis>(F);
6733 auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
6734 auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
6735
6736 bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
6737 if (!Changed)
6738 return PreservedAnalyses::all();
6739
6740 PreservedAnalyses PA;
6741 PA.preserveSet<CFGAnalyses>();
6742 return PA;
6743}
6744
6745bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
6746 TargetTransformInfo *TTI_,
6747 TargetLibraryInfo *TLI_, AAResults *AA_,
6748 LoopInfo *LI_, DominatorTree *DT_,
6749 AssumptionCache *AC_, DemandedBits *DB_,
6750 OptimizationRemarkEmitter *ORE_) {
6751 if (!RunSLPVectorization)
6752 return false;
6753 SE = SE_;
6754 TTI = TTI_;
6755 TLI = TLI_;
6756 AA = AA_;
6757 LI = LI_;
6758 DT = DT_;
6759 AC = AC_;
6760 DB = DB_;
6761 DL = &F.getParent()->getDataLayout();
6762
6763 Stores.clear();
6764 GEPs.clear();
6765 bool Changed = false;
6766
6767 // If the target claims to have no vector registers don't attempt
6768 // vectorization.
6769 if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)))
6770 return false;
6771
6772 // Don't vectorize when the attribute NoImplicitFloat is used.
6773 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
6774 return false;
6775
6776 LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n")do { } while (false);
6777
6778 // Use the bottom up slp vectorizer to construct chains that start with
6779 // store instructions.
6780 BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
6781
6782 // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
6783 // delete instructions.
6784
6785 // Update DFS numbers now so that we can use them for ordering.
6786 DT->updateDFSNumbers();
6787
6788 // Scan the blocks in the function in post order.
6789 for (auto BB : post_order(&F.getEntryBlock())) {
6790 collectSeedInstructions(BB);
6791
6792 // Vectorize trees that end at stores.
6793 if (!Stores.empty()) {
6794 LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()do { } while (false)
6795 << " underlying objects.\n")do { } while (false);
6796 Changed |= vectorizeStoreChains(R);
6797 }
6798
6799 // Vectorize trees that end at reductions.
6800 Changed |= vectorizeChainsInBlock(BB, R);
6801
6802 // Vectorize the index computations of getelementptr instructions. This
6803 // is primarily intended to catch gather-like idioms ending at
6804 // non-consecutive loads.
6805 if (!GEPs.empty()) {
6806 LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()do { } while (false)
6807 << " underlying objects.\n")do { } while (false);
6808 Changed |= vectorizeGEPIndices(BB, R);
6809 }
6810 }
6811
6812 if (Changed) {
6813 R.optimizeGatherSequence();
6814 LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n")do { } while (false);
6815 }
6816 return Changed;
6817}
6818
6819/// Order may have elements assigned special value (size) which is out of
6820/// bounds. Such indices only appear on places which correspond to undef values
6821/// (see canReuseExtract for details) and used in order to avoid undef values
6822/// have effect on operands ordering.
6823/// The first loop below simply finds all unused indices and then the next loop
6824/// nest assigns these indices for undef values positions.
6825/// As an example below Order has two undef positions and they have assigned
6826/// values 3 and 7 respectively:
6827/// before: 6 9 5 4 9 2 1 0
6828/// after: 6 3 5 4 7 2 1 0
6829/// \returns Fixed ordering.
6830static BoUpSLP::OrdersType fixupOrderingIndices(ArrayRef<unsigned> Order) {
6831 BoUpSLP::OrdersType NewOrder(Order.begin(), Order.end());
6832 const unsigned Sz = NewOrder.size();
6833 SmallBitVector UsedIndices(Sz);
6834 SmallVector<int> MaskedIndices;
6835 for (int I = 0, E = NewOrder.size(); I < E; ++I) {
6836 if (NewOrder[I] < Sz)
6837 UsedIndices.set(NewOrder[I]);
6838 else
6839 MaskedIndices.push_back(I);
6840 }
6841 if (MaskedIndices.empty())
6842 return NewOrder;
6843 SmallVector<int> AvailableIndices(MaskedIndices.size());
6844 unsigned Cnt = 0;
6845 int Idx = UsedIndices.find_first();
6846 do {
6847 AvailableIndices[Cnt] = Idx;
6848 Idx = UsedIndices.find_next(Idx);
6849 ++Cnt;
6850 } while (Idx > 0);
6851 assert(Cnt == MaskedIndices.size() && "Non-synced masked/available indices.")(static_cast<void> (0));
6852 for (int I = 0, E = MaskedIndices.size(); I < E; ++I)
6853 NewOrder[MaskedIndices[I]] = AvailableIndices[I];
6854 return NewOrder;
6855}
6856
6857bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
6858 unsigned Idx) {
6859 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()do { } while (false)
6860 << "\n")do { } while (false);
6861 const unsigned Sz = R.getVectorElementSize(Chain[0]);
6862 const unsigned MinVF = R.getMinVecRegSize() / Sz;
6863 unsigned VF = Chain.size();
6864
6865 if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
6866 return false;
6867
6868 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idxdo { } while (false)
6869 << "\n")do { } while (false);
6870
6871 R.buildTree(Chain);
6872 Optional<ArrayRef<unsigned>> Order = R.bestOrder();
6873 // TODO: Handle orders of size less than number of elements in the vector.
6874 if (Order && Order->size() == Chain.size()) {
6875 // TODO: reorder tree nodes without tree rebuilding.
6876 SmallVector<Value *, 4> ReorderedOps(Chain.size());
6877 transform(fixupOrderingIndices(*Order), ReorderedOps.begin(),
6878 [Chain](const unsigned Idx) { return Chain[Idx]; });
6879 R.buildTree(ReorderedOps);
6880 }
6881 if (R.isTreeTinyAndNotFullyVectorizable())
6882 return false;
6883 if (R.isLoadCombineCandidate())
6884 return false;
6885
6886 R.computeMinimumValueSizes();
6887
6888 InstructionCost Cost = R.getTreeCost();
6889
6890 LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n")do { } while (false);
6891 if (Cost < -SLPCostThreshold) {
6892 LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n")do { } while (false);
6893
6894 using namespace ore;
6895
6896 R.getORE()->emit(OptimizationRemark(SV_NAME"slp-vectorizer", "StoresVectorized",
6897 cast<StoreInst>(Chain[0]))
6898 << "Stores SLP vectorized with cost " << NV("Cost", Cost)
6899 << " and with tree size "
6900 << NV("TreeSize", R.getTreeSize()));
6901
6902 R.vectorizeTree();
6903 return true;
6904 }
6905
6906 return false;
6907}
6908
6909bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
6910 BoUpSLP &R) {
6911 // We may run into multiple chains that merge into a single chain. We mark the
6912 // stores that we vectorized so that we don't visit the same store twice.
6913 BoUpSLP::ValueSet VectorizedStores;
6914 bool Changed = false;
6915
6916 int E = Stores.size();
6917 SmallBitVector Tails(E, false);
6918 int MaxIter = MaxStoreLookup.getValue();
6919 SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
6920 E, std::make_pair(E, INT_MAX2147483647));
6921 SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
6922 int IterCnt;
6923 auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
6924 &CheckedPairs,
6925 &ConsecutiveChain](int K, int Idx) {
6926 if (IterCnt >= MaxIter)
6927 return true;
6928 if (CheckedPairs[Idx].test(K))
6929 return ConsecutiveChain[K].second == 1 &&
6930 ConsecutiveChain[K].first == Idx;
6931 ++IterCnt;
6932 CheckedPairs[Idx].set(K);
6933 CheckedPairs[K].set(Idx);
6934 Optional<int> Diff = getPointersDiff(
6935 Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
6936 Stores[Idx]->getValueOperand()->getType(),
6937 Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
6938 if (!Diff || *Diff == 0)
6939 return false;
6940 int Val = *Diff;
6941 if (Val < 0) {
6942 if (ConsecutiveChain[Idx].second > -Val) {
6943 Tails.set(K);
6944 ConsecutiveChain[Idx] = std::make_pair(K, -Val);
6945 }
6946 return false;
6947 }
6948 if (ConsecutiveChain[K].second <= Val)
6949 return false;
6950
6951 Tails.set(Idx);
6952 ConsecutiveChain[K] = std::make_pair(Idx, Val);
6953 return Val == 1;
6954 };
6955 // Do a quadratic search on all of the given stores in reverse order and find
6956 // all of the pairs of stores that follow each other.
6957 for (int Idx = E - 1; Idx >= 0; --Idx) {
6958 // If a store has multiple consecutive store candidates, search according
6959 // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
6960 // This is because usually pairing with immediate succeeding or preceding
6961 // candidate create the best chance to find slp vectorization opportunity.
6962 const int MaxLookDepth = std::max(E - Idx, Idx + 1);
6963 IterCnt = 0;
6964 for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
6965 if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
6966 (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
6967 break;
6968 }
6969
6970 // Tracks if we tried to vectorize stores starting from the given tail
6971 // already.
6972 SmallBitVector TriedTails(E, false);
6973 // For stores that start but don't end a link in the chain:
6974 for (int Cnt = E; Cnt > 0; --Cnt) {
6975 int I = Cnt - 1;
6976 if (ConsecutiveChain[I].first == E || Tails.test(I))
6977 continue;
6978 // We found a store instr that starts a chain. Now follow the chain and try
6979 // to vectorize it.
6980 BoUpSLP::ValueList Operands;
6981 // Collect the chain into a list.
6982 while (I != E && !VectorizedStores.count(Stores[I])) {
6983 Operands.push_back(Stores[I]);
6984 Tails.set(I);
6985 if (ConsecutiveChain[I].second != 1) {
6986 // Mark the new end in the chain and go back, if required. It might be
6987 // required if the original stores come in reversed order, for example.
6988 if (ConsecutiveChain[I].first != E &&
6989 Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
6990 !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
6991 TriedTails.set(I);
6992 Tails.reset(ConsecutiveChain[I].first);
6993 if (Cnt < ConsecutiveChain[I].first + 2)
6994 Cnt = ConsecutiveChain[I].first + 2;
6995 }
6996 break;
6997 }
6998 // Move to the next value in the chain.
6999 I = ConsecutiveChain[I].first;
7000 }
7001 assert(!Operands.empty() && "Expected non-empty list of stores.")(static_cast<void> (0));
7002
7003 unsigned MaxVecRegSize = R.getMaxVecRegSize();
7004 unsigned EltSize = R.getVectorElementSize(Operands[0]);
7005 unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
7006
7007 unsigned MinVF = std::max(2U, R.getMinVecRegSize() / EltSize);
7008 unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
7009 MaxElts);
7010
7011 // FIXME: Is division-by-2 the correct step? Should we assert that the
7012 // register size is a power-of-2?
7013 unsigned StartIdx = 0;
7014 for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
7015 for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
7016 ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
7017 if (!VectorizedStores.count(Slice.front()) &&
7018 !VectorizedStores.count(Slice.back()) &&
7019 vectorizeStoreChain(Slice, R, Cnt)) {
7020 // Mark the vectorized stores so that we don't vectorize them again.
7021 VectorizedStores.insert(Slice.begin(), Slice.end());
7022 Changed = true;
7023 // If we vectorized initial block, no need to try to vectorize it
7024 // again.
7025 if (Cnt == StartIdx)
7026 StartIdx += Size;
7027 Cnt += Size;
7028 continue;
7029 }
7030 ++Cnt;
7031 }
7032 // Check if the whole array was vectorized already - exit.
7033 if (StartIdx >= Operands.size())
7034 break;
7035 }
7036 }
7037
7038 return Changed;
7039}
7040
7041void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
7042 // Initialize the collections. We will make a single pass over the block.
7043 Stores.clear();
7044 GEPs.clear();
7045
7046 // Visit the store and getelementptr instructions in BB and organize them in
7047 // Stores and GEPs according to the underlying objects of their pointer
7048 // operands.
7049 for (Instruction &I : *BB) {
7050 // Ignore store instructions that are volatile or have a pointer operand
7051 // that doesn't point to a scalar type.
7052 if (auto *SI = dyn_cast<StoreInst>(&I)) {
7053 if (!SI->isSimple())
7054 continue;
7055 if (!isValidElementType(SI->getValueOperand()->getType()))
7056 continue;
7057 Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
7058 }
7059
7060 // Ignore getelementptr instructions that have more than one index, a
7061 // constant index, or a pointer operand that doesn't point to a scalar
7062 // type.
7063 else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
7064 auto Idx = GEP->idx_begin()->get();
7065 if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
7066 continue;
7067 if (!isValidElementType(Idx->getType()))
7068 continue;
7069 if (GEP->getType()->isVectorTy())
7070 continue;
7071 GEPs[GEP->getPointerOperand()].push_back(GEP);
7072 }
7073 }
7074}
7075
7076bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
7077 if (!A || !B)
7078 return false;
7079 Value *VL[] = {A, B};
7080 return tryToVectorizeList(VL, R, /*AllowReorder=*/true);
7081}
7082
7083bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
7084 bool AllowReorder) {
7085 if (VL.size() < 2)
7086 return false;
7087
7088 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "do { } while (false)
7089 << VL.size() << ".\n")do { } while (false);
7090
7091 // Check that all of the parts are instructions of the same type,
7092 // we permit an alternate opcode via InstructionsState.
7093 InstructionsState S = getSameOpcode(VL);
7094 if (!S.getOpcode())
7095 return false;
7096
7097 Instruction *I0 = cast<Instruction>(S.OpValue);
7098 // Make sure invalid types (including vector type) are rejected before
7099 // determining vectorization factor for scalar instructions.
7100 for (Value *V : VL) {
7101 Type *Ty = V->getType();
7102 if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
7103 // NOTE: the following will give user internal llvm type name, which may
7104 // not be useful.
7105 R.getORE()->emit([&]() {
7106 std::string type_str;
7107 llvm::raw_string_ostream rso(type_str);
7108 Ty->print(rso);
7109 return OptimizationRemarkMissed(SV_NAME"slp-vectorizer", "UnsupportedType", I0)
7110 << "Cannot SLP vectorize list: type "
7111 << rso.str() + " is unsupported by vectorizer";
7112 });
7113 return false;
7114 }
7115 }
7116
7117 unsigned Sz = R.getVectorElementSize(I0);
7118 unsigned MinVF = std::max(2U, R.getMinVecRegSize() / Sz);
7119 unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
7120 MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
7121 if (MaxVF < 2) {
7122 R.getORE()->emit([&]() {
7123 return OptimizationRemarkMissed(SV_NAME"slp-vectorizer", "SmallVF", I0)
7124 << "Cannot SLP vectorize list: vectorization factor "
7125 << "less than 2 is not supported";
7126 });
7127 return false;
7128 }
7129
7130 bool Changed = false;
7131 bool CandidateFound = false;
7132 InstructionCost MinCost = SLPCostThreshold.getValue();
7133 Type *ScalarTy = VL[0]->getType();
7134 if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
7135 ScalarTy = IE->getOperand(1)->getType();
7136
7137 unsigned NextInst = 0, MaxInst = VL.size();
7138 for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
7139 // No actual vectorization should happen, if number of parts is the same as
7140 // provided vectorization factor (i.e. the scalar type is used for vector
7141 // code during codegen).
7142 auto *VecTy = FixedVectorType::get(ScalarTy, VF);
7143 if (TTI->getNumberOfParts(VecTy) == VF)
7144 continue;
7145 for (unsigned I = NextInst; I < MaxInst; ++I) {
7146 unsigned OpsWidth = 0;
7147
7148 if (I + VF > MaxInst)
7149 OpsWidth = MaxInst - I;
7150 else
7151 OpsWidth = VF;
7152
7153 if (!isPowerOf2_32(OpsWidth))
7154 continue;
7155
7156 if ((VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
7157 break;
7158
7159 ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
7160 // Check that a previous iteration of this loop did not delete the Value.
7161 if (llvm::any_of(Ops, [&R](Value *V) {
7162 auto *I = dyn_cast<Instruction>(V);
7163 return I && R.isDeleted(I);
7164 }))
7165 continue;
7166
7167 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "do { } while (false)
7168 << "\n")do { } while (false);
7169
7170 R.buildTree(Ops);
7171 if (AllowReorder) {
7172 Optional<ArrayRef<unsigned>> Order = R.bestOrder();
7173 if (Order) {
7174 // TODO: reorder tree nodes without tree rebuilding.
7175 SmallVector<Value *, 4> ReorderedOps(Ops.size());
7176 transform(fixupOrderingIndices(*Order), ReorderedOps.begin(),
7177 [Ops](const unsigned Idx) { return Ops[Idx]; });
7178 R.buildTree(ReorderedOps);
7179 }
7180 }
7181 if (R.isTreeTinyAndNotFullyVectorizable())
7182 continue;
7183
7184 R.computeMinimumValueSizes();
7185 InstructionCost Cost = R.getTreeCost();
7186 CandidateFound = true;
7187 MinCost = std::min(MinCost, Cost);
7188
7189 if (Cost < -SLPCostThreshold) {
7190 LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n")do { } while (false);
7191 R.getORE()->emit(OptimizationRemark(SV_NAME"slp-vectorizer", "VectorizedList",
7192 cast<Instruction>(Ops[0]))
7193 << "SLP vectorized with cost " << ore::NV("Cost", Cost)
7194 << " and with tree size "
7195 << ore::NV("TreeSize", R.getTreeSize()));
7196
7197 R.vectorizeTree();
7198 // Move to the next bundle.
7199 I += VF - 1;
7200 NextInst = I + 1;
7201 Changed = true;
7202 }
7203 }
7204 }
7205
7206 if (!Changed && CandidateFound) {
7207 R.getORE()->emit([&]() {
7208 return OptimizationRemarkMissed(SV_NAME"slp-vectorizer", "NotBeneficial", I0)
7209 << "List vectorization was possible but not beneficial with cost "
7210 << ore::NV("Cost", MinCost) << " >= "
7211 << ore::NV("Treshold", -SLPCostThreshold);
7212 });
7213 } else if (!Changed) {
7214 R.getORE()->emit([&]() {
7215 return OptimizationRemarkMissed(SV_NAME"slp-vectorizer", "NotPossible", I0)
7216 << "Cannot SLP vectorize list: vectorization was impossible"
7217 << " with available vectorization factors";
7218 });
7219 }
7220 return Changed;
7221}
7222
7223bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
7224 if (!I)
7225 return false;
7226
7227 if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
7228 return false;
7229
7230 Value *P = I->getParent();
7231
7232 // Vectorize in current basic block only.
7233 auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
7234 auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
7235 if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
7236 return false;
7237
7238 // Try to vectorize V.
7239 if (tryToVectorizePair(Op0, Op1, R))
7240 return true;
7241
7242 auto *A = dyn_cast<BinaryOperator>(Op0);
7243 auto *B = dyn_cast<BinaryOperator>(Op1);
7244 // Try to skip B.
7245 if (B && B->hasOneUse()) {
7246 auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
7247 auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
7248 if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
7249 return true;
7250 if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
7251 return true;
7252 }
7253
7254 // Try to skip A.
7255 if (A && A->hasOneUse()) {
7256 auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
7257 auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
7258 if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
7259 return true;
7260 if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
7261 return true;
7262 }
7263 return false;
7264}
7265
7266namespace {
7267
7268/// Model horizontal reductions.
7269///
7270/// A horizontal reduction is a tree of reduction instructions that has values
7271/// that can be put into a vector as its leaves. For example:
7272///
7273/// mul mul mul mul
7274/// \ / \ /
7275/// + +
7276/// \ /
7277/// +
7278/// This tree has "mul" as its leaf values and "+" as its reduction
7279/// instructions. A reduction can feed into a store or a binary operation
7280/// feeding a phi.
7281/// ...
7282/// \ /
7283/// +
7284/// |
7285/// phi +=
7286///
7287/// Or:
7288/// ...
7289/// \ /
7290/// +
7291/// |
7292/// *p =
7293///
7294class HorizontalReduction {
7295 using ReductionOpsType = SmallVector<Value *, 16>;
7296 using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
7297 ReductionOpsListType ReductionOps;
7298 SmallVector<Value *, 32> ReducedVals;
7299 // Use map vector to make stable output.
7300 MapVector<Instruction *, Value *> ExtraArgs;
7301 WeakTrackingVH ReductionRoot;
7302 /// The type of reduction operation.
7303 RecurKind RdxKind;
7304
7305 const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
7306
7307 static bool isCmpSelMinMax(Instruction *I) {
7308 return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
7309 RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
7310 }
7311
7312 // And/or are potentially poison-safe logical patterns like:
7313 // select x, y, false
7314 // select x, true, y
7315 static bool isBoolLogicOp(Instruction *I) {
7316 return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
7317 match(I, m_LogicalOr(m_Value(), m_Value()));
7318 }
7319
7320 /// Checks if instruction is associative and can be vectorized.
7321 static bool isVectorizable(RecurKind Kind, Instruction *I) {
7322 if (Kind == RecurKind::None)
7323 return false;
7324
7325 // Integer ops that map to select instructions or intrinsics are fine.
7326 if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
7327 isBoolLogicOp(I))
7328 return true;
7329
7330 if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
7331 // FP min/max are associative except for NaN and -0.0. We do not
7332 // have to rule out -0.0 here because the intrinsic semantics do not
7333 // specify a fixed result for it.
7334 return I->getFastMathFlags().noNaNs();
7335 }
7336
7337 return I->isAssociative();
7338 }
7339
7340 static Value *getRdxOperand(Instruction *I, unsigned Index) {
7341 // Poison-safe 'or' takes the form: select X, true, Y
7342 // To make that work with the normal operand processing, we skip the
7343 // true value operand.
7344 // TODO: Change the code and data structures to handle this without a hack.
7345 if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
7346 return I->getOperand(2);
7347 return I->getOperand(Index);
7348 }
7349
7350 /// Checks if the ParentStackElem.first should be marked as a reduction
7351 /// operation with an extra argument or as extra argument itself.
7352 void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
7353 Value *ExtraArg) {
7354 if (ExtraArgs.count(ParentStackElem.first)) {
7355 ExtraArgs[ParentStackElem.first] = nullptr;
7356 // We ran into something like:
7357 // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
7358 // The whole ParentStackElem.first should be considered as an extra value
7359 // in this case.
7360 // Do not perform analysis of remaining operands of ParentStackElem.first
7361 // instruction, this whole instruction is an extra argument.
7362 ParentStackElem.second = INVALID_OPERAND_INDEX;
7363 } else {
7364 // We ran into something like:
7365 // ParentStackElem.first += ... + ExtraArg + ...
7366 ExtraArgs[ParentStackElem.first] = ExtraArg;
7367 }
7368 }
7369
7370 /// Creates reduction operation with the current opcode.
7371 static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
7372 Value *RHS, const Twine &Name, bool UseSelect) {
7373 unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
7374 switch (Kind) {
7375 case RecurKind::Add:
7376 case RecurKind::Mul:
7377 case RecurKind::Or:
7378 case RecurKind::And:
7379 case RecurKind::Xor:
7380 case RecurKind::FAdd:
7381 case RecurKind::FMul:
7382 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
7383 Name);
7384 case RecurKind::FMax:
7385 return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
7386 case RecurKind::FMin:
7387 return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
7388 case RecurKind::SMax:
7389 if (UseSelect) {
7390 Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
7391 return Builder.CreateSelect(Cmp, LHS, RHS, Name);
7392 }
7393 return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
7394 case RecurKind::SMin:
7395 if (UseSelect) {
7396 Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
7397 return Builder.CreateSelect(Cmp, LHS, RHS, Name);
7398 }
7399 return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
7400 case RecurKind::UMax:
7401 if (UseSelect) {
7402 Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
7403 return Builder.CreateSelect(Cmp, LHS, RHS, Name);
7404 }
7405 return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
7406 case RecurKind::UMin:
7407 if (UseSelect) {
7408 Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
7409 return Builder.CreateSelect(Cmp, LHS, RHS, Name);
7410 }
7411 return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
7412 default:
7413 llvm_unreachable("Unknown reduction operation.")__builtin_unreachable();
7414 }
7415 }
7416
7417 /// Creates reduction operation with the current opcode with the IR flags
7418 /// from \p ReductionOps.
7419 static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
7420 Value *RHS, const Twine &Name,
7421 const ReductionOpsListType &ReductionOps) {
7422 bool UseSelect = ReductionOps.size() == 2;
7423 assert((!UseSelect || isa<SelectInst>(ReductionOps[1][0])) &&(static_cast<void> (0))
7424 "Expected cmp + select pairs for reduction")(static_cast<void> (0));
7425 Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
7426 if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
7427 if (auto *Sel = dyn_cast<SelectInst>(Op)) {
7428 propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
7429 propagateIRFlags(Op, ReductionOps[1]);
7430 return Op;
7431 }
7432 }
7433 propagateIRFlags(Op, ReductionOps[0]);
7434 return Op;
7435 }
7436
7437 /// Creates reduction operation with the current opcode with the IR flags
7438 /// from \p I.
7439 static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
7440 Value *RHS, const Twine &Name, Instruction *I) {
7441 auto *SelI = dyn_cast<SelectInst>(I);
7442 Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
7443 if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
7444 if (auto *Sel = dyn_cast<SelectInst>(Op))
7445 propagateIRFlags(Sel->getCondition(), SelI->getCondition());
7446 }
7447 propagateIRFlags(Op, I);
7448 return Op;
7449 }
7450
7451 static RecurKind getRdxKind(Instruction *I) {
7452 assert(I && "Expected instruction for reduction matching")(static_cast<void> (0));
7453 TargetTransformInfo::ReductionFlags RdxFlags;
7454 if (match(I, m_Add(m_Value(), m_Value())))
7455 return RecurKind::Add;
7456 if (match(I, m_Mul(m_Value(), m_Value())))
7457 return RecurKind::Mul;
7458 if (match(I, m_And(m_Value(), m_Value())) ||
7459 match(I, m_LogicalAnd(m_Value(), m_Value())))
7460 return RecurKind::And;
7461 if (match(I, m_Or(m_Value(), m_Value())) ||
7462 match(I, m_LogicalOr(m_Value(), m_Value())))
7463 return RecurKind::Or;
7464 if (match(I, m_Xor(m_Value(), m_Value())))
7465 return RecurKind::Xor;
7466 if (match(I, m_FAdd(m_Value(), m_Value())))
7467 return RecurKind::FAdd;
7468 if (match(I, m_FMul(m_Value(), m_Value())))
7469 return RecurKind::FMul;
7470
7471 if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
7472 return RecurKind::FMax;
7473 if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
7474 return RecurKind::FMin;
7475
7476 // This matches either cmp+select or intrinsics. SLP is expected to handle
7477 // either form.
7478 // TODO: If we are canonicalizing to intrinsics, we can remove several
7479 // special-case paths that deal with selects.
7480 if (match(I, m_SMax(m_Value(), m_Value())))
7481 return RecurKind::SMax;
7482 if (match(I, m_SMin(m_Value(), m_Value())))
7483 return RecurKind::SMin;
7484 if (match(I, m_UMax(m_Value(), m_Value())))
7485 return RecurKind::UMax;
7486 if (match(I, m_UMin(m_Value(), m_Value())))
7487 return RecurKind::UMin;
7488
7489 if (auto *Select = dyn_cast<SelectInst>(I)) {
7490 // Try harder: look for min/max pattern based on instructions producing
7491 // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
7492 // During the intermediate stages of SLP, it's very common to have
7493 // pattern like this (since optimizeGatherSequence is run only once
7494 // at the end):
7495 // %1 = extractelement <2 x i32> %a, i32 0
7496 // %2 = extractelement <2 x i32> %a, i32 1
7497 // %cond = icmp sgt i32 %1, %2
7498 // %3 = extractelement <2 x i32> %a, i32 0
7499 // %4 = extractelement <2 x i32> %a, i32 1
7500 // %select = select i1 %cond, i32 %3, i32 %4
7501 CmpInst::Predicate Pred;
7502 Instruction *L1;
7503 Instruction *L2;
7504
7505 Value *LHS = Select->getTrueValue();
7506 Value *RHS = Select->getFalseValue();
7507 Value *Cond = Select->getCondition();
7508
7509 // TODO: Support inverse predicates.
7510 if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
7511 if (!isa<ExtractElementInst>(RHS) ||
7512 !L2->isIdenticalTo(cast<Instruction>(RHS)))
7513 return RecurKind::None;
7514 } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
7515 if (!isa<ExtractElementInst>(LHS) ||
7516 !L1->isIdenticalTo(cast<Instruction>(LHS)))
7517 return RecurKind::None;
7518 } else {
7519 if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
7520 return RecurKind::None;
7521 if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
7522 !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
7523 !L2->isIdenticalTo(cast<Instruction>(RHS)))
7524 return RecurKind::None;
7525 }
7526
7527 TargetTransformInfo::ReductionFlags RdxFlags;
7528 switch (Pred) {
7529 default:
7530 return RecurKind::None;
7531 case CmpInst::ICMP_SGT:
7532 case CmpInst::ICMP_SGE:
7533 return RecurKind::SMax;
7534 case CmpInst::ICMP_SLT:
7535 case CmpInst::ICMP_SLE:
7536 return RecurKind::SMin;
7537 case CmpInst::ICMP_UGT:
7538 case CmpInst::ICMP_UGE:
7539 return RecurKind::UMax;
7540 case CmpInst::ICMP_ULT:
7541 case CmpInst::ICMP_ULE:
7542 return RecurKind::UMin;
7543 }
7544 }
7545 return RecurKind::None;
7546 }
7547
7548 /// Get the index of the first operand.
7549 static unsigned getFirstOperandIndex(Instruction *I) {
7550 return isCmpSelMinMax(I) ? 1 : 0;
7551 }
7552
7553 /// Total number of operands in the reduction operation.
7554 static unsigned getNumberOfOperands(Instruction *I) {
7555 return isCmpSelMinMax(I) ? 3 : 2;
7556 }
7557
7558 /// Checks if the instruction is in basic block \p BB.
7559 /// For a cmp+sel min/max reduction check that both ops are in \p BB.
7560 static bool hasSameParent(Instruction *I, BasicBlock *BB) {
7561 if (isCmpSelMinMax(I)) {
7562 auto *Sel = cast<SelectInst>(I);
7563 auto *Cmp = cast<Instruction>(Sel->getCondition());
7564 return Sel->getParent() == BB && Cmp->getParent() == BB;
7565 }
7566 return I->getParent() == BB;
7567 }
7568
7569 /// Expected number of uses for reduction operations/reduced values.
7570 static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
7571 if (IsCmpSelMinMax) {
7572 // SelectInst must be used twice while the condition op must have single
7573 // use only.
7574 if (auto *Sel = dyn_cast<SelectInst>(I))
7575 return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
7576 return I->hasNUses(2);
7577 }
7578
7579 // Arithmetic reduction operation must be used once only.
7580 return I->hasOneUse();
7581 }
7582
7583 /// Initializes the list of reduction operations.
7584 void initReductionOps(Instruction *I) {
7585 if (isCmpSelMinMax(I))
7586 ReductionOps.assign(2, ReductionOpsType());
7587 else
7588 ReductionOps.assign(1, ReductionOpsType());
7589 }
7590
7591 /// Add all reduction operations for the reduction instruction \p I.
7592 void addReductionOps(Instruction *I) {
7593 if (isCmpSelMinMax(I)) {
7594 ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
7595 ReductionOps[1].emplace_back(I);
7596 } else {
7597 ReductionOps[0].emplace_back(I);
7598 }
7599 }
7600
7601 static Value *getLHS(RecurKind Kind, Instruction *I) {
7602 if (Kind == RecurKind::None)
7603 return nullptr;
7604 return I->getOperand(getFirstOperandIndex(I));
7605 }
7606 static Value *getRHS(RecurKind Kind, Instruction *I) {
7607 if (Kind == RecurKind::None)
7608 return nullptr;
7609 return I->getOperand(getFirstOperandIndex(I) + 1);
7610 }
7611
7612public:
7613 HorizontalReduction() = default;
7614
7615 /// Try to find a reduction tree.
7616 bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
7617 assert((!Phi || is_contained(Phi->operands(), Inst)) &&(static_cast<void> (0))
7618 "Phi needs to use the binary operator")(static_cast<void> (0));
7619 assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||(static_cast<void> (0))
7620 isa<IntrinsicInst>(Inst)) &&(static_cast<void> (0))
7621 "Expected binop, select, or intrinsic for reduction matching")(static_cast<void> (0));
7622 RdxKind = getRdxKind(Inst);
7623
7624 // We could have a initial reductions that is not an add.
7625 // r *= v1 + v2 + v3 + v4
7626 // In such a case start looking for a tree rooted in the first '+'.
7627 if (Phi) {
7628 if (getLHS(RdxKind, Inst) == Phi) {
7629 Phi = nullptr;
7630 Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
7631 if (!Inst)
7632 return false;
7633 RdxKind = getRdxKind(Inst);
7634 } else if (getRHS(RdxKind, Inst) == Phi) {
7635 Phi = nullptr;
7636 Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
7637 if (!Inst)
7638 return false;
7639 RdxKind = getRdxKind(Inst);
7640 }
7641 }
7642
7643 if (!isVectorizable(RdxKind, Inst))
7644 return false;
7645
7646 // Analyze "regular" integer/FP types for reductions - no target-specific
7647 // types or pointers.
7648 Type *Ty = Inst->getType();
7649 if (!isValidElementType(Ty) || Ty->isPointerTy())
7650 return false;
7651
7652 // Though the ultimate reduction may have multiple uses, its condition must
7653 // have only single use.
7654 if (auto *Sel = dyn_cast<SelectInst>(Inst))
7655 if (!Sel->getCondition()->hasOneUse())
7656 return false;
7657
7658 ReductionRoot = Inst;
7659
7660 // The opcode for leaf values that we perform a reduction on.
7661 // For example: load(x) + load(y) + load(z) + fptoui(w)
7662 // The leaf opcode for 'w' does not match, so we don't include it as a
7663 // potential candidate for the reduction.
7664 unsigned LeafOpcode = 0;
7665
7666 // Post-order traverse the reduction tree starting at Inst. We only handle
7667 // true trees containing binary operators or selects.
7668 SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
7669 Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
7670 initReductionOps(Inst);
7671 while (!Stack.empty()) {
7672 Instruction *TreeN = Stack.back().first;
7673 unsigned EdgeToVisit = Stack.back().second++;
7674 const RecurKind TreeRdxKind = getRdxKind(TreeN);
7675 bool IsReducedValue = TreeRdxKind != RdxKind;
7676
7677 // Postorder visit.
7678 if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
7679 if (IsReducedValue)
7680 ReducedVals.push_back(TreeN);
7681 else {
7682 auto ExtraArgsIter = ExtraArgs.find(TreeN);
7683 if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
7684 // Check if TreeN is an extra argument of its parent operation.
7685 if (Stack.size() <= 1) {
7686 // TreeN can't be an extra argument as it is a root reduction
7687 // operation.
7688 return false;
7689 }
7690 // Yes, TreeN is an extra argument, do not add it to a list of
7691 // reduction operations.
7692 // Stack[Stack.size() - 2] always points to the parent operation.
7693 markExtraArg(Stack[Stack.size() - 2], TreeN);
7694 ExtraArgs.erase(TreeN);
7695 } else
7696 addReductionOps(TreeN);
7697 }
7698 // Retract.
7699 Stack.pop_back();
7700 continue;
7701 }
7702
7703 // Visit operands.
7704 Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
7705 auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
7706 if (!EdgeInst) {
7707 // Edge value is not a reduction instruction or a leaf instruction.
7708 // (It may be a constant, function argument, or something else.)
7709 markExtraArg(Stack.back(), EdgeVal);
7710 continue;
7711 }
7712 RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
7713 // Continue analysis if the next operand is a reduction operation or
7714 // (possibly) a leaf value. If the leaf value opcode is not set,
7715 // the first met operation != reduction operation is considered as the
7716 // leaf opcode.
7717 // Only handle trees in the current basic block.
7718 // Each tree node needs to have minimal number of users except for the
7719 // ultimate reduction.
7720 const bool IsRdxInst = EdgeRdxKind == RdxKind;
7721 if (EdgeInst != Phi && EdgeInst != Inst &&
7722 hasSameParent(EdgeInst, Inst->getParent()) &&
7723 hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
7724 (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
7725 if (IsRdxInst) {
7726 // We need to be able to reassociate the reduction operations.
7727 if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
7728 // I is an extra argument for TreeN (its parent operation).
7729 markExtraArg(Stack.back(), EdgeInst);
7730 continue;
7731 }
7732 } else if (!LeafOpcode) {
7733 LeafOpcode = EdgeInst->getOpcode();
7734 }
7735 Stack.push_back(
7736 std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
7737 continue;
7738 }
7739 // I is an extra argument for TreeN (its parent operation).
7740 markExtraArg(Stack.back(), EdgeInst);
7741 }
7742 return true;
7743 }
7744
7745 /// Attempt to vectorize the tree found by matchAssociativeReduction.
7746 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
7747 // If there are a sufficient number of reduction values, reduce
7748 // to a nearby power-of-2. We can safely generate oversized
7749 // vectors and rely on the backend to split them to legal sizes.
7750 unsigned NumReducedVals = ReducedVals.size();
7751 if (NumReducedVals < 4)
7752 return false;
7753
7754 // Intersect the fast-math-flags from all reduction operations.
7755 FastMathFlags RdxFMF;
7756 RdxFMF.set();
7757 for (ReductionOpsType &RdxOp : ReductionOps) {
7758 for (Value *RdxVal : RdxOp) {
7759 if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
7760 RdxFMF &= FPMO->getFastMathFlags();
7761 }
7762 }
7763
7764 IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
7765 Builder.setFastMathFlags(RdxFMF);
7766
7767 BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
7768 // The same extra argument may be used several times, so log each attempt
7769 // to use it.
7770 for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
7771 assert(Pair.first && "DebugLoc must be set.")(static_cast<void> (0));
7772 ExternallyUsedValues[Pair.second].push_back(Pair.first);
7773 }
7774
7775 // The compare instruction of a min/max is the insertion point for new
7776 // instructions and may be replaced with a new compare instruction.
7777 auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
7778 assert(isa<SelectInst>(RdxRootInst) &&(static_cast<void> (0))
7779 "Expected min/max reduction to have select root instruction")(static_cast<void> (0));
7780 Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
7781 assert(isa<Instruction>(ScalarCond) &&(static_cast<void> (0))
7782 "Expected min/max reduction to have compare condition")(static_cast<void> (0));
7783 return cast<Instruction>(ScalarCond);
7784 };
7785
7786 // The reduction root is used as the insertion point for new instructions,
7787 // so set it as externally used to prevent it from being deleted.
7788 ExternallyUsedValues[ReductionRoot];
7789 SmallVector<Value *, 16> IgnoreList;
7790 for (ReductionOpsType &RdxOp : ReductionOps)
7791 IgnoreList.append(RdxOp.begin(), RdxOp.end());
7792
7793 unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
7794 if (NumReducedVals > ReduxWidth) {
7795 // In the loop below, we are building a tree based on a window of
7796 // 'ReduxWidth' values.
7797 // If the operands of those values have common traits (compare predicate,
7798 // constant operand, etc), then we want to group those together to
7799 // minimize the cost of the reduction.
7800
7801 // TODO: This should be extended to count common operands for
7802 // compares and binops.
7803
7804 // Step 1: Count the number of times each compare predicate occurs.
7805 SmallDenseMap<unsigned, unsigned> PredCountMap;
7806 for (Value *RdxVal : ReducedVals) {
7807 CmpInst::Predicate Pred;
7808 if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
7809 ++PredCountMap[Pred];
7810 }
7811 // Step 2: Sort the values so the most common predicates come first.
7812 stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
7813 CmpInst::Predicate PredA, PredB;
7814 if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
7815 match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
7816 return PredCountMap[PredA] > PredCountMap[PredB];
7817 }
7818 return false;
7819 });
7820 }
7821
7822 Value *VectorizedTree = nullptr;
7823 unsigned i = 0;
7824 while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
7825 ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
7826 V.buildTree(VL, ExternallyUsedValues, IgnoreList);
7827 Optional<ArrayRef<unsigned>> Order = V.bestOrder();
7828 if (Order) {
7829 assert(Order->size() == VL.size() &&(static_cast<void> (0))
7830 "Order size must be the same as number of vectorized "(static_cast<void> (0))
7831 "instructions.")(static_cast<void> (0));
7832 // TODO: reorder tree nodes without tree rebuilding.
7833 SmallVector<Value *, 4> ReorderedOps(VL.size());
7834 transform(fixupOrderingIndices(*Order), ReorderedOps.begin(),
7835 [VL](const unsigned Idx) { return VL[Idx]; });
7836 V.buildTree(ReorderedOps, ExternallyUsedValues, IgnoreList);
7837 }
7838 if (V.isTreeTinyAndNotFullyVectorizable())
7839 break;
7840 if (V.isLoadCombineReductionCandidate(RdxKind))
7841 break;
7842
7843 // For a poison-safe boolean logic reduction, do not replace select
7844 // instructions with logic ops. All reduced values will be frozen (see
7845 // below) to prevent leaking poison.
7846 if (isa<SelectInst>(ReductionRoot) &&
7847 isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
7848 NumReducedVals != ReduxWidth)
7849 break;
7850
7851 V.computeMinimumValueSizes();
7852
7853 // Estimate cost.
7854 InstructionCost TreeCost =
7855 V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
7856 InstructionCost ReductionCost =
7857 getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
7858 InstructionCost Cost = TreeCost + ReductionCost;
7859 if (!Cost.isValid()) {
7860 LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n")do { } while (false);
7861 return false;
7862 }
7863 if (Cost >= -SLPCostThreshold) {
7864 V.getORE()->emit([&]() {
7865 return OptimizationRemarkMissed(SV_NAME"slp-vectorizer", "HorSLPNotBeneficial",
7866 cast<Instruction>(VL[0]))
7867 << "Vectorizing horizontal reduction is possible"
7868 << "but not beneficial with cost " << ore::NV("Cost", Cost)
7869 << " and threshold "
7870 << ore::NV("Threshold", -SLPCostThreshold);
7871 });
7872 break;
7873 }
7874
7875 LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"do { } while (false)
7876 << Cost << ". (HorRdx)\n")do { } while (false);
7877 V.getORE()->emit([&]() {
7878 return OptimizationRemark(SV_NAME"slp-vectorizer", "VectorizedHorizontalReduction",
7879 cast<Instruction>(VL[0]))
7880 << "Vectorized horizontal reduction with cost "
7881 << ore::NV("Cost", Cost) << " and with tree size "
7882 << ore::NV("TreeSize", V.getTreeSize());
7883 });
7884
7885 // Vectorize a tree.
7886 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
7887 Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
7888
7889 // Emit a reduction. If the root is a select (min/max idiom), the insert
7890 // point is the compare condition of that select.
7891 Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
7892 if (isCmpSelMinMax(RdxRootInst))
7893 Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
7894 else
7895 Builder.SetInsertPoint(RdxRootInst);
7896
7897 // To prevent poison from leaking across what used to be sequential, safe,
7898 // scalar boolean logic operations, the reduction operand must be frozen.
7899 if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
7900 VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
7901
7902 Value *ReducedSubTree =
7903 emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
7904
7905 if (!VectorizedTree) {
7906 // Initialize the final value in the reduction.
7907 VectorizedTree = ReducedSubTree;
7908 } else {
7909 // Update the final value in the reduction.
7910 Builder.SetCurrentDebugLocation(Loc);
7911 VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
7912 ReducedSubTree, "op.rdx", ReductionOps);
7913 }
7914 i += ReduxWidth;
7915 ReduxWidth = PowerOf2Floor(NumReducedVals - i);
7916 }
7917
7918 if (VectorizedTree) {
7919 // Finish the reduction.
7920 for (; i < NumReducedVals; ++i) {
7921 auto *I = cast<Instruction>(ReducedVals[i]);
7922 Builder.SetCurrentDebugLocation(I->getDebugLoc());
7923 VectorizedTree =
7924 createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
7925 }
7926 for (auto &Pair : ExternallyUsedValues) {
7927 // Add each externally used value to the final reduction.
7928 for (auto *I : Pair.second) {
7929 Builder.SetCurrentDebugLocation(I->getDebugLoc());
7930 VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
7931 Pair.first, "op.extra", I);
7932 }
7933 }
7934
7935 ReductionRoot->replaceAllUsesWith(VectorizedTree);
7936
7937 // Mark all scalar reduction ops for deletion, they are replaced by the
7938 // vector reductions.
7939 V.eraseInstructions(IgnoreList);
7940 }
7941 return VectorizedTree != nullptr;
7942 }
7943
7944 unsigned numReductionValues() const { return ReducedVals.size(); }
7945
7946private:
7947 /// Calculate the cost of a reduction.
7948 InstructionCost getReductionCost(TargetTransformInfo *TTI,
7949 Value *FirstReducedVal, unsigned ReduxWidth,
7950 FastMathFlags FMF) {
7951 Type *ScalarTy = FirstReducedVal->getType();
7952 FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
7953 InstructionCost VectorCost, ScalarCost;
7954 switch (RdxKind) {
7955 case RecurKind::Add:
7956 case RecurKind::Mul:
7957 case RecurKind::Or:
7958 case RecurKind::And:
7959 case RecurKind::Xor:
7960 case RecurKind::FAdd:
7961 case RecurKind::FMul: {
7962 unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
7963 VectorCost = TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF);
7964 ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy);
7965 break;
7966 }
7967 case RecurKind::FMax:
7968 case RecurKind::FMin: {
7969 auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
7970 VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
7971 /*unsigned=*/false);
7972 ScalarCost =
7973 TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy) +
7974 TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
7975 CmpInst::makeCmpResultType(ScalarTy));
7976 break;
7977 }
7978 case RecurKind::SMax:
7979 case RecurKind::SMin:
7980 case RecurKind::UMax:
7981 case RecurKind::UMin: {
7982 auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
7983 bool IsUnsigned =
7984 RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
7985 VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned);
7986 ScalarCost =
7987 TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy) +
7988 TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
7989 CmpInst::makeCmpResultType(ScalarTy));
7990 break;
7991 }
7992 default:
7993 llvm_unreachable("Expected arithmetic or min/max reduction operation")__builtin_unreachable();
7994 }
7995
7996 // Scalar cost is repeated for N-1 elements.
7997 ScalarCost *= (ReduxWidth - 1);
7998 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCostdo { } while (false)
7999 << " for reduction that starts with " << *FirstReducedValdo { } while (false)
8000 << " (It is a splitting reduction)\n")do { } while (false);
8001 return VectorCost - ScalarCost;
8002 }
8003
8004 /// Emit a horizontal reduction of the vectorized value.
8005 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
8006 unsigned ReduxWidth, const TargetTransformInfo *TTI) {
8007 assert(VectorizedValue && "Need to have a vectorized tree node")(static_cast<void> (0));
8008 assert(isPowerOf2_32(ReduxWidth) &&(static_cast<void> (0))
8009 "We only handle power-of-two reductions for now")(static_cast<void> (0));
8010
8011 return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind,
8012 ReductionOps.back());
8013 }
8014};
8015
8016} // end anonymous namespace
8017
8018static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
8019 if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
8020 return cast<FixedVectorType>(IE->getType())->getNumElements();
8021
8022 unsigned AggregateSize = 1;
8023 auto *IV = cast<InsertValueInst>(InsertInst);
8024 Type *CurrentType = IV->getType();
8025 do {
8026 if (auto *ST = dyn_cast<StructType>(CurrentType)) {
8027 for (auto *Elt : ST->elements())
8028 if (Elt != ST->getElementType(0)) // check homogeneity
8029 return None;
8030 AggregateSize *= ST->getNumElements();
8031 CurrentType = ST->getElementType(0);
8032 } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
8033 AggregateSize *= AT->getNumElements();
8034 CurrentType = AT->getElementType();
8035 } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
8036 AggregateSize *= VT->getNumElements();
8037 return AggregateSize;
8038 } else if (CurrentType->isSingleValueType()) {
8039 return AggregateSize;
8040 } else {
8041 return None;
8042 }
8043 } while (true);
8044}
8045
8046static bool findBuildAggregate_rec(Instruction *LastInsertInst,
8047 TargetTransformInfo *TTI,
8048 SmallVectorImpl<Value *> &BuildVectorOpds,
8049 SmallVectorImpl<Value *> &InsertElts,
8050 unsigned OperandOffset) {
8051 do {
8052 Value *InsertedOperand = LastInsertInst->getOperand(1);
8053 Optional<int> OperandIndex = getInsertIndex(LastInsertInst, OperandOffset);
8054 if (!OperandIndex)
8055 return false;
8056 if (isa<InsertElementInst>(InsertedOperand) ||
8057 isa<InsertValueInst>(InsertedOperand)) {
8058 if (!findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
8059 BuildVectorOpds, InsertElts, *OperandIndex))
8060 return false;
8061 } else {
8062 BuildVectorOpds[*OperandIndex] = InsertedOperand;
8063 InsertElts[*OperandIndex] = LastInsertInst;
8064 }
8065 LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
8066 } while (LastInsertInst != nullptr &&
8067 (isa<InsertValueInst>(LastInsertInst) ||
8068 isa<InsertElementInst>(LastInsertInst)) &&
8069 LastInsertInst->hasOneUse());
8070 return true;
8071}
8072
8073/// Recognize construction of vectors like
8074/// %ra = insertelement <4 x float> poison, float %s0, i32 0
8075/// %rb = insertelement <4 x float> %ra, float %s1, i32 1
8076/// %rc = insertelement <4 x float> %rb, float %s2, i32 2
8077/// %rd = insertelement <4 x float> %rc, float %s3, i32 3
8078/// starting from the last insertelement or insertvalue instruction.
8079///
8080/// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
8081/// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
8082/// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
8083///
8084/// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
8085///
8086/// \return true if it matches.
8087static bool findBuildAggregate(Instruction *LastInsertInst,
8088 TargetTransformInfo *TTI,
8089 SmallVectorImpl<Value *> &BuildVectorOpds,
8090 SmallVectorImpl<Value *> &InsertElts) {
8091
8092 assert((isa<InsertElementInst>(LastInsertInst) ||(static_cast<void> (0))
8093 isa<InsertValueInst>(LastInsertInst)) &&(static_cast<void> (0))
8094 "Expected insertelement or insertvalue instruction!")(static_cast<void> (0));
8095
8096 assert((BuildVectorOpds.empty() && InsertElts.empty()) &&(static_cast<void> (0))
8097 "Expected empty result vectors!")(static_cast<void> (0));
8098
8099 Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
8100 if (!AggregateSize)
8101 return false;
8102 BuildVectorOpds.resize(*AggregateSize);
8103 InsertElts.resize(*AggregateSize);
8104
8105 if (findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts,
8106 0)) {
8107 llvm::erase_value(BuildVectorOpds, nullptr);
8108 llvm::erase_value(InsertElts, nullptr);
8109 if (BuildVectorOpds.size() >= 2)
8110 return true;
8111 }
8112
8113 return false;
8114}
8115
8116/// Try and get a reduction value from a phi node.
8117///
8118/// Given a phi node \p P in a block \p ParentBB, consider possible reductions
8119/// if they come from either \p ParentBB or a containing loop latch.
8120///
8121/// \returns A candidate reduction value if possible, or \code nullptr \endcode
8122/// if not possible.
8123static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
8124 BasicBlock *ParentBB, LoopInfo *LI) {
8125 // There are situations where the reduction value is not dominated by the
8126 // reduction phi. Vectorizing such cases has been reported to cause
8127 // miscompiles. See PR25787.
8128 auto DominatedReduxValue = [&](Value *R) {
8129 return isa<Instruction>(R) &&
8130 DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
8131 };
8132
8133 Value *Rdx = nullptr;
8134
8135 // Return the incoming value if it comes from the same BB as the phi node.
8136 if (P->getIncomingBlock(0) == ParentBB) {
8137 Rdx = P->getIncomingValue(0);
8138 } else if (P->getIncomingBlock(1) == ParentBB) {
8139 Rdx = P->getIncomingValue(1);
8140 }
8141
8142 if (Rdx && DominatedReduxValue(Rdx))
8143 return Rdx;
8144
8145 // Otherwise, check whether we have a loop latch to look at.
8146 Loop *BBL = LI->getLoopFor(ParentBB);
8147 if (!BBL)
8148 return nullptr;
8149 BasicBlock *BBLatch = BBL->getLoopLatch();
8150 if (!BBLatch)
8151 return nullptr;
8152
8153 // There is a loop latch, return the incoming value if it comes from
8154 // that. This reduction pattern occasionally turns up.
8155 if (P->getIncomingBlock(0) == BBLatch) {
8156 Rdx = P->getIncomingValue(0);
8157 } else if (P->getIncomingBlock(1) == BBLatch) {
8158 Rdx = P->getIncomingValue(1);
8159 }
8160
8161 if (Rdx && DominatedReduxValue(Rdx))
8162 return Rdx;
8163
8164 return nullptr;
8165}
8166
8167static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
8168 if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
8169 return true;
8170 if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
8171 return true;
8172 if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
8173 return true;
8174 if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
8175 return true;
8176 if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
8177 return true;
8178 if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
8179 return true;
8180 if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
8181 return true;
8182 return false;
8183}
8184
8185/// Attempt to reduce a horizontal reduction.
8186/// If it is legal to match a horizontal reduction feeding the phi node \a P
8187/// with reduction operators \a Root (or one of its operands) in a basic block
8188/// \a BB, then check if it can be done. If horizontal reduction is not found
8189/// and root instruction is a binary operation, vectorization of the operands is
8190/// attempted.
8191/// \returns true if a horizontal reduction was matched and reduced or operands
8192/// of one of the binary instruction were vectorized.
8193/// \returns false if a horizontal reduction was not matched (or not possible)
8194/// or no vectorization of any binary operation feeding \a Root instruction was
8195/// performed.
8196static bool tryToVectorizeHorReductionOrInstOperands(
8197 PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
8198 TargetTransformInfo *TTI,
8199 const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
8200 if (!ShouldVectorizeHor)
8201 return false;
8202
8203 if (!Root)
8204 return false;
8205
8206 if (Root->getParent() != BB || isa<PHINode>(Root))
8207 return false;
8208 // Start analysis starting from Root instruction. If horizontal reduction is
8209 // found, try to vectorize it. If it is not a horizontal reduction or
8210 // vectorization is not possible or not effective, and currently analyzed
8211 // instruction is a binary operation, try to vectorize the operands, using
8212 // pre-order DFS traversal order. If the operands were not vectorized, repeat
8213 // the same procedure considering each operand as a possible root of the
8214 // horizontal reduction.
8215 // Interrupt the process if the Root instruction itself was vectorized or all
8216 // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
8217 // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
8218 // CmpInsts so we can skip extra attempts in
8219 // tryToVectorizeHorReductionOrInstOperands and save compile time.
8220 SmallVector<std::pair<Instruction *, unsigned>, 8> Stack(1, {Root, 0});
8221 SmallPtrSet<Value *, 8> VisitedInstrs;
8222 bool Res = false;
8223 while (!Stack.empty()) {
8224 Instruction *Inst;
8225 unsigned Level;
8226 std::tie(Inst, Level) = Stack.pop_back_val();
8227 // Do not try to analyze instruction that has already been vectorized.
8228 // This may happen when we vectorize instruction operands on a previous
8229 // iteration while stack was populated before that happened.
8230 if (R.isDeleted(Inst))
8231 continue;
8232 Value *B0, *B1;
8233 bool IsBinop = matchRdxBop(Inst, B0, B1);
8234 bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
8235 if (IsBinop || IsSelect) {
8236 HorizontalReduction HorRdx;
8237 if (HorRdx.matchAssociativeReduction(P, Inst)) {
8238 if (HorRdx.tryToReduce(R, TTI)) {
8239 Res = true;
8240 // Set P to nullptr to avoid re-analysis of phi node in
8241 // matchAssociativeReduction function unless this is the root node.
8242 P = nullptr;
8243 continue;
8244 }
8245 }
8246 if (P && IsBinop) {
8247 Inst = dyn_cast<Instruction>(B0);
8248 if (Inst == P)
8249 Inst = dyn_cast<Instruction>(B1);
8250 if (!Inst) {
8251 // Set P to nullptr to avoid re-analysis of phi node in
8252 // matchAssociativeReduction function unless this is the root node.
8253 P = nullptr;
8254 continue;
8255 }
8256 }
8257 }
8258 // Set P to nullptr to avoid re-analysis of phi node in
8259 // matchAssociativeReduction function unless this is the root node.
8260 P = nullptr;
8261 // Do not try to vectorize CmpInst operands, this is done separately.
8262 if (!isa<CmpInst>(Inst) && Vectorize(Inst, R)) {
8263 Res = true;
8264 continue;
8265 }
8266
8267 // Try to vectorize operands.
8268 // Continue analysis for the instruction from the same basic block only to
8269 // save compile time.
8270 if (++Level < RecursionMaxDepth)
8271 for (auto *Op : Inst->operand_values())
8272 if (VisitedInstrs.insert(Op).second)
8273 if (auto *I = dyn_cast<Instruction>(Op))
8274 // Do not try to vectorize CmpInst operands, this is done
8275 // separately.
8276 if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
8277 I->getParent() == BB)
8278 Stack.emplace_back(I, Level);
8279 }
8280 return Res;
8281}
8282
8283bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
8284 BasicBlock *BB, BoUpSLP &R,
8285 TargetTransformInfo *TTI) {
8286 auto *I = dyn_cast_or_null<Instruction>(V);
8287 if (!I)
8288 return false;
8289
8290 if (!isa<BinaryOperator>(I))
8291 P = nullptr;
8292 // Try to match and vectorize a horizontal reduction.
8293 auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
8294 return tryToVectorize(I, R);
8295 };
8296 return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
8297 ExtraVectorization);
8298}
8299
8300bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
8301 BasicBlock *BB, BoUpSLP &R) {
8302 const DataLayout &DL = BB->getModule()->getDataLayout();
8303 if (!R.canMapToVector(IVI->getType(), DL))
8304 return false;
8305
8306 SmallVector<Value *, 16> BuildVectorOpds;
8307 SmallVector<Value *, 16> BuildVectorInsts;
8308 if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
8309 return false;
8310
8311 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n")do { } while (false);
8312 // Aggregate value is unlikely to be processed in vector register, we need to
8313 // extract scalars into scalar registers, so NeedExtraction is set true.
8314 return tryToVectorizeList(BuildVectorOpds, R, /*AllowReorder=*/false);
8315}
8316
8317bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
8318 BasicBlock *BB, BoUpSLP &R) {
8319 SmallVector<Value *, 16> BuildVectorInsts;
8320 SmallVector<Value *, 16> BuildVectorOpds;
8321 SmallVector<int> Mask;
8322 if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
8323 (llvm::all_of(BuildVectorOpds,
8324 [](Value *V) { return isa<ExtractElementInst>(V); }) &&
8325 isShuffle(BuildVectorOpds, Mask)))
8326 return false;
8327
8328 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n")do { } while (false);
8329 return tryToVectorizeList(BuildVectorInsts, R, /*AllowReorder=*/true);
8330}
8331
8332bool SLPVectorizerPass::vectorizeSimpleInstructions(
8333 SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
8334 bool AtTerminator) {
8335 bool OpsChanged = false;
8336 SmallVector<Instruction *, 4> PostponedCmps;
8337 for (auto *I : reverse(Instructions)) {
8338 if (R.isDeleted(I))
8339 continue;
8340 if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
8341 OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
8342 else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
8343 OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
8344 else if (isa<CmpInst>(I))
8345 PostponedCmps.push_back(I);
8346 }
8347 if (AtTerminator) {
8348 // Try to find reductions first.
8349 for (Instruction *I : PostponedCmps) {
8350 if (R.isDeleted(I))
8351 continue;
8352 for (Value *Op : I->operands())
8353 OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
8354 }
8355 // Try to vectorize operands as vector bundles.
8356 for (Instruction *I : PostponedCmps) {
8357 if (R.isDeleted(I))
8358 continue;
8359 OpsChanged |= tryToVectorize(I, R);
8360 }
8361 Instructions.clear();
8362 } else {
8363 // Insert in reverse order since the PostponedCmps vector was filled in
8364 // reverse order.
8365 Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
8366 }
8367 return OpsChanged;
8368}
8369
8370bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
8371 bool Changed = false;
8372 SmallVector<Value *, 4> Incoming;
8373 SmallPtrSet<Value *, 16> VisitedInstrs;
8374 // Maps phi nodes to the non-phi nodes found in the use tree for each phi
8375 // node. Allows better to identify the chains that can be vectorized in the
8376 // better way.
8377 DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
8378
8379 bool HaveVectorizedPhiNodes = true;
8380 while (HaveVectorizedPhiNodes) {
8381 HaveVectorizedPhiNodes = false;
8382
8383 // Collect the incoming values from the PHIs.
8384 Incoming.clear();
8385 for (Instruction &I : *BB) {
8386 PHINode *P = dyn_cast<PHINode>(&I);
8387 if (!P)
8388 break;
8389
8390 // No need to analyze deleted, vectorized and non-vectorizable
8391 // instructions.
8392 if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
8393 isValidElementType(P->getType()))
8394 Incoming.push_back(P);
8395 }
8396
8397 // Find the corresponding non-phi nodes for better matching when trying to
8398 // build the tree.
8399 for (Value *V : Incoming) {
8400 SmallVectorImpl<Value *> &Opcodes =
8401 PHIToOpcodes.try_emplace(V).first->getSecond();
8402 if (!Opcodes.empty())
8403 continue;
8404 SmallVector<Value *, 4> Nodes(1, V);
8405 SmallPtrSet<Value *, 4> Visited;
8406 while (!Nodes.empty()) {
8407 auto *PHI = cast<PHINode>(Nodes.pop_back_val());
8408 if (!Visited.insert(PHI).second)
8409 continue;
8410 for (Value *V : PHI->incoming_values()) {
8411 if (auto *PHI1 = dyn_cast<PHINode>((V))) {
8412 Nodes.push_back(PHI1);
8413 continue;
8414 }
8415 Opcodes.emplace_back(V);
8416 }
8417 }
8418 }
8419
8420 // Sort by type, parent, operands.
8421 stable_sort(Incoming, [this, &PHIToOpcodes](Value *V1, Value *V2) {
8422 assert(isValidElementType(V1->getType()) &&(static_cast<void> (0))
8423 isValidElementType(V2->getType()) &&(static_cast<void> (0))
8424 "Expected vectorizable types only.")(static_cast<void> (0));
8425 // It is fine to compare type IDs here, since we expect only vectorizable
8426 // types, like ints, floats and pointers, we don't care about other type.
8427 if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
8428 return true;
8429 if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
8430 return false;
8431 ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
8432 ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
8433 if (Opcodes1.size() < Opcodes2.size())
8434 return true;
8435 if (Opcodes1.size() > Opcodes2.size())
8436 return false;
8437 for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
8438 // Undefs are compatible with any other value.
8439 if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
8440 continue;
8441 if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
8442 if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
8443 DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
8444 DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
8445 if (!NodeI1)
8446 return NodeI2 != nullptr;
8447 if (!NodeI2)
8448 return false;
8449 assert((NodeI1 == NodeI2) ==(static_cast<void> (0))
8450 (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&(static_cast<void> (0))
8451 "Different nodes should have different DFS numbers")(static_cast<void> (0));
8452 if (NodeI1 != NodeI2)
8453 return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
8454 InstructionsState S = getSameOpcode({I1, I2});
8455 if (S.getOpcode())
8456 continue;
8457 return I1->getOpcode() < I2->getOpcode();
8458 }
8459 if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
8460 continue;
8461 if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
8462 return true;
8463 if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
8464 return false;
8465 }
8466 return false;
8467 });
8468
8469 auto &&AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
8470 if (V1 == V2)
8471 return true;
8472 if (V1->getType() != V2->getType())
8473 return false;
8474 ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
8475 ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
8476 if (Opcodes1.size() != Opcodes2.size())
8477 return false;
8478 for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
8479 // Undefs are compatible with any other value.
8480 if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
8481 continue;
8482 if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
8483 if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
8484 if (I1->getParent() != I2->getParent())
8485 return false;
8486 InstructionsState S = getSameOpcode({I1, I2});
8487 if (S.getOpcode())
8488 continue;
8489 return false;
8490 }
8491 if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
8492 continue;
8493 if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
8494 return false;
8495 }
8496 return true;
8497 };
8498
8499 // Try to vectorize elements base on their type.
8500 SmallVector<Value *, 4> Candidates;
8501 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
8502 E = Incoming.end();
8503 IncIt != E;) {
8504
8505 // Look for the next elements with the same type, parent and operand
8506 // kinds.
8507 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
8508 while (SameTypeIt != E && AreCompatiblePHIs(*SameTypeIt, *IncIt)) {
8509 VisitedInstrs.insert(*SameTypeIt);
8510 ++SameTypeIt;
8511 }
8512
8513 // Try to vectorize them.
8514 unsigned NumElts = (SameTypeIt - IncIt);
8515 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at PHIs ("do { } while (false)
8516 << NumElts << ")\n")do { } while (false);
8517 // The order in which the phi nodes appear in the program does not matter.
8518 // So allow tryToVectorizeList to reorder them if it is beneficial. This
8519 // is done when there are exactly two elements since tryToVectorizeList
8520 // asserts that there are only two values when AllowReorder is true.
8521 if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R,
8522 /*AllowReorder=*/true)) {
8523 // Success start over because instructions might have been changed.
8524 HaveVectorizedPhiNodes = true;
8525 Changed = true;
8526 } else if (NumElts < 4 &&
8527 (Candidates.empty() ||
8528 Candidates.front()->getType() == (*IncIt)->getType())) {
8529 Candidates.append(IncIt, std::next(IncIt, NumElts));
8530 }
8531 // Final attempt to vectorize phis with the same types.
8532 if (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType()) {
8533 if (Candidates.size() > 1 &&
8534 tryToVectorizeList(Candidates, R, /*AllowReorder=*/true)) {
8535 // Success start over because instructions might have been changed.
8536 HaveVectorizedPhiNodes = true;
8537 Changed = true;
8538 }
8539 Candidates.clear();
8540 }
8541
8542 // Start over at the next instruction of a different type (or the end).
8543 IncIt = SameTypeIt;
8544 }
8545 }
8546
8547 VisitedInstrs.clear();
8548
8549 SmallVector<Instruction *, 8> PostProcessInstructions;
8550 SmallDenseSet<Instruction *, 4> KeyNodes;
8551 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
8552 // Skip instructions with scalable type. The num of elements is unknown at
8553 // compile-time for scalable type.
8554 if (isa<ScalableVectorType>(it->getType()))
8555 continue;
8556
8557 // Skip instructions marked for the deletion.
8558 if (R.isDeleted(&*it))
8559 continue;
8560 // We may go through BB multiple times so skip the one we have checked.
8561 if (!VisitedInstrs.insert(&*it).second) {
8562 if (it->use_empty() && KeyNodes.contains(&*it) &&
8563 vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
8564 it->isTerminator())) {
8565 // We would like to start over since some instructions are deleted
8566 // and the iterator may become invalid value.
8567 Changed = true;
8568 it = BB->begin();
8569 e = BB->end();
8570 }
8571 continue;
8572 }
8573
8574 if (isa<DbgInfoIntrinsic>(it))
8575 continue;
8576
8577 // Try to vectorize reductions that use PHINodes.
8578 if (PHINode *P = dyn_cast<PHINode>(it)) {
8579 // Check that the PHI is a reduction PHI.
8580 if (P->getNumIncomingValues() == 2) {
8581 // Try to match and vectorize a horizontal reduction.
8582 if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
8583 TTI)) {
8584 Changed = true;
8585 it = BB->begin();
8586 e = BB->end();
8587 continue;
8588 }
8589 }
8590 // Try to vectorize the incoming values of the PHI, to catch reductions
8591 // that feed into PHIs.
8592 for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
8593 // Skip if the incoming block is the current BB for now. Also, bypass
8594 // unreachable IR for efficiency and to avoid crashing.
8595 // TODO: Collect the skipped incoming values and try to vectorize them
8596 // after processing BB.
8597 if (BB == P->getIncomingBlock(I) ||
8598 !DT->isReachableFromEntry(P->getIncomingBlock(I)))
8599 continue;
8600
8601 Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
8602 P->getIncomingBlock(I), R, TTI);
8603 }
8604 continue;
8605 }
8606
8607 // Ran into an instruction without users, like terminator, or function call
8608 // with ignored return value, store. Ignore unused instructions (basing on
8609 // instruction type, except for CallInst and InvokeInst).
8610 if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
8611 isa<InvokeInst>(it))) {
8612 KeyNodes.insert(&*it);
8613 bool OpsChanged = false;
8614 if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
8615 for (auto *V : it->operand_values()) {
8616 // Try to match and vectorize a horizontal reduction.
8617 OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
8618 }
8619 }
8620 // Start vectorization of post-process list of instructions from the
8621 // top-tree instructions to try to vectorize as many instructions as
8622 // possible.
8623 OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
8624 it->isTerminator());
8625 if (OpsChanged) {
8626 // We would like to start over since some instructions are deleted
8627 // and the iterator may become invalid value.
8628 Changed = true;
8629 it = BB->begin();
8630 e = BB->end();
8631 continue;
8632 }
8633 }
8634
8635 if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
8636 isa<InsertValueInst>(it))
8637 PostProcessInstructions.push_back(&*it);
8638 }
8639
8640 return Changed;
8641}
8642
8643bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
8644 auto Changed = false;
8645 for (auto &Entry : GEPs) {
8646 // If the getelementptr list has fewer than two elements, there's nothing
8647 // to do.
8648 if (Entry.second.size() < 2)
8649 continue;
8650
8651 LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "do { } while (false)
8652 << Entry.second.size() << ".\n")do { } while (false);
8653
8654 // Process the GEP list in chunks suitable for the target's supported
8655 // vector size. If a vector register can't hold 1 element, we are done. We
8656 // are trying to vectorize the index computations, so the maximum number of
8657 // elements is based on the size of the index expression, rather than the
8658 // size of the GEP itself (the target's pointer size).
8659 unsigned MaxVecRegSize = R.getMaxVecRegSize();
8660 unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
8661 if (MaxVecRegSize < EltSize)
8662 continue;
8663
8664 unsigned MaxElts = MaxVecRegSize / EltSize;
8665 for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
8666 auto Len = std::min<unsigned>(BE - BI, MaxElts);
8667 ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
8668
8669 // Initialize a set a candidate getelementptrs. Note that we use a
8670 // SetVector here to preserve program order. If the index computations
8671 // are vectorizable and begin with loads, we want to minimize the chance
8672 // of having to reorder them later.
8673 SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
8674
8675 // Some of the candidates may have already been vectorized after we
8676 // initially collected them. If so, they are marked as deleted, so remove
8677 // them from the set of candidates.
8678 Candidates.remove_if(
8679 [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
8680
8681 // Remove from the set of candidates all pairs of getelementptrs with
8682 // constant differences. Such getelementptrs are likely not good
8683 // candidates for vectorization in a bottom-up phase since one can be
8684 // computed from the other. We also ensure all candidate getelementptr
8685 // indices are unique.
8686 for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
8687 auto *GEPI = GEPList[I];
8688 if (!Candidates.count(GEPI))
8689 continue;
8690 auto *SCEVI = SE->getSCEV(GEPList[I]);
8691 for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
8692 auto *GEPJ = GEPList[J];
8693 auto *SCEVJ = SE->getSCEV(GEPList[J]);
8694 if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
8695 Candidates.remove(GEPI);
8696 Candidates.remove(GEPJ);
8697 } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
8698 Candidates.remove(GEPJ);
8699 }
8700 }
8701 }
8702
8703 // We break out of the above computation as soon as we know there are
8704 // fewer than two candidates remaining.
8705 if (Candidates.size() < 2)
8706 continue;
8707
8708 // Add the single, non-constant index of each candidate to the bundle. We
8709 // ensured the indices met these constraints when we originally collected
8710 // the getelementptrs.
8711 SmallVector<Value *, 16> Bundle(Candidates.size());
8712 auto BundleIndex = 0u;
8713 for (auto *V : Candidates) {
8714 auto *GEP = cast<GetElementPtrInst>(V);
8715 auto *GEPIdx = GEP->idx_begin()->get();
8716 assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx))(static_cast<void> (0));
8717 Bundle[BundleIndex++] = GEPIdx;
8718 }
8719
8720 // Try and vectorize the indices. We are currently only interested in
8721 // gather-like cases of the form:
8722 //
8723 // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
8724 //
8725 // where the loads of "a", the loads of "b", and the subtractions can be
8726 // performed in parallel. It's likely that detecting this pattern in a
8727 // bottom-up phase will be simpler and less costly than building a
8728 // full-blown top-down phase beginning at the consecutive loads.
8729 Changed |= tryToVectorizeList(Bundle, R);
8730 }
8731 }
8732 return Changed;
8733}
8734
8735bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
8736 bool Changed = false;
8737 // Sort by type, base pointers and values operand. Value operands must be
8738 // compatible (have the same opcode, same parent), otherwise it is
8739 // definitely not profitable to try to vectorize them.
8740 auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
8741 if (V->getPointerOperandType()->getTypeID() <
8742 V2->getPointerOperandType()->getTypeID())
8743 return true;
8744 if (V->getPointerOperandType()->getTypeID() >
8745 V2->getPointerOperandType()->getTypeID())
8746 return false;
8747 // UndefValues are compatible with all other values.
8748 if (isa<UndefValue>(V->getValueOperand()) ||
8749 isa<UndefValue>(V2->getValueOperand()))
8750 return false;
8751 if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
8752 if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
8753 DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
8754 DT->getNode(I1->getParent());
8755 DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
8756 DT->getNode(I2->getParent());
8757 assert(NodeI1 && "Should only process reachable instructions")(static_cast<void> (0));
8758 assert(NodeI1 && "Should only process reachable instructions")(static_cast<void> (0));
8759 assert((NodeI1 == NodeI2) ==(static_cast<void> (0))
8760 (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&(static_cast<void> (0))
8761 "Different nodes should have different DFS numbers")(static_cast<void> (0));
8762 if (NodeI1 != NodeI2)
8763 return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
8764 InstructionsState S = getSameOpcode({I1, I2});
8765 if (S.getOpcode())
8766 return false;
8767 return I1->getOpcode() < I2->getOpcode();
8768 }
8769 if (isa<Constant>(V->getValueOperand()) &&
8770 isa<Constant>(V2->getValueOperand()))
8771 return false;
8772 return V->getValueOperand()->getValueID() <
8773 V2->getValueOperand()->getValueID();
8774 };
8775
8776 auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
8777 if (V1 == V2)
8778 return true;
8779 if (V1->getPointerOperandType() != V2->getPointerOperandType())
8780 return false;
8781 // Undefs are compatible with any other value.
8782 if (isa<UndefValue>(V1->getValueOperand()) ||
8783 isa<UndefValue>(V2->getValueOperand()))
8784 return true;
8785 if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
8786 if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
8787 if (I1->getParent() != I2->getParent())
8788 return false;
8789 InstructionsState S = getSameOpcode({I1, I2});
8790 return S.getOpcode() > 0;
8791 }
8792 if (isa<Constant>(V1->getValueOperand()) &&
8793 isa<Constant>(V2->getValueOperand()))
8794 return true;
8795 return V1->getValueOperand()->getValueID() ==
8796 V2->getValueOperand()->getValueID();
8797 };
8798
8799 // Attempt to sort and vectorize each of the store-groups.
8800 for (auto &Pair : Stores) {
8801 if (Pair.second.size() < 2)
8802 continue;
8803
8804 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "do { } while (false)
8805 << Pair.second.size() << ".\n")do { } while (false);
8806
8807 stable_sort(Pair.second, StoreSorter);
8808
8809 // Try to vectorize elements based on their compatibility.
8810 for (ArrayRef<StoreInst *>::iterator IncIt = Pair.second.begin(),
8811 E = Pair.second.end();
8812 IncIt != E;) {
8813
8814 // Look for the next elements with the same type.
8815 ArrayRef<StoreInst *>::iterator SameTypeIt = IncIt;
8816 Type *EltTy = (*IncIt)->getPointerOperand()->getType();
8817
8818 while (SameTypeIt != E && AreCompatibleStores(*SameTypeIt, *IncIt))
8819 ++SameTypeIt;
8820
8821 // Try to vectorize them.
8822 unsigned NumElts = (SameTypeIt - IncIt);
8823 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at stores ("do { } while (false)
8824 << NumElts << ")\n")do { } while (false);
8825 if (NumElts > 1 && !EltTy->getPointerElementType()->isVectorTy() &&
8826 vectorizeStores(makeArrayRef(IncIt, NumElts), R)) {
8827 // Success start over because instructions might have been changed.
8828 Changed = true;
8829 }
8830
8831 // Start over at the next instruction of a different type (or the end).
8832 IncIt = SameTypeIt;
8833 }
8834 }
8835 return Changed;
8836}
8837
8838char SLPVectorizer::ID = 0;
8839
8840static const char lv_name[] = "SLP Vectorizer";
8841
8842INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)static void *initializeSLPVectorizerPassOnce(PassRegistry &
Registry) {
8843INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)initializeAAResultsWrapperPassPass(Registry);
8844INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)initializeTargetTransformInfoWrapperPassPass(Registry);
8845INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)initializeAssumptionCacheTrackerPass(Registry);
8846INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)initializeScalarEvolutionWrapperPassPass(Registry);
8847INITIALIZE_PASS_DEPENDENCY(LoopSimplify)initializeLoopSimplifyPass(Registry);
8848INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)initializeDemandedBitsWrapperPassPass(Registry);
8849INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)initializeOptimizationRemarkEmitterWrapperPassPass(Registry);
8850INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)initializeInjectTLIMappingsLegacyPass(Registry);
8851INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)PassInfo *PI = new PassInfo( lv_name, "slp-vectorizer", &
SLPVectorizer::ID, PassInfo::NormalCtor_t(callDefaultCtor<
SLPVectorizer>), false, false); Registry.registerPass(*PI,
true); return PI; } static llvm::once_flag InitializeSLPVectorizerPassFlag
; void llvm::initializeSLPVectorizerPass(PassRegistry &Registry
) { llvm::call_once(InitializeSLPVectorizerPassFlag, initializeSLPVectorizerPassOnce
, std::ref(Registry)); }
8852
8853Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include/llvm/ADT/ilist_iterator.h

1//===- llvm/ADT/ilist_iterator.h - Intrusive List Iterator ------*- C++ -*-===//
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#ifndef LLVM_ADT_ILIST_ITERATOR_H
10#define LLVM_ADT_ILIST_ITERATOR_H
11
12#include "llvm/ADT/ilist_node.h"
13#include <cassert>
14#include <cstddef>
15#include <iterator>
16#include <type_traits>
17
18namespace llvm {
19
20namespace ilist_detail {
21
22/// Find const-correct node types.
23template <class OptionsT, bool IsConst> struct IteratorTraits;
24template <class OptionsT> struct IteratorTraits<OptionsT, false> {
25 using value_type = typename OptionsT::value_type;
26 using pointer = typename OptionsT::pointer;
27 using reference = typename OptionsT::reference;
28 using node_pointer = ilist_node_impl<OptionsT> *;
29 using node_reference = ilist_node_impl<OptionsT> &;
30};
31template <class OptionsT> struct IteratorTraits<OptionsT, true> {
32 using value_type = const typename OptionsT::value_type;
33 using pointer = typename OptionsT::const_pointer;
34 using reference = typename OptionsT::const_reference;
35 using node_pointer = const ilist_node_impl<OptionsT> *;
36 using node_reference = const ilist_node_impl<OptionsT> &;
37};
38
39template <bool IsReverse> struct IteratorHelper;
40template <> struct IteratorHelper<false> : ilist_detail::NodeAccess {
41 using Access = ilist_detail::NodeAccess;
42
43 template <class T> static void increment(T *&I) { I = Access::getNext(*I); }
44 template <class T> static void decrement(T *&I) { I = Access::getPrev(*I); }
45};
46template <> struct IteratorHelper<true> : ilist_detail::NodeAccess {
47 using Access = ilist_detail::NodeAccess;
48
49 template <class T> static void increment(T *&I) { I = Access::getPrev(*I); }
50 template <class T> static void decrement(T *&I) { I = Access::getNext(*I); }
51};
52
53} // end namespace ilist_detail
54
55/// Iterator for intrusive lists based on ilist_node.
56template <class OptionsT, bool IsReverse, bool IsConst>
57class ilist_iterator : ilist_detail::SpecificNodeAccess<OptionsT> {
58 friend ilist_iterator<OptionsT, IsReverse, !IsConst>;
59 friend ilist_iterator<OptionsT, !IsReverse, IsConst>;
60 friend ilist_iterator<OptionsT, !IsReverse, !IsConst>;
61
62 using Traits = ilist_detail::IteratorTraits<OptionsT, IsConst>;
63 using Access = ilist_detail::SpecificNodeAccess<OptionsT>;
64
65public:
66 using value_type = typename Traits::value_type;
67 using pointer = typename Traits::pointer;
68 using reference = typename Traits::reference;
69 using difference_type = ptrdiff_t;
70 using iterator_category = std::bidirectional_iterator_tag;
71 using const_pointer = typename OptionsT::const_pointer;
72 using const_reference = typename OptionsT::const_reference;
73
74private:
75 using node_pointer = typename Traits::node_pointer;
76 using node_reference = typename Traits::node_reference;
77
78 node_pointer NodePtr = nullptr;
79
80public:
81 /// Create from an ilist_node.
82 explicit ilist_iterator(node_reference N) : NodePtr(&N) {}
83
84 explicit ilist_iterator(pointer NP) : NodePtr(Access::getNodePtr(NP)) {}
85 explicit ilist_iterator(reference NR) : NodePtr(Access::getNodePtr(&NR)) {}
86 ilist_iterator() = default;
87
88 // This is templated so that we can allow constructing a const iterator from
89 // a nonconst iterator...
90 template <bool RHSIsConst>
91 ilist_iterator(const ilist_iterator<OptionsT, IsReverse, RHSIsConst> &RHS,
92 std::enable_if_t<IsConst || !RHSIsConst, void *> = nullptr)
93 : NodePtr(RHS.NodePtr) {}
94
95 // This is templated so that we can allow assigning to a const iterator from
96 // a nonconst iterator...
97 template <bool RHSIsConst>
98 std::enable_if_t<IsConst || !RHSIsConst, ilist_iterator &>
99 operator=(const ilist_iterator<OptionsT, IsReverse, RHSIsConst> &RHS) {
100 NodePtr = RHS.NodePtr;
101 return *this;
102 }
103
104 /// Explicit conversion between forward/reverse iterators.
105 ///
106 /// Translate between forward and reverse iterators without changing range
107 /// boundaries. The resulting iterator will dereference (and have a handle)
108 /// to the previous node, which is somewhat unexpected; but converting the
109 /// two endpoints in a range will give the same range in reverse.
110 ///
111 /// This matches std::reverse_iterator conversions.
112 explicit ilist_iterator(
113 const ilist_iterator<OptionsT, !IsReverse, IsConst> &RHS)
114 : ilist_iterator(++RHS.getReverse()) {}
115
116 /// Get a reverse iterator to the same node.
117 ///
118 /// Gives a reverse iterator that will dereference (and have a handle) to the
119 /// same node. Converting the endpoint iterators in a range will give a
120 /// different range; for range operations, use the explicit conversions.
121 ilist_iterator<OptionsT, !IsReverse, IsConst> getReverse() const {
122 if (NodePtr)
123 return ilist_iterator<OptionsT, !IsReverse, IsConst>(*NodePtr);
124 return ilist_iterator<OptionsT, !IsReverse, IsConst>();
125 }
126
127 /// Const-cast.
128 ilist_iterator<OptionsT, IsReverse, false> getNonConst() const {
129 if (NodePtr)
130 return ilist_iterator<OptionsT, IsReverse, false>(
131 const_cast<typename ilist_iterator<OptionsT, IsReverse,
132 false>::node_reference>(*NodePtr));
133 return ilist_iterator<OptionsT, IsReverse, false>();
134 }
135
136 // Accessors...
137 reference operator*() const {
138 assert(!NodePtr->isKnownSentinel())(static_cast<void> (0));
139 return *Access::getValuePtr(NodePtr);
140 }
141 pointer operator->() const { return &operator*(); }
142
143 // Comparison operators
144 friend bool operator==(const ilist_iterator &LHS, const ilist_iterator &RHS) {
145 return LHS.NodePtr == RHS.NodePtr;
30
Assuming 'LHS.NodePtr' is equal to 'RHS.NodePtr'
31
Returning the value 1, which participates in a condition later
146 }
147 friend bool operator!=(const ilist_iterator &LHS, const ilist_iterator &RHS) {
148 return LHS.NodePtr != RHS.NodePtr;
26
Assuming 'LHS.NodePtr' is equal to 'RHS.NodePtr'
27
Returning zero, which participates in a condition later
149 }
150
151 // Increment and decrement operators...
152 ilist_iterator &operator--() {
153 NodePtr = IsReverse ? NodePtr->getNext() : NodePtr->getPrev();
154 return *this;
155 }
156 ilist_iterator &operator++() {
157 NodePtr = IsReverse ? NodePtr->getPrev() : NodePtr->getNext();
158 return *this;
159 }
160 ilist_iterator operator--(int) {
161 ilist_iterator tmp = *this;
162 --*this;
163 return tmp;
164 }
165 ilist_iterator operator++(int) {
166 ilist_iterator tmp = *this;
167 ++*this;
168 return tmp;
169 }
170
171 /// Get the underlying ilist_node.
172 node_pointer getNodePtr() const { return static_cast<node_pointer>(NodePtr); }
173
174 /// Check for end. Only valid if ilist_sentinel_tracking<true>.
175 bool isEnd() const { return NodePtr ? NodePtr->isSentinel() : false; }
176};
177
178template <typename From> struct simplify_type;
179
180/// Allow ilist_iterators to convert into pointers to a node automatically when
181/// used by the dyn_cast, cast, isa mechanisms...
182///
183/// FIXME: remove this, since there is no implicit conversion to NodeTy.
184template <class OptionsT, bool IsConst>
185struct simplify_type<ilist_iterator<OptionsT, false, IsConst>> {
186 using iterator = ilist_iterator<OptionsT, false, IsConst>;
187 using SimpleType = typename iterator::pointer;
188
189 static SimpleType getSimplifiedValue(const iterator &Node) { return &*Node; }
190};
191template <class OptionsT, bool IsConst>
192struct simplify_type<const ilist_iterator<OptionsT, false, IsConst>>
193 : simplify_type<ilist_iterator<OptionsT, false, IsConst>> {};
194
195} // end namespace llvm
196
197#endif // LLVM_ADT_ILIST_ITERATOR_H