MLIR 24.0.0git
TestTarget.cpp
Go to the documentation of this file.
1//===- TestTarget.cpp - Predictable test ABI target ----------------------===//
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// **NOT A REAL ABI TARGET.**
10//
11// This file implements a predictable, dialect-agnostic ABI classifier for
12// testing the MLIR ABIRewriteContext infrastructure. The rules approximate
13// x86_64 SysV thresholds (Direct / Extend / Indirect / Ignore / Expand) so
14// the generated classifications are familiar to reviewers, but they are
15// NOT a substitute for testing against the real x86_64 ABIInfo. Real
16// ABI targets live alongside the LLVM ABI library in `llvm/lib/ABI/Targets/`.
17//
18// Real-ABI-shaped tests use the classification-injection driver via
19// `parseClassificationAttr`, which lets tests construct any
20// FunctionClassification (including shapes the test target itself does
21// not produce) by attaching a DictionaryAttr to the function.
22//
23// Rules:
24// - mlir::NoneType → Ignore
25// - IntegerType with width < 32 → Extend (zero-extend by
26// default; tests using the
27// injection driver can
28// override to signed)
29// - IntegerType with width >= 32 → Direct
30// - FloatType, VectorType, MemRefType → Direct
31// - Anything else with DataLayout size 0 → Ignore
32// - Anything else with DataLayout size <= 16 → Direct (coerced to the
33// same type — no actual
34// coercion in the test
35// target; PR C handles
36// non-trivial coercion)
37// - Anything else with DataLayout size > 16 → Indirect with byval=true
38// (sret on returns) and
39// alignment from
40// DataLayout
41//
42//===----------------------------------------------------------------------===//
43
46#include "llvm/Support/Alignment.h"
47
48using namespace mlir;
49using namespace mlir::abi;
50using namespace mlir::abi::test;
51
52namespace {
53
54/// Indirect-vs-direct cutoff in bytes. Chosen to match x86_64 SysV's
55/// 16-byte register-passing window for reviewer familiarity.
56constexpr uint64_t IndirectCutoffBytes = 16;
57
58/// Below this width (in bits) integers get an extension attribute.
59/// Chosen to match x86_64 SysV (32-bit register width) for reviewer
60/// familiarity.
61constexpr unsigned ExtendBelowBits = 32;
62
63ArgClassification classifyOne(Type type, const DataLayout &dl) {
64 if (isa<NoneType>(type))
66
67 if (auto intTy = dyn_cast<IntegerType>(type)) {
68 if (intTy.getWidth() < ExtendBelowBits) {
69 Type i32Ty = IntegerType::get(type.getContext(), ExtendBelowBits);
70 return ArgClassification::getExtend(i32Ty, /*signExt=*/intTy.isSigned());
71 }
73 }
74
75 if (auto indexTy = dyn_cast<IndexType>(type)) {
76 llvm::TypeSize sizeInBits = dl.getTypeSizeInBits(indexTy);
77 if (sizeInBits.getFixedValue() < ExtendBelowBits) {
78 Type i32Ty = IntegerType::get(type.getContext(), ExtendBelowBits);
79 return ArgClassification::getExtend(i32Ty, /*signExt=*/true);
80 }
82 }
83
84 if (isa<FloatType, VectorType, MemRefType>(type))
86
87 // For dialect-specific types: query DataLayout via
88 // DataLayoutTypeInterface. Types that don't implement the interface
89 // (e.g. dialect-specific void / unit-style sentinel types used as a
90 // function's "no return value" marker) are treated as Ignore so that
91 // the test target degrades gracefully rather than crashing on unknown
92 // types.
93 if (!isa<DataLayoutTypeInterface>(type))
95
96 llvm::TypeSize sizeInBits = dl.getTypeSizeInBits(type);
97 if (sizeInBits.isZero())
99
100 uint64_t sizeInBytes = (sizeInBits.getFixedValue() + 7) / 8;
101 if (sizeInBytes <= IndirectCutoffBytes)
103
104 uint64_t alignBytes = dl.getTypeABIAlignment(type);
105 return ArgClassification::getIndirect(llvm::Align(alignBytes),
106 /*byVal=*/true, /*addrSpace=*/0);
107}
108
109} // namespace
110
112 Type returnType,
113 const DataLayout &dl) {
115 fc.returnInfo = classifyOne(returnType, dl);
116 fc.argInfos.reserve(argTypes.size());
117 for (Type t : argTypes)
118 fc.argInfos.push_back(classifyOne(t, dl));
119 return fc;
120}
121
122namespace {
123
124/// Set of dictionary keys this parser knows about. Any key not in this
125/// set causes a parse error (no silent ignore). Updated when new
126/// optional keys are added to the schema.
127constexpr StringRef knownArgKeys[] = {
128 "kind", "coerced_type", "sign_extend", "can_flatten",
129 "direct_align", "indirect_align", "byval", "indirect_addr_space",
130};
131
132bool isKnownArgKey(StringRef key) {
133 for (StringRef k : knownArgKeys)
134 if (k == key)
135 return true;
136 return false;
137}
138
139/// Parse a single ArgClassification dictionary. Returns failure on
140/// any error (with the diagnostic emitted via \p emitError).
141FailureOr<ArgClassification>
142parseOne(DictionaryAttr argDict, function_ref<InFlightDiagnostic()> emitError) {
143 StringAttr kindAttr = argDict.getAs<StringAttr>("kind");
144 if (!kindAttr) {
145 emitError() << "missing required 'kind' StringAttr";
146 return failure();
147 }
148
149 for (NamedAttribute na : argDict)
150 if (!isKnownArgKey(na.getName().getValue())) {
151 emitError() << "unknown key '" << na.getName().getValue()
152 << "' in classification dictionary; allowed keys are "
153 << "kind, coerced_type, sign_extend, can_flatten, "
154 << "direct_align, indirect_align, byval, "
155 << "indirect_addr_space";
156 return failure();
157 }
158
159 StringRef kind = kindAttr.getValue();
160
161 if (kind == "direct") {
162 Type coerced;
163 if (auto t = argDict.getAs<TypeAttr>("coerced_type"))
164 coerced = t.getValue();
165 llvm::MaybeAlign align;
166 if (auto da = argDict.getAs<IntegerAttr>("direct_align")) {
167 if (da.getInt() <= 0 || !llvm::isPowerOf2_64(da.getInt())) {
168 emitError() << "'direct_align' must be a positive power of 2; got "
169 << da.getInt();
170 return failure();
171 }
172 align = llvm::Align(da.getInt());
173 }
174 auto c = ArgClassification::getDirect(coerced, /*offset=*/0, align);
175 if (auto cf = argDict.getAs<BoolAttr>("can_flatten"))
176 c.canFlatten = cf.getValue();
177 return c;
178 }
179
180 if (kind == "extend") {
181 auto coerced = argDict.getAs<TypeAttr>("coerced_type");
182 if (!coerced) {
183 emitError() << "kind='extend' requires 'coerced_type' TypeAttr";
184 return failure();
185 }
186 bool signExt = false;
187 if (auto se = argDict.getAs<BoolAttr>("sign_extend"))
188 signExt = se.getValue();
189 return ArgClassification::getExtend(coerced.getValue(), signExt);
190 }
191
192 if (kind == "indirect" || kind == "indirect_aliased") {
193 auto align = argDict.getAs<IntegerAttr>("indirect_align");
194 if (!align) {
195 emitError() << "kind='" << kind
196 << "' requires 'indirect_align' IntegerAttr";
197 return failure();
198 }
199 if (align.getInt() <= 0 || !llvm::isPowerOf2_64(align.getInt())) {
200 emitError() << "'indirect_align' must be a positive power of 2; got "
201 << align.getInt();
202 return failure();
203 }
204 unsigned addrSpace = 0;
205 if (auto as = argDict.getAs<IntegerAttr>("indirect_addr_space")) {
206 if (as.getInt() < 0) {
207 emitError() << "'indirect_addr_space' must be non-negative; got "
208 << as.getInt();
209 return failure();
210 }
211 addrSpace = as.getInt();
212 }
213 if (kind == "indirect_aliased") {
214 if (argDict.get("byval")) {
215 emitError() << "kind='indirect_aliased' does not take 'byval'";
216 return failure();
217 }
218 return ArgClassification::getIndirectAliased(llvm::Align(align.getInt()),
219 addrSpace);
220 }
221 bool byVal = true;
222 if (auto bv = argDict.getAs<BoolAttr>("byval"))
223 byVal = bv.getValue();
224 return ArgClassification::getIndirect(llvm::Align(align.getInt()), byVal,
225 addrSpace);
226 }
227
228 if (kind == "ignore") {
230 }
231
232 if (kind == "expand") {
235 return c;
236 }
237
238 emitError() << "unknown kind='" << kind
239 << "'; expected one of direct, extend, indirect, "
240 "indirect_aliased, ignore, expand";
241 return failure();
242}
243} // namespace
244
245FailureOr<FunctionClassification> mlir::abi::test::parseClassificationAttr(
246 DictionaryAttr attr, function_ref<InFlightDiagnostic()> emitError) {
247 auto returnDict = attr.getAs<DictionaryAttr>("return");
248 if (!returnDict) {
249 emitError() << "missing required 'return' DictionaryAttr";
250 return failure();
251 }
252
253 auto argsArr = attr.getAs<ArrayAttr>("args");
254 if (!argsArr) {
255 emitError() << "missing required 'args' ArrayAttr";
256 return failure();
257 }
258
259 for (NamedAttribute na : attr) {
260 StringRef k = na.getName().getValue();
261 if (k != "return" && k != "args") {
262 emitError() << "unknown top-level key '" << k
263 << "'; only 'return' and 'args' are allowed";
264 return failure();
265 }
266 }
267
269
270 FailureOr<ArgClassification> ret = parseOne(returnDict, emitError);
271 if (failed(ret))
272 return failure();
273 fc.returnInfo = *ret;
274
275 fc.argInfos.reserve(argsArr.size());
276 for (Attribute a : argsArr) {
277 auto d = dyn_cast<DictionaryAttr>(a);
278 if (!d) {
279 emitError() << "'args' entries must be DictionaryAttrs";
280 return failure();
281 }
282 FailureOr<ArgClassification> ac = parseOne(d, emitError);
283 if (failed(ac))
284 return failure();
285 fc.argInfos.push_back(*ac);
286 }
287
288 return fc;
289}
Attributes are known-constant values of operations.
Definition Attributes.h:25
Special case of IntegerAttr to represent boolean integers, i.e., signless i1 integers.
The main mechanism for performing data layout queries.
uint64_t getTypeABIAlignment(Type t) const
Returns the required alignment of the given type in the current scope.
llvm::TypeSize getTypeSizeInBits(Type t) const
Returns the size in bits of the given type in the current scope.
This class represents a diagnostic that is inflight and set to be reported.
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:166
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
Definition Types.cpp:35
FailureOr< FunctionClassification > parseClassificationAttr(DictionaryAttr attr, function_ref< InFlightDiagnostic()> emitError)
Parse a FunctionClassification from a plain MLIR DictionaryAttr.
FunctionClassification classify(TypeRange argTypes, Type returnType, const DataLayout &dl)
Classify a function signature using the test target's predictable rules.
@ Expand
Expand an aggregate into its constituent scalar fields.
Include the generated interface declarations.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
Describes how a single argument or return value is passed after ABI lowering.
static ArgClassification getIgnore()
static ArgClassification getDirect()
static ArgClassification getIndirect(llvm::Align align, bool byVal, unsigned addrSpace)
static ArgClassification getIndirectAliased(llvm::Align align, unsigned addrSpace)
static ArgClassification getExtend(Type coerced, bool signExt)
Holds the full ABI classification for a function: return type and all arguments.
SmallVector< ArgClassification > argInfos