LLVM 24.0.0git
Legality.h
Go to the documentation of this file.
1//===- Legality.h -----------------------------------------------*- 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// Legality checks for the Sandbox Vectorizer.
10//
11
12#ifndef LLVM_TRANSFORMS_VECTORIZE_SANDBOXVECTORIZER_LEGALITY_H
13#define LLVM_TRANSFORMS_VECTORIZE_SANDBOXVECTORIZER_LEGALITY_H
14
15#include "llvm/ADT/ArrayRef.h"
18#include "llvm/IR/DataLayout.h"
24
25namespace llvm::sandboxir {
26
28class Value;
29class InstrMaps;
30
32public:
34
35private:
36 IndicesVecT Indices;
37
38public:
39 ShuffleMask(SmallVectorImpl<int> &&Indices) : Indices(std::move(Indices)) {}
40 ShuffleMask(std::initializer_list<int> Indices) : Indices(Indices) {}
41 explicit ShuffleMask(ArrayRef<int> Indices) : Indices(Indices) {}
42 operator ArrayRef<int>() const { return Indices; }
43 /// Creates and returns an identity shuffle mask of size \p Sz.
44 /// For example if Sz == 4 the returned mask is {0, 1, 2, 3}.
45 static ShuffleMask getIdentity(unsigned Sz) {
46 IndicesVecT Indices;
47 Indices.reserve(Sz);
48 llvm::append_range(Indices, seq<int>(0, (int)Sz));
49 return ShuffleMask(std::move(Indices));
50 }
51 /// \Returns true if the mask is a perfect identity mask with consecutive
52 /// indices, i.e., performs no lane shuffling, like 0,1,2,3...
53 bool isIdentity() const {
54 for (auto [Idx, Elm] : enumerate(Indices)) {
55 if ((int)Idx != Elm)
56 return false;
57 }
58 return true;
59 }
60 bool operator==(const ShuffleMask &Other) const {
61 return Indices == Other.Indices;
62 }
63 bool operator!=(const ShuffleMask &Other) const { return !(*this == Other); }
64 size_t size() const { return Indices.size(); }
65 int operator[](int Idx) const { return Indices[Idx]; }
67 const_iterator begin() const { return Indices.begin(); }
68 const_iterator end() const { return Indices.end(); }
69#ifndef NDEBUG
70 friend raw_ostream &operator<<(raw_ostream &OS, const ShuffleMask &Mask) {
71 Mask.print(OS);
72 return OS;
73 }
74 void print(raw_ostream &OS) const {
75 interleave(Indices, OS, [&OS](auto Elm) { OS << Elm; }, ",");
76 }
77 LLVM_DUMP_METHOD void dump() const;
78#endif
79};
80
81enum class LegalityResultID {
82 Pack, ///> Collect scalar values.
83 Widen, ///> Vectorize by combining scalars to a vector.
84 DiamondReuse, ///> Don't generate new code, reuse existing vector.
85 DiamondReuseWithShuffle, ///> Reuse the existing vector but add a shuffle.
86 DiamondReuseMultiInput, ///> Reuse more than one vector and/or scalars.
87};
88
89/// The reason for vectorizing or not vectorizing.
105
106#ifndef NDEBUG
107struct ToStr {
108 static const char *getLegalityResultID(LegalityResultID ID) {
109 switch (ID) {
111 return "Pack";
113 return "Widen";
115 return "DiamondReuse";
117 return "DiamondReuseWithShuffle";
119 return "DiamondReuseMultiInput";
120 }
121 llvm_unreachable("Unknown LegalityResultID enum");
122 }
123
124 static const char *getVecReason(ResultReason Reason) {
125 switch (Reason) {
127 return "NotInstructions";
129 return "DiffOpcodes";
131 return "DiffTypes";
133 return "DiffMathFlags";
135 return "DiffWrapFlags";
137 return "DiffBBs";
139 return "RepeatedInstrs";
141 return "NotConsecutive";
143 return "AlignmentNotSupported";
145 return "CantSchedule";
147 return "Unimplemented";
149 return "Infeasible";
151 return "ForcePackForDebugging";
152 }
153 llvm_unreachable("Unknown ResultReason enum");
154 }
155};
156#endif // NDEBUG
157
158/// The legality outcome is represented by a class rather than an enum class
159/// because in some cases the legality checks are expensive and look for a
160/// particular instruction that can be passed along to the vectorizer to avoid
161/// repeating the same expensive computation.
163protected:
165 /// Only Legality can create LegalityResults.
167 friend class LegalityAnalysis;
168
169 /// We shouldn't need copies.
172
173public:
174 virtual ~LegalityResult() = default;
176#ifndef NDEBUG
177 virtual void print(raw_ostream &OS) const {
179 }
180 LLVM_DUMP_METHOD void dump() const;
182 LR.print(OS);
183 return OS;
184 }
185#endif // NDEBUG
186};
187
188/// Base class for results with reason.
189class LegalityResultWithReason : public LegalityResult {
190 ResultReason Reason;
191 LegalityResultWithReason(LegalityResultID ID, ResultReason Reason)
192 : LegalityResult(ID), Reason(Reason) {}
193 friend class Pack; // For constructor.
194
195public:
196 ResultReason getReason() const { return Reason; }
197#ifndef NDEBUG
198 void print(raw_ostream &OS) const override {
200 OS << " Reason: " << ToStr::getVecReason(Reason);
201 }
202#endif
203};
204
205class Widen final : public LegalityResult {
206 friend class LegalityAnalysis;
208
209public:
210 static bool classof(const LegalityResult *From) {
211 return From->getSubclassID() == LegalityResultID::Widen;
212 }
213};
214
215class DiamondReuse final : public LegalityResult {
216 friend class LegalityAnalysis;
217 Action *Vec;
218 DiamondReuse(Action *Vec)
219 : LegalityResult(LegalityResultID::DiamondReuse), Vec(Vec) {}
220
221public:
222 static bool classof(const LegalityResult *From) {
224 }
225 Action *getVector() const { return Vec; }
226};
227
228class DiamondReuseWithShuffle final : public LegalityResult {
229 friend class LegalityAnalysis;
230 Action *Vec;
231 ShuffleMask Mask;
233 : LegalityResult(LegalityResultID::DiamondReuseWithShuffle), Vec(Vec),
234 Mask(Mask) {}
235
236public:
237 static bool classof(const LegalityResult *From) {
239 }
240 Action *getVector() const { return Vec; }
241 const ShuffleMask &getMask() const { return Mask; }
242};
243
244class Pack final : public LegalityResultWithReason {
245 Pack(ResultReason Reason)
246 : LegalityResultWithReason(LegalityResultID::Pack, Reason) {}
247 friend class LegalityAnalysis; // For constructor.
248
249public:
250 static bool classof(const LegalityResult *From) {
251 return From->getSubclassID() == LegalityResultID::Pack;
252 }
253};
254
255/// Describes how to collect the values needed by each lane.
257public:
258 /// Describes how to get a value element. If the value is a vector then it
259 /// also provides the index to extract it from.
262 /// The index in `V` that the value can be extracted from.
263 int ExtractIdx = 0;
264
265 public:
266 ExtractElementDescr(Action *V, int ExtractIdx)
267 : V(V), ExtractIdx(ExtractIdx) {}
269 Action *getValue() const { return cast<Action *>(V); }
270 Value *getScalar() const { return cast<Value *>(V); }
271 bool needsExtract() const { return isa<Action *>(V); }
272 int getExtractIdx() const { return ExtractIdx; }
273 };
274
277
278public:
281 /// If all elements come from a single vector input, then return that vector
282 /// and also the shuffle mask required to get them in order.
283 std::optional<std::pair<Action *, ShuffleMask>> getSingleInput() const {
284 const auto &Descr0 = *Descrs.begin();
285 if (!Descr0.needsExtract())
286 return std::nullopt;
287 auto *V0 = Descr0.getValue();
288 ShuffleMask::IndicesVecT MaskIndices;
289 MaskIndices.push_back(Descr0.getExtractIdx());
290 for (const auto &Descr : drop_begin(Descrs)) {
291 if (!Descr.needsExtract())
292 return std::nullopt;
293 if (Descr.getValue() != V0)
294 return std::nullopt;
295 MaskIndices.push_back(Descr.getExtractIdx());
296 }
297 return std::make_pair(V0, ShuffleMask(std::move(MaskIndices)));
298 }
299 bool hasVectorInputs() const {
300 return any_of(Descrs, [](const auto &D) { return D.needsExtract(); });
301 }
303 return Descrs;
304 }
305};
306
307class DiamondReuseMultiInput final : public LegalityResult {
308 friend class LegalityAnalysis;
309 CollectDescr Descr;
311 : LegalityResult(LegalityResultID::DiamondReuseMultiInput),
312 Descr(std::move(Descr)) {}
313
314public:
315 static bool classof(const LegalityResult *From) {
317 }
318 const CollectDescr &getCollectDescr() const { return Descr; }
319};
320
321/// Performs the legality analysis and returns a LegalityResult object.
323 Scheduler Sched;
324 /// Owns the legality result objects created by createLegalityResult().
326 /// Checks opcodes, types and other IR-specifics and returns a ResultReason
327 /// object if not vectorizable, or nullptr otherwise.
328 std::optional<ResultReason>
329 notVectorizableBasedOnOpcodesAndTypes(BndlRef<Value *> Bndl);
330
331 ScalarEvolution &SE;
332 const DataLayout &DL;
334 InstrMaps &IMaps;
335
336 /// Finds how we can collect the values in \p Bndl from the vectorized or
337 /// non-vectorized code. It returns a map of the value we should extract from
338 /// and the corresponding shuffle mask we need to use.
339 CollectDescr getHowToCollectValues(BndlRef<Value *> Bndl) const;
340
341public:
343 TargetTransformInfo &TTI, Context &Ctx, InstrMaps &IMaps,
344 SchedDirection Dir)
345 : Sched(AA, Ctx, Dir), SE(SE), DL(DL), TTI(TTI), IMaps(IMaps) {}
346 /// A LegalityResult factory.
347 template <typename ResultT, typename... ArgsT>
348 ResultT &createLegalityResult(ArgsT &&...Args) {
349 ResultPool.push_back(
350 std::unique_ptr<ResultT>(new ResultT(std::move(Args)...)));
351 return cast<ResultT>(*ResultPool.back());
352 }
353
354 /// \returns true if \p Instrs are in different blocks.
355 template <typename ValueT>
356 static bool differentBlock(BndlRef<ValueT *> Instrs) {
357 auto *BB0 = cast<Instruction>(Instrs[0])->getParent();
358 return any_of(drop_begin(Instrs), [BB0](auto *V) {
359 return cast<Instruction>(V)->getParent() != BB0;
360 });
361 }
362
363 /// \returns true if all values in \p Values are unique.
364 template <typename ValueT> static bool areUnique(BndlRef<ValueT *> Values) {
366 return Unique.size() == Values.size();
367 }
368
369 /// \returns true if the alignment of the vector composed of \p Values has
370 /// alignment that is supported by the target.
372
373 /// Checks if it's legal to vectorize the instructions in \p Bndl.
374 /// \Returns a LegalityResult object owned by LegalityAnalysis.
375 /// \p SkipScheduling skips the scheduler check and is only meant for testing.
376 // TODO: Try to remove the SkipScheduling argument by refactoring the tests.
378 bool SkipScheduling = false);
379 /// \Returns a Pack with reason 'ForcePackForDebugging'.
383 LLVM_ABI void clear();
384};
385
386} // namespace llvm::sandboxir
387
388#endif // LLVM_TRANSFORMS_VECTORIZE_SANDBOXVECTORIZER_LEGALITY_H
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
#define LLVM_ABI
Definition Compiler.h:215
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:686
This pass exposes codegen information to IR-level passes.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A discriminated union of two or more pointer types, with the discriminator in the low bits of the poi...
The main scalar evolution driver.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
typename SuperClass::const_iterator const_iterator
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
An ArrayRef of Values or Instructions that we can print/dump for debugging.
Definition VecUtils.h:39
ExtractElementDescr(Action *V, int ExtractIdx)
Definition Legality.h:266
Describes how to collect the values needed by each lane.
Definition Legality.h:256
const SmallVector< ExtractElementDescr, 4 > & getDescrs() const
Definition Legality.h:302
SmallVector< ExtractElementDescr, 4 > DescrVecT
Definition Legality.h:275
std::optional< std::pair< Action *, ShuffleMask > > getSingleInput() const
If all elements come from a single vector input, then return that vector and also the shuffle mask re...
Definition Legality.h:283
CollectDescr(SmallVectorImpl< ExtractElementDescr > &&Descrs)
Definition Legality.h:279
static bool classof(const LegalityResult *From)
Definition Legality.h:315
const CollectDescr & getCollectDescr() const
Definition Legality.h:318
const ShuffleMask & getMask() const
Definition Legality.h:241
static bool classof(const LegalityResult *From)
Definition Legality.h:237
Action * getVector() const
Definition Legality.h:225
static bool classof(const LegalityResult *From)
Definition Legality.h:222
Maps the original instructions to the vectorized instrs and the reverse.
Definition InstrMaps.h:50
Performs the legality analysis and returns a LegalityResult object.
Definition Legality.h:322
const LegalityResult & getForcedPackForDebugging()
\Returns a Pack with reason 'ForcePackForDebugging'.
Definition Legality.h:380
LegalityAnalysis(AAResults &AA, ScalarEvolution &SE, const DataLayout &DL, TargetTransformInfo &TTI, Context &Ctx, InstrMaps &IMaps, SchedDirection Dir)
Definition Legality.h:342
LLVM_ABI const LegalityResult & canVectorize(BndlRef< Value * > Bndl, bool SkipScheduling=false)
Checks if it's legal to vectorize the instructions in Bndl.
Definition Legality.cpp:236
LLVM_ABI bool isAlignmentSupported(ArrayRef< Value * > Values) const
Definition Legality.cpp:217
static bool areUnique(BndlRef< ValueT * > Values)
Definition Legality.h:364
static bool differentBlock(BndlRef< ValueT * > Instrs)
Definition Legality.h:356
ResultT & createLegalityResult(ArgsT &&...Args)
A LegalityResult factory.
Definition Legality.h:348
void print(raw_ostream &OS) const override
Definition Legality.h:198
The legality outcome is represented by a class rather than an enum class because in some cases the le...
Definition Legality.h:162
LegalityResult & operator=(const LegalityResult &)=delete
friend raw_ostream & operator<<(raw_ostream &OS, const LegalityResult &LR)
Definition Legality.h:181
LLVM_DUMP_METHOD void dump() const
Definition Legality.cpp:27
virtual ~LegalityResult()=default
LegalityResultID getSubclassID() const
Definition Legality.h:175
virtual void print(raw_ostream &OS) const
Definition Legality.h:177
LegalityResult(LegalityResultID ID)
Only Legality can create LegalityResults.
Definition Legality.h:166
LegalityResult(const LegalityResult &)=delete
We shouldn't need copies.
friend class LegalityAnalysis
Definition Legality.h:247
static bool classof(const LegalityResult *From)
Definition Legality.h:250
The list scheduler.
Definition Scheduler.h:302
ShuffleMask(std::initializer_list< int > Indices)
Definition Legality.h:40
void print(raw_ostream &OS) const
Definition Legality.h:74
bool isIdentity() const
\Returns true if the mask is a perfect identity mask with consecutive indices, i.e....
Definition Legality.h:53
const_iterator end() const
Definition Legality.h:68
ShuffleMask(SmallVectorImpl< int > &&Indices)
Definition Legality.h:39
static ShuffleMask getIdentity(unsigned Sz)
Creates and returns an identity shuffle mask of size Sz.
Definition Legality.h:45
LLVM_DUMP_METHOD void dump() const
Definition Legality.cpp:22
bool operator==(const ShuffleMask &Other) const
Definition Legality.h:60
bool operator!=(const ShuffleMask &Other) const
Definition Legality.h:63
IndicesVecT::const_iterator const_iterator
Definition Legality.h:66
int operator[](int Idx) const
Definition Legality.h:65
friend raw_ostream & operator<<(raw_ostream &OS, const ShuffleMask &Mask)
Definition Legality.h:70
ShuffleMask(ArrayRef< int > Indices)
Definition Legality.h:41
const_iterator begin() const
Definition Legality.h:67
SmallVector< int, 8 > IndicesVecT
Definition Legality.h:33
A SandboxIR Value has users. This is the base class.
Definition Value.h:72
friend class LegalityAnalysis
Definition Legality.h:206
static bool classof(const LegalityResult *From)
Definition Legality.h:210
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:165
ResultReason
The reason for vectorizing or not vectorizing.
Definition Legality.h:90
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
void interleave(ForwardIterator begin, ForwardIterator end, UnaryFunctor each_fn, NullaryFunctor between_fn)
An STL-style algorithm similar to std::for_each that applies a second functor between every pair of e...
Definition STLExtras.h:2291
constexpr from_range_t from_range
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ Other
Any other memory.
Definition ModRef.h:68
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
static const char * getVecReason(ResultReason Reason)
Definition Legality.h:124
static const char * getLegalityResultID(LegalityResultID ID)
Definition Legality.h:108