clang 24.0.0git
CIRABIClassifier.cpp
Go to the documentation of this file.
1//===- CIRABIClassifier.cpp - ABI classification for CIR ------------------===//
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 file implements the classification shared by the targets that classify
10// through the LLVM ABI Lowering Library, and the two test drivers that stand
11// in for a target.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CIRABIClassifier.h"
17
18#include "mlir/ABI/Targets/Test/TestTarget.h"
21#include "llvm/ABI/Types.h"
22#include "llvm/ADT/TypeSwitch.h"
23#include "llvm/Support/MathExtras.h"
24
25using namespace mlir;
26using namespace mlir::abi;
27using namespace cir;
28
29//===----------------------------------------------------------------------===//
30// LLVM ABI Lowering Library classifier bridge
31//
32// Maps CIR types to llvm::abi::Type, runs the target's classifier from the
33// LLVM ABI Lowering Library, and converts the result back into the
34// dialect-agnostic mlir::abi::FunctionClassification that CIRABIRewriteContext
35// consumes.
36//
37// isSupportedType says which CIR types the bridge handles, and a signature
38// naming any other fails the pass instead of being misclassified.
39//===----------------------------------------------------------------------===//
40
41/// Whether a struct's declared argument-passing kind (from the module's
42/// record-layout metadata) allows it to be passed in registers. A record with
43/// no layout entry (e.g. an anonymous struct) has no C++ non-trivial reason to
44/// be forced to memory, so it defaults to can-pass-in-registers.
45static bool recordCanPassInRegs(ModuleOp modOp, cir::RecordType recTy) {
46 auto layout = cir::tryGetRecordLayout(modOp, recTy.getName());
47 if (!layout)
48 return true;
49 return layout.getArgPassingKind() == cir::ArgPassingKind::CanPassInRegs;
50}
51
52static bool recordIsTransparentUnion(ModuleOp modOp, cir::RecordType recTy) {
53 auto layout = cir::tryGetRecordLayout(modOp, recTy.getName());
54 return layout && layout.getTransparentUnion();
55}
56
57/// Read from the layout, which also covers a last field that has one.
58static bool recordHasFlexibleArrayMember(ModuleOp modOp,
59 cir::RecordType recTy) {
60 auto layout = cir::tryGetRecordLayout(modOp, recTy.getName());
61 return layout && layout.getFlexibleArrayMember();
62}
63
64/// Whether the classifier could give this type the SSEUP class, looking
65/// through arrays and records at the types they hold.
66static bool mayReachSseUp(mlir::Type ty, const DataLayout &dl) {
67 // The classifier sizes a vector with its width rounded up to a power of two.
68 if (isa<cir::VectorType>(ty))
69 return llvm::PowerOf2Ceil(dl.getTypeSizeInBits(ty).getFixedValue()) >= 128;
70 if (auto fpTy = dyn_cast<cir::FPTypeInterface>(ty))
71 return &fpTy.getFloatSemantics() == &llvm::APFloat::IEEEquad();
72 if (auto arrTy = dyn_cast<cir::ArrayType>(ty))
73 return mayReachSseUp(arrTy.getElementType(), dl);
74 if (auto recTy = dyn_cast<cir::RecordType>(ty))
75 return recTy.isComplete() &&
76 llvm::any_of(recTy.getMembers(),
77 [&](mlir::Type m) { return mayReachSseUp(m, dl); });
78 // The rest classify integer, SSE or memory. A complex is SSE at float and
79 // double width and memory above that, so it needs no walk of its own.
80 assert((isa<cir::IntType, cir::BoolType, cir::PointerType, cir::VPtrType,
81 cir::VoidType, cir::ComplexType, cir::BitFieldType>(ty)) &&
82 "unhandled type in the SSEUP walk");
83 return false;
84}
85
86/// Whether the record's size has no SSEUP coerce. That coerce is a vector as
87/// wide as the record, so only 128, 256 and 512 bits have one. A record past
88/// 512 bits classifies memory before any coerce is asked for.
89static bool sseUpCoerceSizeUnsupported(uint64_t recordBits,
91 const DataLayout &dl) {
92 if (recordBits == 128 || recordBits == 256 || recordBits == 512)
93 return false;
94 if (recordBits < 128 || recordBits > 512)
95 return false;
96 return llvm::any_of(members,
97 [&](mlir::Type m) { return mayReachSseUp(m, dl); });
98}
99
100/// Whether a member is an empty record, looking through arrays, since an array
101/// of empty records supplies no bytes either.
102static bool memberIsEmptyRecord(mlir::Type ty) {
103 while (auto arrTy = dyn_cast<cir::ArrayType>(ty))
104 ty = arrTy.getElementType();
105 auto recTy = dyn_cast<cir::RecordType>(ty);
106 return recTy && recTy.isEmptyForABI();
107}
108
109/// A record's unadjusted alignment, the alignment its members give it before
110/// an alignment attribute on the record raises it. It comes from the module's
111/// record-layout metadata, and the computed fallback only serves hand-written
112/// CIR.
113static llvm::Align recordUnadjustedAlign(ModuleOp modOp, cir::RecordType recTy,
114 const cir::CIRDataLayout &cirDL) {
115 auto layout = cir::tryGetRecordLayout(modOp, recTy.getName());
116 if (!layout)
117 return llvm::Align(cirDL.getTypeLanguageAlignment(recTy));
118 return llvm::Align(layout.getUnadjustedAlign());
119}
120
121/// The CIR types the bridge handles. Scalars: an integer up to 128
122/// bits (including `__int128`), a `_BitInt` of any width, pointer, vtable
123/// pointer, bool, void, or any floating-point type. Aggregates: a complete
124/// struct or union whose members are all themselves supported, or an array
125/// of a supported element type. Also a `_Complex`, or a fixed-width vector,
126/// of a supported element type. Everything else is reported NYI at the
127/// reject() choke point in classifySignature.
128static bool isSupportedType(mlir::Type ty, const DataLayout &dl) {
129 // A pointer is only handled in the default address space (null) or an
130 // already-lowered target address space. A LangAddressSpaceAttr must be
131 // lowered before this pass, so reject it rather than silently dropping it.
132 if (auto ptrTy = dyn_cast<cir::PointerType>(ty))
133 return !ptrTy.getAddrSpace() ||
134 mlir::isa<cir::TargetAddressSpaceAttr>(ptrTy.getAddrSpace());
135 // cir::VPtrType carries no address-space parameter yet, so its target
136 // address space cannot be checked here even though it is not always the
137 // default one.
138 if (isa<cir::VPtrType>(ty)) {
140 return true;
141 }
142 if (isa<cir::VoidType, cir::BoolType>(ty))
143 return true;
144 // Every CIR floating-point type carries the semantics the classifier
145 // switches on, so all of them are handled.
146 if (isa<cir::FPTypeInterface>(ty))
147 return true;
148 if (auto intTy = dyn_cast<cir::IntType>(ty)) {
149 // Integers up to 64 bits, __int128, and _BitInt of any width are
150 // handled: the classifier extends a width below 32, widens 33 through 63
151 // to i64, coerces 65 through 127 to a {i64, i64} pair, and passes 32, 64,
152 // and 128 in the natural type. A _BitInt wider than 128 bits classifies
153 // Indirect, the same path an oversized aggregate already takes.
154 // Non-_BitInt intermediate widths (65..127) do not arise from C and stay
155 // rejected.
156 if (intTy.getIsBitInt())
157 return true;
158 return intTy.getWidth() <= 64 || intTy.getWidth() == 128;
159 }
160 if (auto complexTy = dyn_cast<cir::ComplexType>(ty))
161 return isSupportedType(complexTy.getElementType(), dl);
162 if (auto vecTy = dyn_cast<cir::VectorType>(ty)) {
163 // A scalable vector has no fixed size, and no target that classifies
164 // through the bridge passes one yet.
165 if (vecTy.isScalable())
166 return false;
167 // mapCIRType maps a bool as a one-bit integer, so a bool vector is sized
168 // one bit per element, as clang packs it. Vectors of a _BitInt whose
169 // width is not a whole number of bytes are not handled yet.
170 mlir::Type elemTy = vecTy.getElementType();
171 if (auto elemInt = dyn_cast<cir::IntType>(elemTy)) {
172 if (elemInt.getWidth() % 8)
173 return false;
174 } else if (!isa<cir::FPTypeInterface, cir::BoolType>(elemTy)) {
175 return false;
176 }
177 return isSupportedType(elemTy, dl);
178 }
179 if (auto arrTy = dyn_cast<cir::ArrayType>(ty))
180 return isSupportedType(arrTy.getElementType(), dl);
181 // A bit-field is classified from the type it was declared with and the bits
182 // it holds, and is loaded through its access unit, so both types have to be
183 // ones the bridge handles. A zero-width bit-field has no unit of its own.
184 if (auto bfTy = dyn_cast<cir::BitFieldType>(ty)) {
185 if (mlir::Type storageTy = bfTy.getStorageType())
186 if (!isSupportedType(storageTy, dl))
187 return false;
188 return llvm::all_of(bfTy.getFields(), [&](cir::BitFieldDeclAttr decl) {
189 return isSupportedType(decl.getDeclaredType(), dl);
190 });
191 }
192 if (auto recTy = dyn_cast<cir::RecordType>(ty)) {
193 // An incomplete record has no layout to classify.
194 if (!recTy.isComplete())
195 return false;
196 // The members are checked first so that everything below reasons only
197 // about types the bridge handles.
198 if (!llvm::all_of(recTy.getMembers(),
199 [&](mlir::Type m) { return isSupportedType(m, dl); }))
200 return false;
201 if (recTy.isUnion()) {
202 llvm::ArrayRef<mlir::Type> members = recTy.getMembers();
203 uint64_t recordBits = dl.getTypeSizeInBits(recTy).getFixedValue();
204 // Refuse a union that could reach SSEUP at a size no coerce exists for.
205 // The classifier asserts on those rather than returning a coerce.
206 if (sseUpCoerceSizeUnsupported(recordBits, members, dl))
207 return false;
208 // A member-less union is all padding, which classifies Ignore up to two
209 // eightbytes. Past that SysV says MEMORY regardless of content, and
210 // there is no member here to build the Indirect coercion from.
211 if (members.empty() && recordBits > 128)
212 return false;
213 // A `_BitInt` access unit past an eightbyte has byte-array storage in
214 // CIR and integer storage in classic CodeGen, so the narrowing walk
215 // finds an i8 in the second eightbyte where classic keeps an i64.
216 if (llvm::any_of(members, [&](mlir::Type m) {
217 auto bfTy = dyn_cast<cir::BitFieldType>(m);
218 if (!bfTy || dl.getTypeSizeInBits(bfTy).getFixedValue() <= 64)
219 return false;
220 return llvm::any_of(bfTy.getFields(), [](cir::BitFieldDeclAttr d) {
221 return cir::isBitIntType(d.getDeclaredType());
222 });
223 }))
224 return false;
225 } else {
226 // A struct's `empty` member that occupies bytes is later read as an
227 // unnamed bit-field. An empty-for-ABI record occupies its own padding,
228 // and reading that as a unit would hand the classifier storage classic
229 // CodeGen ignores. A zero-sized one is dropped before classification,
230 // so a misaligned one never reaches the rule that sends its record to
231 // memory. A union needs neither rule: mapCIRType skips such a variant
232 // instead of reading it as a unit, and every variant sits at offset
233 // zero.
234 for (auto [idx, memberTy, kind] :
235 llvm::enumerate(recTy.getMembers(), recTy.getMemberKinds())) {
236 if (kind != cir::RecordMemberKind::Empty)
237 continue;
238 if (dl.getTypeSizeInBits(memberTy).getFixedValue()) {
239 if (memberIsEmptyRecord(memberTy))
240 return false;
241 } else if (recTy.getElementOffset(dl, idx) %
242 dl.getTypeABIAlignment(memberTy)) {
243 return false;
244 }
245 }
246 }
247 return true;
248 }
249 return false;
250}
251
252/// Convert an llvm::abi::Type coercion type back to a CIR type.
253static mlir::Type abiTypeToCIR(const llvm::abi::Type *ty, MLIRContext *ctx) {
254 if (!ty)
255 return nullptr;
256 return llvm::TypeSwitch<const llvm::abi::Type *, mlir::Type>(ty)
257 .Case(
258 [&](const llvm::abi::VoidType *) { return cir::VoidType::get(ctx); })
259 .Case([&](const llvm::abi::IntegerType *intTy) -> mlir::Type {
260 // mapCIRType maps a bool as a one-bit integer.
261 if (intTy->isBool())
262 return cir::BoolType::get(ctx);
263 return cir::IntType::get(ctx, intTy->getSizeInBits().getFixedValue(),
264 intTy->isSigned(), intTy->isBitInt());
265 })
266 .Case([&](const llvm::abi::FloatType *fltTy) {
267 return cir::getFloatingPointType(*fltTy->getSemantics(), ctx);
268 })
269 .Case([&](const llvm::abi::PointerType *ptrTy) {
270 auto voidTy = cir::VoidType::get(ctx);
271 if (unsigned as = ptrTy->getAddrSpace())
272 return cir::PointerType::get(
273 voidTy, cir::TargetAddressSpaceAttr::get(ctx, as));
274 return cir::PointerType::get(voidTy);
275 })
276 .Case([&](const llvm::abi::VectorType *vecTy) -> mlir::Type {
277 mlir::Type elemCIR = abiTypeToCIR(vecTy->getElementType(), ctx);
278 if (!elemCIR)
279 return nullptr;
280 return cir::VectorType::getFixed(
281 elemCIR, vecTy->getNumElements().getFixedValue());
282 })
283 .Case([&](const llvm::abi::ArrayType *arrTy) -> mlir::Type {
284 mlir::Type elemCIR = abiTypeToCIR(arrTy->getElementType(), ctx);
285 if (!elemCIR)
286 return nullptr;
287 return cir::ArrayType::get(elemCIR, arrTy->getNumElements());
288 })
289 .Case([&](const llvm::abi::RecordType *recTy) -> mlir::Type {
290 SmallVector<mlir::Type> fieldTypes;
291 fieldTypes.reserve(recTy->getFields().size());
292 for (const auto &field : recTy->getFields()) {
293 mlir::Type fieldCIR = abiTypeToCIR(field.FieldType, ctx);
294 if (!fieldCIR)
295 return nullptr;
296 fieldTypes.push_back(fieldCIR);
297 }
298 // Coercion types are plain register tuples, not the source record.
299 return cir::StructType::get(
300 ctx, fieldTypes, /*packed=*/false,
301 /*is_class=*/false, cir::RecordType::getAllDataKinds(fieldTypes));
302 })
303 .Default([](const llvm::abi::Type *) -> mlir::Type { return nullptr; });
304}
305
306/// Returns \p ty with a LongDoubleType vector element replaced by its
307/// underlying format, which is the element abiTypeToCIR builds for the same
308/// float.
309static mlir::Type unwrapLongDoubleVectorElement(mlir::Type ty) {
310 if (auto vecTy = dyn_cast<cir::VectorType>(ty)) {
311 if (auto longDoubleTy =
312 dyn_cast<cir::LongDoubleType>(vecTy.getElementType()))
313 return cir::VectorType::get(longDoubleTy.getUnderlying(),
314 vecTy.getSize());
315 }
316 return ty;
317}
318
319/// Map a CIR type to an llvm::abi::Type. classifySignature pre-filters
320/// the signature, so only the scalar and struct/array types handled here can
321/// reach this function.
322static const llvm::abi::Type *mapCIRType(mlir::Type type,
323 mlir::abi::ABITypeMapper &typeMapper,
324 const DataLayout &dl,
325 const cir::CIRDataLayout &cirDL,
326 ModuleOp modOp) {
327 llvm::abi::TypeBuilder &tb = typeMapper.getTypeBuilder();
328 return llvm::TypeSwitch<mlir::Type, const llvm::abi::Type *>(type)
329 .Case([&](cir::IntType intTy) {
330 return tb.getIntegerType(
331 intTy.getWidth(), llvm::Align(cirDL.getTypeLanguageAlignment(type)),
332 intTy.isSigned(), intTy.getIsBitInt());
333 })
334 .Case([&](cir::PointerType ptrTy) {
335 unsigned addrSpace = 0;
336 if (auto targetAsAttr =
337 dyn_cast_if_present<cir::TargetAddressSpaceAttr>(
338 ptrTy.getAddrSpace()))
339 addrSpace = targetAsAttr.getValue();
340 // Any address-space attribute is a qualifier.
341 bool hasAddressSpaceQualifier = ptrTy.getAddrSpace() != nullptr;
342 return tb.getPointerType(
343 dl.getTypeSizeInBits(type),
344 llvm::Align(cirDL.getTypeLanguageAlignment(type)), addrSpace,
345 hasAddressSpaceQualifier);
346 })
347 .Case([&](cir::VPtrType) {
348 // cir::VPtrType carries no address-space parameter yet, so this
349 // always maps into the default one until that gap closes.
351 return tb.getPointerType(
352 dl.getTypeSizeInBits(type),
353 llvm::Align(cirDL.getTypeLanguageAlignment(type)));
354 })
355 .Case([&](cir::BoolType) {
356 // A bool is a one-bit integer to the classifier, as QualTypeMapper
357 // maps it, so a bool vector is sized one bit per element.
358 return tb.getIntegerType(
359 1, llvm::Align(cirDL.getTypeLanguageAlignment(type)),
360 /*Signed=*/false);
361 })
362 .Case([&](cir::VoidType) { return tb.getVoidType(); })
363 .Case([&](cir::FPTypeInterface fpTy) {
364 // LongDoubleType reports its underlying format's semantics, so the
365 // classifier sees x87 or IEEE quad rather than the wrapper.
366 return tb.getFloatType(
367 fpTy.getFloatSemantics(),
368 llvm::Align(cirDL.getTypeLanguageAlignment(type)));
369 })
370 .Case([&](cir::ComplexType complexTy) {
371 return tb.getComplexType(
372 mapCIRType(complexTy.getElementType(), typeMapper, dl, cirDL,
373 modOp),
374 llvm::Align(cirDL.getTypeLanguageAlignment(type)));
375 })
376 .Case([&](cir::VectorType vecTy) {
377 // isSupportedType rejects a scalable vector, so the element count is
378 // always fixed here.
379 return tb.getVectorType(
380 mapCIRType(vecTy.getElementType(), typeMapper, dl, cirDL, modOp),
381 vecTy.getSize(), llvm::Align(cirDL.getTypeLanguageAlignment(type)));
382 })
383 .Case([&](cir::ArrayType arrTy) {
384 const llvm::abi::Type *elemAbi =
385 mapCIRType(arrTy.getElementType(), typeMapper, dl, cirDL, modOp);
386 return tb.getArrayType(elemAbi, arrTy.getSize(),
387 dl.getTypeSizeInBits(type).getFixedValue());
388 })
389 .Case([&](cir::RecordType recTy) -> const llvm::abi::Type * {
390 llvm::abi::RecordFlags flags = llvm::abi::RecordFlags::None;
391 if (recordCanPassInRegs(modOp, recTy))
392 flags = flags | llvm::abi::RecordFlags::CanPassInRegisters;
393 if (recordIsTransparentUnion(modOp, recTy))
394 flags = flags | llvm::abi::RecordFlags::IsTransparent;
395 if (recordHasFlexibleArrayMember(modOp, recTy))
396 flags = flags | llvm::abi::RecordFlags::HasFlexibleArrayMember;
397 llvm::TypeSize sizeBits = llvm::TypeSize::getFixed(
398 dl.getTypeSizeInBits(type).getFixedValue());
399 llvm::Align align(cirDL.getTypeLanguageAlignment(recTy));
400 llvm::Align unadjustedAlign =
401 recordUnadjustedAlign(modOp, recTy, cirDL);
402
403 // Mapped with no fields, an empty record reaches Ignore on its own.
404 // The size still matters, since a target may pass a large empty
405 // record in memory whatever its content.
406 if (recTy.isEmptyForABI())
407 return tb.getRecordType(
408 /*Fields=*/{}, sizeBits, align, unadjustedAlign,
409 llvm::abi::StructPacking::Default,
410 /*BaseClasses=*/{}, /*VirtualBaseClasses=*/{}, flags);
411
413 fields.reserve(recTy.getMembers().size());
414
415 // The classifier reads one entry per source bit-field, so a unit is
416 // spread back out into the fields it holds. The targets classified
417 // here are little-endian, so the unit's first byte holds the first of
418 // them, and the rest follow at the widths ahead of them.
419 //
420 // A coercion for a register is built from the type at the first byte
421 // the register holds, where the unit's first field sits, so that
422 // field's entry carries the unit rather than its own declared type.
423 // The bits holding user data are a separate question, and the answer
424 // is the extent of the type each field was declared with, which the
425 // classifier reads through to decide whether a narrower coercion
426 // would drop something. One entry cannot answer both, so a unit
427 // narrower than its first field's declaration takes an extra entry for
428 // that declaration, holding no bits of its own. A zero-width
429 // bit-field has no unit and so contributes only the declaration.
430 //
431 // A width of zero is how the classifier recognizes the entries that
432 // take no part in assigning register classes, so the width goes
433 // through as declared.
434 auto addAccessUnit = [&](cir::BitFieldType bfTy,
435 uint64_t unitOffsetBits) {
436 mlir::Type unitTy = bfTy.getStorageType();
437 uint64_t unitBits =
438 unitTy ? dl.getTypeSizeInBits(unitTy).getFixedValue() : 0;
439 for (auto [idx, decl] : llvm::enumerate(bfTy.getFields())) {
440 const uint64_t offsetBits =
441 unitOffsetBits + bfTy.getFieldBitOffset(idx);
442 const bool holdsUnit = idx == 0 && unitTy;
443 if (holdsUnit)
444 fields.push_back(llvm::abi::FieldInfo(
445 mapCIRType(unitTy, typeMapper, dl, cirDL, modOp), offsetBits,
446 /*IsBitField=*/true, decl.getWidth(),
447 /*IsUnnamedBitField=*/decl.getIsUnnamed()));
448 mlir::Type declaredTy = decl.getDeclaredType();
449 if (!holdsUnit ||
450 dl.getTypeSizeInBits(declaredTy).getFixedValue() > unitBits)
451 fields.push_back(llvm::abi::FieldInfo(
452 mapCIRType(declaredTy, typeMapper, dl, cirDL, modOp),
453 offsetBits,
454 /*IsBitField=*/true, holdsUnit ? 0 : decl.getWidth(),
455 /*IsUnnamedBitField=*/holdsUnit || decl.getIsUnnamed()));
456 }
457 };
458
459 // The size passed here spans the tail padding, so the classifier
460 // covers the whole union rather than just the member it reduces the
461 // union to.
462 if (recTy.isUnion()) {
463 // Classify only the variants that supply data, judged by each
464 // variant's own storage rather than by its mark. One supplying
465 // none is skipped so it does not appear as a spurious argument.
466 // Whether the record is empty at all is settled from the marks
467 // before this. Every variant starts at offset zero, so a
468 // bit-field variant needs no offset of its own.
469 assert(!llvm::is_contained(recTy.getMemberKinds(),
470 cir::RecordMemberKind::Pad) &&
471 "a union member cannot be marked pad");
472 for (mlir::Type variantTy : recTy.getMembers()) {
473 if (auto bfTy = dyn_cast<cir::BitFieldType>(variantTy)) {
474 // A variant that is an unnamed bit-field holds data all the
475 // same, so it is flagged rather than skipped, as in the struct
476 // path below.
477 addAccessUnit(bfTy, /*unitOffsetBits=*/0);
478 continue;
479 }
480 if (dl.getTypeSizeInBits(variantTy).getFixedValue() == 0 ||
481 memberIsEmptyRecord(variantTy))
482 continue;
483 fields.push_back(llvm::abi::FieldInfo(
484 mapCIRType(variantTy, typeMapper, dl, cirDL, modOp)));
485 }
486 return tb.getUnionType(fields, sizeBits, align, unadjustedAlign,
487 llvm::abi::StructPacking::Default, flags);
488 }
489
490 // Padding is dropped, so the classifier sees its bytes as holding
491 // nothing, while the record's full size set above still spans them. An
492 // unnamed bit-field is flagged rather than dropped, since classic
493 // CodeGen ignores it when assigning register classes but counts it
494 // when choosing the coerce type, and a member's presence alone cannot
495 // say both.
496 for (auto [idx, fieldTy, kind] :
497 llvm::enumerate(recTy.getMembers(), recTy.getMemberKinds())) {
498 if (kind == cir::RecordMemberKind::Pad)
499 continue;
500 if (auto bfTy = dyn_cast<cir::BitFieldType>(fieldTy)) {
501 addAccessUnit(bfTy, recTy.getElementOffset(dl, idx) * 8);
502 continue;
503 }
504 // An `empty` member that is not a bit-field still stands for bytes
505 // no field of the source reads, so it is flagged the same way.
506 bool isUnnamed = kind == cir::RecordMemberKind::Empty;
507 uint64_t widthBits = dl.getTypeSizeInBits(fieldTy).getFixedValue();
508 if (isUnnamed && widthBits == 0)
509 continue;
510 assert((!isUnnamed || !memberIsEmptyRecord(fieldTy)) &&
511 "an empty-for-ABI member must not reach the classifier as an "
512 "unnamed bit-field");
513 fields.push_back(llvm::abi::FieldInfo(
514 mapCIRType(fieldTy, typeMapper, dl, cirDL, modOp),
515 recTy.getElementOffset(dl, idx) * 8,
516 /*IsBitField=*/isUnnamed, isUnnamed ? widthBits : 0,
517 /*IsUnnamedBitField=*/isUnnamed));
518 }
519
520 return tb.getRecordType(fields, sizeBits, align, unadjustedAlign,
521 llvm::abi::StructPacking::Default,
522 /*BaseClasses=*/{}, /*VirtualBaseClasses=*/{},
523 flags);
524 })
525 .Default([](mlir::Type) -> const llvm::abi::Type * {
526 llvm_unreachable(
527 "mapCIRType: type not pre-filtered by classifySignature");
528 });
529}
530
531#ifndef NDEBUG
532/// Whether \p coercedAbiTy holds the same value as the scalar \p origTy: an
533/// integer of the same width, a float with the same semantics, or a pointer.
534/// Used only in an assert in convertDirectArgInfo.
535static bool coerceKeepsScalarValue(mlir::Type origTy,
536 const llvm::abi::Type *coercedAbiTy) {
537 if (auto intTy = dyn_cast<cir::IntType>(origTy)) {
538 const auto *abiInt = dyn_cast<llvm::abi::IntegerType>(coercedAbiTy);
539 return abiInt &&
540 abiInt->getSizeInBits().getFixedValue() == intTy.getWidth();
541 }
542 if (isa<cir::BoolType>(origTy))
543 return isa<llvm::abi::IntegerType>(coercedAbiTy);
544 if (auto fpTy = dyn_cast<cir::FPTypeInterface>(origTy)) {
545 const auto *abiFloat = dyn_cast<llvm::abi::FloatType>(coercedAbiTy);
546 return abiFloat && abiFloat->getSemantics() == &fpTy.getFloatSemantics();
547 }
548 if (isa<cir::PointerType, cir::VPtrType>(origTy))
549 return isa<llvm::abi::PointerType>(coercedAbiTy);
550 return false;
551}
552#endif
553
554/// Convert a Direct llvm::abi::ArgInfo. A null coercedType in the result
555/// means the value is passed unchanged in its own type. Otherwise the
556/// rewriter converts the value to coercedType, and when that is a struct and
557/// canFlatten is set, passes each field of the struct as a separate argument.
558/// When the classifier names no coerce type, a struct or _Complex that can be
559/// flattened is coerced to a struct of its own fields.
560static mlir::FailureOr<ArgClassification>
561convertDirectArgInfo(const llvm::abi::ArgInfo &info, MLIRContext *ctx,
562 mlir::Type origTy) {
563 assert(origTy && "a Direct value must have a type");
564 unsigned offset = info.getDirectOffset();
565 llvm::MaybeAlign align = info.getDirectAlign();
566 auto passUnchanged = [&] {
567 return ArgClassification::getDirect(/*coerced=*/nullptr, /*offset=*/0,
568 align);
569 };
570 auto passCoerced = [&](mlir::Type coerced, unsigned coercedOffset) {
571 ArgClassification classified =
572 ArgClassification::getDirect(coerced, coercedOffset, align);
573 classified.canFlatten = info.getCanBeFlattened();
574 return classified;
575 };
576
577 const llvm::abi::Type *coercedAbiTy = info.getCoerceToType();
578 if (!coercedAbiTy) {
579 // A record the classifier allows to be flattened is coerced to its own
580 // type, so that its fields are passed as separate arguments. A union is
581 // flattened as its LLVM type, the storage member and the tail padding.
582 auto recTy = dyn_cast<cir::RecordType>(origTy);
583 if (recTy && (recTy.isStruct() || recTy.isUnion()) &&
584 info.getCanBeFlattened())
585 return passCoerced(recTy, /*offset=*/0);
586 // A _Complex is flattened the same way, as its {real, imag} pair.
587 if (auto complexTy = dyn_cast<cir::ComplexType>(origTy);
588 complexTy && info.getCanBeFlattened()) {
589 SmallVector<mlir::Type, 2> parts(2, complexTy.getElementType());
590 return passCoerced(
591 cir::StructType::get(ctx, parts, /*packed=*/false,
592 /*is_class=*/false,
594 /*offset=*/0);
595 }
596 return passUnchanged();
597 }
598
599 // A nonzero offset means the value's data starts that many bytes into its
600 // storage. The rewriter has no implementation of an offset for a coerced
601 // struct, either when it passes the struct's fields as separate arguments
602 // or when it fetches the struct in va_arg, so this is reported as NYI.
603 bool coercedIsStruct = isa<llvm::abi::RecordType>(coercedAbiTy);
604 if (offset && coercedIsStruct)
605 return mlir::failure();
606
607 // A scalar at byte 0 that is not split into a struct is coerced when the
608 // classifier names a wider integer or a pointer in another address space.
609 // Otherwise the classifier names a type of the same kind and width, and the
610 // scalar passes unchanged. The coerce type is not compared with the
611 // scalar's own in CIR, since converting it to CIR loses a long double's
612 // wrapper and a pointer's pointee.
613 bool isScalar =
614 !isa<cir::VectorType, cir::RecordType, cir::ArrayType, cir::ComplexType>(
615 origTy);
616 if (isScalar && !offset && !coercedIsStruct) {
617 auto origPtr = dyn_cast<cir::PointerType>(origTy);
618 const auto *coercedAbiPtr = dyn_cast<llvm::abi::PointerType>(coercedAbiTy);
619 if (origPtr && coercedAbiPtr) {
620 // Compare numbers, since an explicit address_space(0) keeps a
621 // target_address_space(0) attribute that a plain pointer lacks.
622 auto origAS = dyn_cast_if_present<cir::TargetAddressSpaceAttr>(
623 origPtr.getAddrSpace());
624 if (coercedAbiPtr->getAddrSpace() == (origAS ? origAS.getValue() : 0))
625 return passUnchanged();
626 auto coercedPtr = cast<cir::PointerType>(abiTypeToCIR(coercedAbiTy, ctx));
627 return passCoerced(cir::PointerType::get(origPtr.getPointee(),
628 coercedPtr.getAddrSpace()),
629 /*offset=*/0);
630 }
631 auto origInt = dyn_cast<cir::IntType>(origTy);
632 const auto *coercedAbiInt = dyn_cast<llvm::abi::IntegerType>(coercedAbiTy);
633 bool widensInt =
634 origInt && coercedAbiInt &&
635 coercedAbiInt->getSizeInBits().getFixedValue() > origInt.getWidth();
636 if (!widensInt) {
637 // FIXME: A coerce type that changes the scalar's kind or width should
638 // be handled like a wider integer. The scalar is coerced to
639 // abiTypeToCIR(coercedAbiTy), which the rewriter emits as a store of
640 // the scalar and a load of the coerce type from the same memory.
641 assert(coerceKeepsScalarValue(origTy, coercedAbiTy) &&
642 "the classifier changed a scalar's kind or width");
643 return passUnchanged();
644 }
645 }
646
647 mlir::Type coerced = abiTypeToCIR(coercedAbiTy, ctx);
648 if (!coerced)
649 return mlir::failure();
650 if (coerced == unwrapLongDoubleVectorElement(origTy)) {
651 // ArgClassification has no way to represent a coercion to the value's own
652 // type at an offset, since a coerced type equal to the value's own type
653 // is treated as no coercion. This is reported as NYI.
654 if (offset)
655 return mlir::failure();
656 // A vector the classifier passes as itself needs no rewrite.
657 if (isa<cir::VectorType>(origTy))
658 return passUnchanged();
659 }
660 // An aggregate or _Complex is unpacked into the registers the coerced type
661 // describes. A vector or scalar is reinterpreted as the coerced type.
662 return passCoerced(coerced, offset);
663}
664
665/// Convert an llvm::abi::ArgInfo into the ArgClassification consumed by
666/// CIRABIRewriteContext. Returns failure when the classifier picks a
667/// coercion this bridge cannot represent, which the caller reports as NYI.
668static mlir::FailureOr<ArgClassification>
669convertABIArgInfo(const llvm::abi::ArgInfo &info, MLIRContext *ctx,
670 mlir::Type origTy) {
671 if (info.isDirect())
672 return convertDirectArgInfo(info, ctx, origTy);
673 // An extended value is always read from byte 0 of its own storage, so
674 // there is no offset to honor here.
675 if (info.isExtend()) {
676 assert(origTy && "an extended value must have a type");
677 if (isa<cir::BoolType>(origTy))
678 return ArgClassification::getExtend(nullptr, info.isSignExt(),
679 info.isConservative());
680 assert((isa<cir::IntType, cir::RecordType>(origTy)) &&
681 "Extend is only expected for integers, bool, and transparent "
682 "unions");
683 mlir::Type extendedTy = abiTypeToCIR(info.getCoerceToType(), ctx);
684 return ArgClassification::getExtend(extendedTy, info.isSignExt(),
685 info.isConservative());
686 }
687 if (info.isIndirect())
688 return ArgClassification::getIndirect(info.getIndirectAlign(),
689 info.getIndirectByVal(),
690 info.getIndirectAddrSpace());
691 if (info.isIndirectAliased())
692 return ArgClassification::getIndirectAliased(info.getIndirectAlign(),
693 info.getIndirectAddrSpace());
694 // AArch64 pure scalable aggregates use CoerceAndExpand, but they aren't
695 // supported yet.
696 assert(!info.isCoerceAndExpand() && "CoerceAndExpand is not handled yet");
697 assert(info.isIgnore() && "Unexpected classification");
698 return ArgClassification::getIgnore();
699}
700
701/// Where \p fnTy's declared parameters end and its ellipsis arguments begin.
702static llvm::abi::RequiredArgs requiredArgs(cir::FuncType fnTy) {
703 if (!fnTy.isVarArg())
704 return llvm::abi::RequiredArgs::All;
705 return llvm::abi::RequiredArgs(fnTy.getNumInputs());
706}
707
708/// Classify a signature (return type + argument types) using the LLVM ABI
709/// library. Shared by the cir.func path, the variadic-call path and the
710/// indirect-call path (the latter classifies from the callee function
711/// pointer's pointee FuncType). \p required marks where the declared
712/// parameters in \p inputs end. The classifier treats every argument past that
713/// point as passed through an ellipsis. \p callConv is the calling convention
714/// the signature is classified under. Returns failure and emits an NYI
715/// error via \p emitError if the signature uses a type the bridge does not
716/// handle yet.
717mlir::FailureOr<FunctionClassification>
718CIRABIClassifierCommon::classifySignature(
719 mlir::Type retCIR, mlir::TypeRange inputs, llvm::abi::RequiredArgs required,
720 const llvm::abi::TargetInfo &targetInfo, llvm::CallingConv::ID callConv,
721 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) {
722 assert(retCIR && "signature return type must be non-null");
723 assert((!required.allowsOptionalArgs() ||
724 required.getNumRequiredArgs() <= inputs.size()) &&
725 "declared parameters cannot outnumber the classified arguments");
726 MLIRContext *ctx = modOp->getContext();
727 bool voidRet = isa<cir::VoidType>(retCIR);
728
729 auto reject = [&](mlir::Type t) -> bool {
730 if (isSupportedType(t, dl))
731 return false;
732 emitError() << "calling-convention lowering not yet implemented for type "
733 << t;
734 return true;
735 };
736 if (!voidRet && reject(retCIR))
737 return mlir::failure();
738 for (mlir::Type a : inputs)
739 if (reject(a))
740 return mlir::failure();
741
742 const llvm::abi::Type *retAbi =
743 voidRet ? typeMapper.getTypeBuilder().getVoidType()
745 SmallVector<const llvm::abi::Type *> argAbi;
746 for (mlir::Type a : inputs)
747 argAbi.push_back(mapCIRType(a, typeMapper, dl, cirDataLayout, modOp));
748
749 std::unique_ptr<llvm::abi::FunctionInfo> fi =
750 llvm::abi::FunctionInfo::create(callConv, retAbi, argAbi, required);
751 targetInfo.computeInfo(*fi);
752
753 // convertABIArgInfo returns failure when the classifier picks a coercion this
754 // bridge cannot represent.
755 auto nyiCoercion = [&](mlir::Type t) {
756 emitError() << "calling-convention lowering not yet "
757 "implemented for the ABI coercion of type "
758 << t;
759 };
760
761 FunctionClassification fc;
762 fc.returnsVoid = voidRet;
763 mlir::Type origRet = voidRet ? mlir::Type() : retCIR;
764 mlir::FailureOr<ArgClassification> retAc =
765 convertABIArgInfo(fi->getReturnInfo(), ctx, origRet);
766 if (failed(retAc)) {
767 nyiCoercion(retCIR);
768 return mlir::failure();
769 }
770 fc.returnInfo = *retAc;
771 for (unsigned i = 0, e = fi->arg_size(); i < e; ++i) {
772 mlir::Type origArg = inputs[i];
773 const llvm::abi::ArgInfo &argInfo = fi->getArgInfo(i).Info;
774 mlir::FailureOr<ArgClassification> ac =
775 convertABIArgInfo(argInfo, ctx, origArg);
776 if (failed(ac)) {
777 nyiCoercion(origArg);
778 return mlir::failure();
779 }
780 // The classifier passes a transparent union as its first member, and
781 // names no coerce type when it passes that member as its own type. The
782 // union is then left unchanged or coerced to itself above.
783 auto recTy = dyn_cast<cir::RecordType>(origArg);
784 if (ac->kind == ArgKind::Direct && recTy &&
785 (!ac->coercedType || ac->coercedType == recTy) &&
787 ac->coercedType = recTy.getMembers().front();
788 ac->neededIntRegs = argInfo.getNeededIntRegs();
789 ac->neededSseRegs = argInfo.getNeededSseRegs();
790 fc.argInfos.push_back(*ac);
791 }
792 return fc;
793}
794
795/// FIXME: Implement proper support for other calling conventions.
796llvm::CallingConv::ID cir::convertCallingConv(cir::CallingConv cc) {
797 if (cc == cir::CallingConv::AMDGPUKernel)
798 return llvm::CallingConv::AMDGPU_KERNEL;
799 if (cc == cir::CallingConv::SpirKernel)
800 return llvm::CallingConv::SPIR_KERNEL;
801 return llvm::CallingConv::C;
802}
803
804/// Classify a cir.func using the LLVM ABI library. Returns failure and
805/// emits an NYI error if the signature uses a type the bridge does not handle
806/// yet.
807mlir::FailureOr<FunctionClassification>
809 cir::FuncType fnTy = func.getFunctionType();
810 return classifySignature(fnTy.getReturnType(), fnTy.getInputs(),
811 requiredArgs(fnTy), getTargetInfo(func),
812 convertCallingConv(func.getCallingConv()),
813 [&]() { return func.emitOpError(); });
814}
815
816/// Classify the single type fetched by a `cir.va_arg` as an unnamed argument
817/// (RequiredArgs(0)) with a full register budget. Returns failure and
818/// emits an NYI error if the type is not one this bridge handles.
819mlir::FailureOr<ArgClassification> CIRABIClassifierCommon::classifyVarArgType(
820 mlir::Type ty, const llvm::abi::TargetInfo &targetInfo,
821 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) {
822 MLIRContext *ctx = modOp->getContext();
823 mlir::FailureOr<FunctionClassification> fc = classifySignature(
824 cir::VoidType::get(ctx), mlir::TypeRange(ty), llvm::abi::RequiredArgs(0),
825 targetInfo, llvm::CallingConv::C, emitError);
826 if (failed(fc))
827 return mlir::failure();
828 return fc->argInfos[0];
829}
830
831/// Classify a call that passes arguments through an ellipsis. The callee's
832/// own classification covers only its declared parameters, but an ellipsis
833/// argument competes for the same argument registers as a declared one, so
834/// what the ABI does with it depends on the whole argument list: the same
835/// small struct is passed in registers early in the list and in memory once
836/// the integer registers are gone. Classifying from the call's operands
837/// rather than the callee's signature is what makes that accounting right.
838mlir::FailureOr<FunctionClassification>
840 cir::CIRCallOpInterface call, cir::FuncType calleeTy,
841 const llvm::abi::TargetInfo &targetInfo, llvm::CallingConv::ID callConv) {
842 assert(calleeTy.isVarArg() &&
843 "only a variadic callee can take more operands than it declares");
844 Operation *op = call.getOperation();
845 return classifySignature(calleeTy.getReturnType(),
846 call.getArgOperands().getTypes(),
847 requiredArgs(calleeTy), targetInfo, callConv,
848 [&]() { return op->emitOpError(); });
849}
850
851mlir::FailureOr<FunctionClassification>
853 cir::FuncOp callee) {
854 return classifyVariadicCall(call, callee.getFunctionType(),
855 getTargetInfo(callee),
856 convertCallingConv(callee.getCallingConv()));
857}
858
859mlir::FailureOr<FunctionClassification>
860CIRABIClassifierCommon::classifyIndirectCall(cir::CIRCallOpInterface call) {
861 cir::FuncType funcTy = getIndirectCalleeType(call);
862 const llvm::abi::TargetInfo &targetInfo =
863 getTargetInfo(call->getParentOfType<cir::FuncOp>());
864 // An indirect callee is an ordinary function pointer, so it uses the C
865 // convention.
866 if (call.getNumArgOperands() > funcTy.getNumInputs())
867 return classifyVariadicCall(call, funcTy, targetInfo, llvm::CallingConv::C);
868 return classifySignature(
869 funcTy.getReturnType(), funcTy.getInputs(), requiredArgs(funcTy),
870 targetInfo, llvm::CallingConv::C, [&]() { return call->emitOpError(); });
871}
872
873/// Record on \p fc whether \p returnType is CIR's void. classifySignature
874/// answers this itself, but the other two drivers cannot: the test target is
875/// dialect-neutral and has no notion of CIR's void, and the
876/// classification-attr schema carries no return type at all. Both route
877/// through here so a classification always reaches needsRewrite paired with
878/// the return type it was built from.
879static mlir::FailureOr<FunctionClassification>
880withReturnVoidness(mlir::FailureOr<FunctionClassification> fc,
881 mlir::Type returnType) {
882 if (succeeded(fc))
883 fc->returnsVoid = mlir::isa<cir::VoidType>(returnType);
884 return fc;
885}
886
887/// Classify \p func using whichever driver mode is configured. Returns
888/// failure and emits an error on the function if classification fails
889/// (e.g. injection-driver mode but the function is missing the attribute,
890/// or the attribute is malformed).
891static mlir::FailureOr<FunctionClassification>
892classifyFunction(cir::FuncOp func, const DataLayout &dl,
893 cir::CallConvTarget target, StringRef classificationAttrName) {
894 ArrayRef<Type> argTypes = func.getFunctionType().getInputs();
895 Type returnType = func.getFunctionType().getReturnType();
896
897 if (!classificationAttrName.empty()) {
898 auto attr = func->getAttrOfType<DictionaryAttr>(classificationAttrName);
899 if (!attr) {
900 func.emitOpError()
901 << "missing classification attribute '" << classificationAttrName
902 << "' (CallConvLowering driver mode 'classification-attr')";
903 return mlir::failure();
904 }
905 return withReturnVoidness(mlir::abi::test::parseClassificationAttr(
906 attr, [&]() { return func.emitOpError(); }),
907 returnType);
908 }
909
910 // The x86_64 and AMDGPU targets classify through CIRABIClassifierCommon, so
911 // only the test target reaches here.
912 assert(target == cir::CallConvTarget::Test &&
913 "classifyFunction only handles the test target");
914 return withReturnVoidness(mlir::abi::test::classify(argTypes, returnType, dl),
915 returnType);
916}
917
918namespace {
919
920/// Classifies with the MLIR test ABI target: predictable rules that
921/// approximate x86_64 SysV, used by tests that need a target-independent
922/// driver.
923class TestTargetClassifier final : public CIRABIClassifier {
924public:
925 explicit TestTargetClassifier(const mlir::DataLayout &dl) : dl(dl) {}
926
927 mlir::FailureOr<FunctionClassification>
928 classifyFunction(cir::FuncOp func) final {
929 return ::classifyFunction(func, dl, cir::CallConvTarget::Test,
930 /*classificationAttrName=*/"");
931 }
932
933 /// The test target classifies only declared parameters.
934 mlir::FailureOr<FunctionClassification>
935 classifyVariadicCall(cir::CIRCallOpInterface call, cir::FuncOp) final {
936 call->emitOpError()
937 << "variadic arguments not yet implemented in CallConvLowering";
938 return mlir::failure();
939 }
940
941 mlir::FailureOr<FunctionClassification>
942 classifyIndirectCall(cir::CIRCallOpInterface call) final {
943 cir::FuncType funcTy = getIndirectCalleeType(call);
944 if (call.getNumArgOperands() > funcTy.getNumInputs()) {
945 call->emitOpError()
946 << "variadic arguments not yet implemented in CallConvLowering";
947 return mlir::failure();
948 }
949 return withReturnVoidness(mlir::abi::test::classify(funcTy.getInputs(),
950 funcTy.getReturnType(),
951 dl),
952 funcTy.getReturnType());
953 }
954
955 mlir::FailureOr<ArgClassification> classifyVAArg(cir::VAArgOp vaArg) final {
956 vaArg->emitOpError()
957 << "not yet implemented in CallConvLowering for the test target";
958 return mlir::failure();
959 }
960
961private:
962 const mlir::DataLayout &dl;
963};
964
965/// Reads a pre-built classification from a function attribute, so a test can
966/// inject any classification (including shapes no target produces) without
967/// depending on a real ABI target.
968class InjectedClassifier final : public CIRABIClassifier {
969public:
970 InjectedClassifier(const mlir::DataLayout &dl, llvm::StringRef attrName)
971 : dl(dl), attrName(attrName) {}
972
973 mlir::FailureOr<FunctionClassification>
974 classifyFunction(cir::FuncOp func) final {
975 return ::classifyFunction(func, dl, cir::CallConvTarget::None, attrName);
976 }
977
978 /// The injected classification covers a function's declared parameters, so
979 /// it cannot describe an operand passed through an ellipsis.
980 mlir::FailureOr<FunctionClassification>
981 classifyVariadicCall(cir::CIRCallOpInterface call, cir::FuncOp) final {
982 call->emitOpError()
983 << "variadic arguments not yet implemented in CallConvLowering";
984 return mlir::failure();
985 }
986
987 /// Nor can it describe a callee resolved at run time, which names no
988 /// function to read the attribute from.
989 mlir::FailureOr<FunctionClassification>
990 classifyIndirectCall(cir::CIRCallOpInterface call) final {
991 call->emitOpError() << "indirect call cannot be classified in the "
992 "'classification-attr' driver mode";
993 return mlir::failure();
994 }
995
996 mlir::FailureOr<ArgClassification> classifyVAArg(cir::VAArgOp vaArg) final {
997 vaArg->emitOpError() << "cannot be classified in the "
998 "'classification-attr' driver mode";
999 return mlir::failure();
1000 }
1001
1002private:
1003 const mlir::DataLayout &dl;
1004 std::string attrName;
1005};
1006
1007} // namespace
1008
1009std::unique_ptr<CIRABIClassifier>
1010cir::createTestTargetABIClassifier(const mlir::DataLayout &dl) {
1011 return std::make_unique<TestTargetClassifier>(dl);
1012}
1013
1014std::unique_ptr<CIRABIClassifier>
1015cir::createInjectedABIClassifier(const mlir::DataLayout &dl,
1016 llvm::StringRef attrName) {
1017 return std::make_unique<InjectedClassifier>(dl, attrName);
1018}
static bool recordHasFlexibleArrayMember(ModuleOp modOp, cir::RecordType recTy)
Read from the layout, which also covers a last field that has one.
static llvm::Align recordUnadjustedAlign(ModuleOp modOp, cir::RecordType recTy, const cir::CIRDataLayout &cirDL)
A record's unadjusted alignment, the alignment its members give it before an alignment attribute on t...
static bool recordIsTransparentUnion(ModuleOp modOp, cir::RecordType recTy)
static bool memberIsEmptyRecord(mlir::Type ty)
Whether a member is an empty record, looking through arrays, since an array of empty records supplies...
static bool recordCanPassInRegs(ModuleOp modOp, cir::RecordType recTy)
Whether a struct's declared argument-passing kind (from the module's record-layout metadata) allows i...
static mlir::FailureOr< ArgClassification > convertABIArgInfo(const llvm::abi::ArgInfo &info, MLIRContext *ctx, mlir::Type origTy)
Convert an llvm::abi::ArgInfo into the ArgClassification consumed by CIRABIRewriteContext.
static mlir::FailureOr< FunctionClassification > withReturnVoidness(mlir::FailureOr< FunctionClassification > fc, mlir::Type returnType)
Record on fc whether returnType is CIR's void.
static mlir::Type unwrapLongDoubleVectorElement(mlir::Type ty)
Returns ty with a LongDoubleType vector element replaced by its underlying format,...
static bool mayReachSseUp(mlir::Type ty, const DataLayout &dl)
Whether the classifier could give this type the SSEUP class, looking through arrays and records at th...
static llvm::abi::RequiredArgs requiredArgs(cir::FuncType fnTy)
Where fnTy's declared parameters end and its ellipsis arguments begin.
static bool coerceKeepsScalarValue(mlir::Type origTy, const llvm::abi::Type *coercedAbiTy)
Whether coercedAbiTy holds the same value as the scalar origTy: an integer of the same width,...
static mlir::FailureOr< FunctionClassification > classifyFunction(cir::FuncOp func, const DataLayout &dl, cir::CallConvTarget target, StringRef classificationAttrName)
Classify func using whichever driver mode is configured.
static mlir::FailureOr< ArgClassification > convertDirectArgInfo(const llvm::abi::ArgInfo &info, MLIRContext *ctx, mlir::Type origTy)
Convert a Direct llvm::abi::ArgInfo.
static bool sseUpCoerceSizeUnsupported(uint64_t recordBits, llvm::ArrayRef< mlir::Type > members, const DataLayout &dl)
Whether the record's size has no SSEUP coerce.
static bool isSupportedType(mlir::Type ty, const DataLayout &dl)
The CIR types the bridge handles.
static const llvm::abi::Type * mapCIRType(mlir::Type type, mlir::abi::ABITypeMapper &typeMapper, const DataLayout &dl, const cir::CIRDataLayout &cirDL, ModuleOp modOp)
Map a CIR type to an llvm::abi::Type.
static mlir::Type abiTypeToCIR(const llvm::abi::Type *ty, MLIRContext *ctx)
Convert an llvm::abi::Type coercion type back to a CIR type.
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
cir::CIRDataLayout cirDataLayout
mlir::FailureOr< mlir::abi::FunctionClassification > classifyIndirectCall(cir::CIRCallOpInterface call) override
A callee resolved at run time carries no features of its own, so the call is classified at the featur...
mlir::FailureOr< mlir::abi::FunctionClassification > classifyFunction(cir::FuncOp func) override
Classify a cir.func using the LLVM ABI library.
const mlir::DataLayout & dl
mlir::FailureOr< mlir::abi::ArgClassification > classifyVarArgType(mlir::Type ty, const llvm::abi::TargetInfo &targetInfo, llvm::function_ref< mlir::InFlightDiagnostic()> emitError)
Classify ty, the type fetched by a cir.va_arg, as an unnamed argument with every argument register fr...
mlir::FailureOr< mlir::abi::FunctionClassification > classifyVariadicCall(cir::CIRCallOpInterface call, cir::FuncOp callee) override
The call is classified at the callee's features, not the caller's, because the pass rewrites the defi...
virtual const llvm::abi::TargetInfo & getTargetInfo(cir::FuncOp featureSource)=0
The library classifier for a function whose recorded target features may refine the ABI rules.
mlir::abi::ABITypeMapper typeMapper
Produces the classification CallConvLowering rewrites a signature from.
uint64_t getTypeLanguageAlignment(mlir::Type ty) const
Returns the alignment, in bytes, that the source language requires for an object of type ty.
C++ view class that accepts both !cir.struct and !cir.union types.
Definition CIRTypes.h:153
bool isUnion() const
Definition CIRTypes.h:179
bool isEmptyForABI() const
Whether no member holds data.
Definition CIRTypes.cpp:745
llvm::ArrayRef< mlir::Type > getMembers() const
Definition CIRTypes.cpp:652
static llvm::SmallVector< RecordMemberKind > getAllDataKinds(llvm::ArrayRef< mlir::Type > members)
One Data kind per member.
Definition CIRTypes.cpp:155
mlir::StringAttr getName() const
Definition CIRTypes.cpp:657
llvm::ArrayRef< RecordMemberKind > getMemberKinds() const
Definition CIRTypes.cpp:677
uint64_t getElementOffset(const mlir::DataLayout &dataLayout, unsigned idx) const
Definition CIRTypes.cpp:710
RecordLayoutAttr tryGetRecordLayout(mlir::ModuleOp mod, mlir::StringAttr name)
Same lookup as getRecordLayout, but returns a null attribute instead of asserting when the record has...
llvm::CallingConv::ID convertCallingConv(cir::CallingConv cc)
Map a CIR calling convention to the llvm::CallingConv the ABI classifier uses.
cir::FPTypeInterface getFloatingPointType(const llvm::fltSemantics &sem, mlir::MLIRContext *ctx)
Returns the CIR floating-point type for the given semantics, or a null type if CIR has no type for it...
Definition CIRTypes.cpp:47
cir::FuncType getIndirectCalleeType(cir::CIRCallOpInterface call)
The signature the indirect call call reaches its callee through.
std::unique_ptr< CIRABIClassifier > createInjectedABIClassifier(const mlir::DataLayout &dl, llvm::StringRef attrName)
A classifier that reads each function's classification from the DictionaryAttr named attrName.
std::unique_ptr< CIRABIClassifier > createTestTargetABIClassifier(const mlir::DataLayout &dl)
The MLIR test ABI target's classifier, whose predictable rules approximate x86_64 SysV.
CallConvTarget
The ABI target whose calling-convention rules drive CallConvLowering.
Definition Passes.h:23
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
static bool addressSpace()