clang 24.0.0git
CIRTypes.cpp
Go to the documentation of this file.
1//===- CIRTypes.cpp - MLIR CIR Types --------------------------------------===//
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 defines the types in the CIR dialect.
10//
11//===----------------------------------------------------------------------===//
12
14
15#include "mlir/Dialect/Ptr/IR/MemorySpaceInterfaces.h"
16#include "mlir/IR/BuiltinAttributes.h"
17#include "mlir/IR/DialectImplementation.h"
18#include "mlir/IR/MLIRContext.h"
19#include "mlir/Support/LLVM.h"
26#include "llvm/ADT/APFloat.h"
27#include "llvm/ADT/APInt.h"
28#include "llvm/ADT/APSInt.h"
29#include "llvm/Support/MathExtras.h"
30
31#include "CIROpDefinitions.h"
32
33//===----------------------------------------------------------------------===//
34// CIR Helpers
35//===----------------------------------------------------------------------===//
36bool cir::isSized(mlir::Type ty) {
37 if (auto sizedTy = mlir::dyn_cast<cir::SizedTypeInterface>(ty))
38 return sizedTy.isSized();
40 return false;
41}
42
43cir::FPTypeInterface cir::getFloatingPointType(const llvm::fltSemantics &sem,
44 mlir::MLIRContext *ctx) {
45 switch (llvm::APFloat::SemanticsToEnum(sem)) {
46 case llvm::APFloat::S_IEEEhalf:
47 return cir::FP16Type::get(ctx);
48 case llvm::APFloat::S_BFloat:
49 return cir::BF16Type::get(ctx);
50 case llvm::APFloat::S_IEEEsingle:
51 return cir::SingleType::get(ctx);
52 case llvm::APFloat::S_IEEEdouble:
53 return cir::DoubleType::get(ctx);
54 case llvm::APFloat::S_x87DoubleExtended:
55 return cir::FP80Type::get(ctx);
56 case llvm::APFloat::S_IEEEquad:
57 return cir::FP128Type::get(ctx);
58 default:
59 // CIR has no type for the remaining semantics (PPCDoubleDouble, the
60 // Float8 formats). Return null and let the caller report it.
61 return {};
62 }
63}
64
65//===----------------------------------------------------------------------===//
66// CIR Custom Parser/Printer Signatures
67//===----------------------------------------------------------------------===//
68
69static mlir::ParseResult
70parseFuncTypeParams(mlir::AsmParser &p, llvm::SmallVector<mlir::Type> &params,
71 bool &isVarArg);
72static void printFuncTypeParams(mlir::AsmPrinter &p,
73 mlir::ArrayRef<mlir::Type> params,
74 bool isVarArg);
75//===----------------------------------------------------------------------===//
76// CIR Custom Parser/Printer Signatures
77//===----------------------------------------------------------------------===//
78
79static mlir::ParseResult
80parseFuncTypeParams(mlir::AsmParser &p, llvm::SmallVector<mlir::Type> &params,
81 bool &isVarArg);
82
83static void printFuncTypeParams(mlir::AsmPrinter &p,
84 mlir::ArrayRef<mlir::Type> params,
85 bool isVarArg);
86
87//===----------------------------------------------------------------------===//
88// AddressSpace
89//===----------------------------------------------------------------------===//
90
91// Spells the address space of `!cir.ptr` and `cir.global` as either
92// `lang_address_space(x)` or `target_address_space(n)`.
93mlir::ParseResult parseMemorySpace(mlir::AsmParser &p,
94 mlir::ptr::MemorySpaceAttrInterface &attr);
95
96void printMemorySpace(mlir::AsmPrinter &printer,
97 mlir::ptr::MemorySpaceAttrInterface attr);
98
99//===----------------------------------------------------------------------===//
100// Get autogenerated stuff
101//===----------------------------------------------------------------------===//
102
103namespace cir {
104
105#include "clang/CIR/Dialect/IR/CIRTypeConstraints.cpp.inc"
106
107} // namespace cir
108
109#define GET_TYPEDEF_CLASSES
110#include "clang/CIR/Dialect/IR/CIROpsTypes.cpp.inc"
111
112using namespace mlir;
113using namespace cir;
114
115//===----------------------------------------------------------------------===//
116// General CIR parsing / printing
117//===----------------------------------------------------------------------===//
118
119Type CIRDialect::parseType(DialectAsmParser &parser) const {
120 llvm::SMLoc typeLoc = parser.getCurrentLocation();
121 llvm::StringRef mnemonic;
122 Type genType;
123
124 // Try to parse as a tablegen'd type.
125 OptionalParseResult parseResult =
126 generatedTypeParser(parser, &mnemonic, genType);
127 if (parseResult.has_value())
128 return genType;
129
130 // All CIR types are now tablegen'd; nothing left to dispatch here.
131 parser.emitError(typeLoc) << "unknown CIR type: " << mnemonic;
132 return Type();
133}
134
135void CIRDialect::printType(Type type, DialectAsmPrinter &os) const {
136 // Try to print as a tablegen'd type.
137 if (generatedTypePrinter(type, os).succeeded())
138 return;
139
140 // TODO(CIR) Attempt to print as a raw C++ type.
141 llvm::report_fatal_error("printer is missing a handler for this type");
142}
143
144//===----------------------------------------------------------------------===//
145// StructType
146//===----------------------------------------------------------------------===//
147
148// Shared helpers for StructType and UnionType parse/print.
149
152 return llvm::SmallVector<RecordMemberKind>(members.size(),
153 RecordMemberKind::Data);
154}
155
156/// An incomplete record has no members, so a kind for one is caught by the
157/// same check.
158static mlir::LogicalResult
159verifyRecordMemberKinds(function_ref<mlir::InFlightDiagnostic()> emitError,
160 size_t numMembers,
162 if (memberKinds.size() != numMembers)
163 return emitError() << "expected " << numMembers << " member kinds, got "
164 << memberKinds.size();
165 return mlir::success();
166}
167
168/// Members must be CIR types other than void, which has no layout.
169static mlir::LogicalResult
170verifyRecordMemberTypes(function_ref<mlir::InFlightDiagnostic()> emitError,
172 for (auto [idx, memberTy] : llvm::enumerate(members)) {
173 if (!cir::isCIRType(memberTy))
174 return emitError() << "record member at index " << idx
175 << " must be a CIR type, got " << memberTy;
176 if (mlir::isa<cir::VoidType>(memberTy))
177 return emitError() << "record member at index " << idx
178 << " cannot be void";
179 }
180 return mlir::success();
181}
182
183/// The keywords that spell a member kind. A union's tail-padding slot probes
184/// for one of these to reject it, since that slot is not a member.
185static const llvm::StringRef memberKindMarks[] = {"data", "pad", "empty",
186 "bitfield"};
187
188static std::optional<RecordMemberKind>
189parseMemberKind(mlir::AsmParser &parser) {
190 llvm::StringRef keyword;
191 const llvm::SMLoc loc = parser.getCurrentLocation();
192 if (parser.parseKeyword(&keyword).failed())
193 return std::nullopt;
194 std::optional<RecordMemberKind> kind = symbolizeRecordMemberKind(keyword);
195 if (!kind)
196 parser.emitError(loc, "expected a record member kind");
197 return kind;
198}
199
200/// Parse "incomplete" or "{mark type, mark type, ...}", writing results into
201/// \p incomplete, \p members and \p memberKinds. Returns failure if member
202/// parsing fails.
203static mlir::ParseResult
204parseRecordBody(mlir::AsmParser &parser, bool &incomplete,
207 assert(incomplete && "caller must pre-initialize incomplete to true");
208 if (parser.parseOptionalKeyword("incomplete").succeeded())
209 return mlir::success();
210 incomplete = false;
211 return parser.parseCommaSeparatedList(
212 AsmParser::Delimiter::Braces,
213 [&parser, &members, &memberKinds]() -> mlir::ParseResult {
214 std::optional<RecordMemberKind> kind = parseMemberKind(parser);
215 if (!kind)
216 return mlir::failure();
217 memberKinds.push_back(*kind);
218 return parser.parseType(members.emplace_back());
219 });
220}
221
222/// Print a complete CIR record body:
223/// '<' ['class '] [name] ['packed '] body '>'
224/// where body is "incomplete" or "{[mark] members}[, padding = {type}]".
225/// RecordTy must be a mutable MLIR type (StructType or UnionType).
226template <typename RecordTy>
227static void
228printRecordBody(mlir::AsmPrinter &printer, RecordTy self, mlir::StringAttr name,
229 bool hasClassPrefix, bool isPacked, bool isIncomplete,
230 llvm::ArrayRef<mlir::Type> members, mlir::Type padding,
232 printer << '<';
233 if (hasClassPrefix)
234 printer << "class ";
235 if (name)
236 printer << name;
237
238 FailureOr<AsmPrinter::CyclicPrintReset> cyclicPrintGuard =
239 printer.tryStartCyclicPrint(self);
240 if (failed(cyclicPrintGuard)) {
241 printer << '>';
242 return;
243 }
244
245 if (hasClassPrefix || name)
246 printer << ' ';
247 if (isPacked)
248 printer << "packed ";
249 if (isIncomplete) {
250 printer << "incomplete";
251 } else {
252 printer << "{";
253 for (auto [idx, member] : llvm::enumerate(members)) {
254 if (idx)
255 printer << ", ";
256 printer << stringifyRecordMemberKind(memberKinds[idx]) << ' ';
257 printer.printType(member);
258 }
259 printer << "}";
260 if (padding) {
261 printer << ", padding = {";
262 printer.printType(padding);
263 printer << '}';
264 }
265 }
266 printer << '>';
267}
268
269/// Parse the body of a !cir.struct<...> type.
270Type StructType::parse(mlir::AsmParser &parser) {
271 FailureOr<AsmParser::CyclicParseReset> cyclicParseGuard;
272 const llvm::SMLoc loc = parser.getCurrentLocation();
273 const mlir::Location eLoc = parser.getEncodedSourceLoc(loc);
274 bool packed = false;
275 mlir::MLIRContext *context = parser.getContext();
276
277 if (parser.parseLess())
278 return {};
279
280 // An optional "class" keyword distinguishes class from struct.
281 bool is_class = parser.parseOptionalKeyword("class").succeeded();
282
283 mlir::StringAttr name;
284 parser.parseOptionalAttribute(name);
285
286 // Self-reference: ensure the referenced type was already parsed.
287 if (name && parser.parseOptionalGreater().succeeded()) {
288 StructType type = StructType::getChecked(eLoc, context, name, is_class);
289 if (succeeded(parser.tryStartCyclicParse(type))) {
290 parser.emitError(loc, "invalid self-reference within record");
291 return {};
292 }
293 return type;
294 }
295
296 // Named definition: ensure name has not been parsed yet.
297 if (name) {
298 StructType type = StructType::getChecked(eLoc, context, name, is_class);
299 cyclicParseGuard = parser.tryStartCyclicParse(type);
300 if (failed(cyclicParseGuard)) {
301 parser.emitError(loc, "record already defined");
302 return {};
303 }
304 }
305
306 if (parser.parseOptionalKeyword("packed").succeeded())
307 packed = true;
308
309 bool incomplete = true;
310 llvm::SmallVector<mlir::Type> members;
311 llvm::SmallVector<RecordMemberKind> memberKinds;
312 if (parseRecordBody(parser, incomplete, members, memberKinds).failed())
313 return {};
314
315 if (parser.parseGreater())
316 return {};
317
318 ArrayRef<mlir::Type> membersRef(members);
319 ArrayRef<RecordMemberKind> kindsRef(memberKinds);
320 mlir::Type type = {};
321 if (name && incomplete) {
322 type = StructType::getChecked(eLoc, context, name, is_class);
323 } else if (!name && !incomplete) {
324 type = StructType::getChecked(eLoc, context, membersRef, packed, is_class,
325 kindsRef);
326 if (!type)
327 return {};
328 } else if (!incomplete) {
329 type = StructType::getChecked(eLoc, context, membersRef, name, packed,
330 is_class, kindsRef);
331 if (!type)
332 return {};
333 if (auto structTy = mlir::dyn_cast<StructType>(type)) {
334 if (failed(structTy.mutate(membersRef, packed, kindsRef))) {
335 parser.emitError(loc, "record '")
336 << name.getValue() << "' redefined with a different body";
337 return {};
338 }
339 }
341 } else {
342 parser.emitError(loc, "anonymous records must be complete");
343 return {};
344 }
345
346 return type;
347}
348
349void StructType::print(mlir::AsmPrinter &printer) const {
350 printRecordBody(printer, *this, getName(), isClass(), getPacked(),
351 isIncomplete(), getMembers(), /*padding=*/{},
352 getMemberKinds());
353}
354
355mlir::LogicalResult StructType::verify(
356 function_ref<mlir::InFlightDiagnostic()> emitError,
357 llvm::ArrayRef<mlir::Type> members, mlir::StringAttr name, bool incomplete,
358 bool packed, llvm::ArrayRef<RecordMemberKind> member_kinds, bool is_class) {
359 if (name && name.getValue().empty())
360 return emitError() << "identified records cannot have an empty name";
361 if (failed(verifyRecordMemberTypes(emitError, members)))
362 return mlir::failure();
363 return verifyRecordMemberKinds(emitError, members.size(), member_kinds);
364}
365
366// Accessors are hand-written because genStorageClass = 0 suppresses generated
367// implementations.
368llvm::ArrayRef<mlir::Type> StructType::getMembers() const {
369 return getImpl()->members;
370}
371mlir::StringAttr StructType::getName() const { return getImpl()->name; }
372bool StructType::isIncomplete() const { return getImpl()->incomplete; }
373bool StructType::getIncomplete() const { return getImpl()->incomplete; }
374bool StructType::getPacked() const { return getImpl()->packed; }
375llvm::ArrayRef<RecordMemberKind> StructType::getMemberKinds() const {
376 return getImpl()->member_kinds;
377}
378bool StructType::getIsClass() const { return getImpl()->is_class; }
379
380bool StructType::getPadded() const {
381 return llvm::is_contained(getMemberKinds(), RecordMemberKind::Pad);
382}
383
384bool StructType::isABIConvertedRecord() const {
385 return getName() && getName().getValue().starts_with(abi_conversion_prefix);
386}
387
388mlir::StringAttr StructType::getABIConvertedName() const {
389 assert(!isABIConvertedRecord());
390 return StringAttr::get(getContext(),
391 abi_conversion_prefix + getName().getValue());
392}
393
394void StructType::removeABIConversionNamePrefix() {
395 mlir::StringAttr recordName = getName();
396 if (recordName && recordName.getValue().starts_with(abi_conversion_prefix))
397 getImpl()->name = mlir::StringAttr::get(
398 recordName.getValue().drop_front(sizeof(abi_conversion_prefix) - 1),
399 recordName.getType());
400}
401
402void StructType::complete(ArrayRef<Type> members, bool packed,
403 ArrayRef<RecordMemberKind> memberKinds) {
405 // mutate() bypasses the verifier, so check what get() would have checked.
406 assert(
407 succeeded(verifyInvariants(
408 mlir::detail::getDefaultDiagnosticEmitFn(getContext()), members,
409 getName(), /*incomplete=*/false, packed, memberKinds, isClass())) &&
410 "invalid struct completion");
411 if (mutate(members, packed, memberKinds).failed())
412 llvm_unreachable("failed to complete struct");
413}
414
415bool StructType::isLayoutIdentical(const StructType &other) {
416 if (getImpl() == other.getImpl())
417 return true;
418 if (getPacked() != other.getPacked())
419 return false;
420 return getMembers() == other.getMembers();
421}
422
423//===----------------------------------------------------------------------===//
424// UnionType
425//===----------------------------------------------------------------------===//
426
427Type UnionType::parse(mlir::AsmParser &parser) {
428 FailureOr<AsmParser::CyclicParseReset> cyclicParseGuard;
429 const llvm::SMLoc loc = parser.getCurrentLocation();
430 const mlir::Location eLoc = parser.getEncodedSourceLoc(loc);
431 bool packed = false;
432 mlir::Type padding;
433 mlir::MLIRContext *context = parser.getContext();
434
435 if (parser.parseLess())
436 return {};
437
438 mlir::StringAttr name;
439 parser.parseOptionalAttribute(name);
440
441 // Self-reference.
442 if (name && parser.parseOptionalGreater().succeeded()) {
443 UnionType type = UnionType::getChecked(eLoc, context, name);
444 if (succeeded(parser.tryStartCyclicParse(type))) {
445 parser.emitError(loc, "invalid self-reference within record");
446 return {};
447 }
448 return type;
449 }
450
451 // Named definition.
452 if (name) {
453 UnionType type = UnionType::getChecked(eLoc, context, name);
454 cyclicParseGuard = parser.tryStartCyclicParse(type);
455 if (failed(cyclicParseGuard)) {
456 parser.emitError(loc, "record already defined");
457 return {};
458 }
459 }
460
461 if (parser.parseOptionalKeyword("packed").succeeded())
462 packed = true;
463
464 bool incomplete = true;
465 llvm::SmallVector<mlir::Type> members;
466 llvm::SmallVector<RecordMemberKind> memberKinds;
467 if (parseRecordBody(parser, incomplete, members, memberKinds).failed())
468 return {};
469
470 // Optional tail-padding slot: ", padding = { <type> }". It is not a variant
471 // and so takes no mark.
472 if (!incomplete && parser.parseOptionalComma().succeeded()) {
473 if (parser.parseKeyword("padding").failed())
474 return {};
475 if (parser.parseEqual().failed())
476 return {};
477 if (parser.parseLBrace().failed())
478 return {};
479 const llvm::SMLoc paddingLoc = parser.getCurrentLocation();
480 llvm::StringRef paddingKeyword;
481 if (parser.parseOptionalKeyword(&paddingKeyword, memberKindMarks)
482 .succeeded()) {
483 parser.emitError(paddingLoc, "a union's tail padding takes no kind mark");
484 return {};
485 }
486 if (parser.parseType(padding).failed())
487 return {};
488 if (parser.parseRBrace().failed())
489 return {};
490 }
491
492 if (parser.parseGreater())
493 return {};
494
495 ArrayRef<mlir::Type> membersRef(members);
496 ArrayRef<RecordMemberKind> kindsRef(memberKinds);
497 mlir::Type type = {};
498 if (name && incomplete) {
499 type = UnionType::getChecked(eLoc, context, name);
500 } else if (!name && !incomplete) {
501 type = UnionType::getChecked(eLoc, context, membersRef, packed, padding,
502 kindsRef);
503 if (!type)
504 return {};
505 } else if (!incomplete) {
506 type = UnionType::getChecked(eLoc, context, membersRef, name, packed,
507 padding, kindsRef);
508 if (!type)
509 return {};
510 if (auto unionTy = mlir::dyn_cast<UnionType>(type)) {
511 if (failed(unionTy.mutate(membersRef, packed, padding, kindsRef))) {
512 parser.emitError(loc, "record '")
513 << name.getValue() << "' redefined with a different body";
514 return {};
515 }
516 }
518 } else {
519 parser.emitError(loc, "anonymous records must be complete");
520 return {};
521 }
522
523 return type;
524}
525
526void UnionType::print(mlir::AsmPrinter &printer) const {
527 printRecordBody(printer, *this, getName(), /*hasClassPrefix=*/false,
528 getPacked(), isIncomplete(), getMembers(), getPadding(),
529 getMemberKinds());
530}
531
532mlir::LogicalResult
533UnionType::verify(function_ref<mlir::InFlightDiagnostic()> emitError,
534 llvm::ArrayRef<mlir::Type> members, mlir::StringAttr name,
535 bool incomplete, bool packed, mlir::Type padding,
536 llvm::ArrayRef<RecordMemberKind> member_kinds) {
537 if (name && name.getValue().empty())
538 return emitError() << "identified records cannot have an empty name";
539 // A union's variants all start at offset zero, so there is no inter-member
540 // padding for a pad mark to describe. Its tail padding lives in the separate
541 // padding slot.
542 if (llvm::is_contained(member_kinds, RecordMemberKind::Pad))
543 return emitError() << "a union member cannot be marked pad";
544 if (failed(verifyRecordMemberTypes(emitError, members)))
545 return mlir::failure();
546 // CIRGen pads a union's tail with a char or an array of chars.
547 if (padding) {
548 mlir::Type charTy = padding;
549 if (auto arrTy = mlir::dyn_cast<cir::ArrayType>(padding))
550 charTy = arrTy.getElementType();
551 auto intTy = mlir::dyn_cast<cir::IntType>(charTy);
552 if (!intTy || intTy.getWidth() != 8 || intTy.isSigned() || intTy.isBitInt())
553 return emitError()
554 << "union padding must be !u8i or an array of !u8i, got "
555 << padding;
556 }
557 // Every variant starts at offset zero, so a bit-field variant is an access
558 // unit of its own. There is no run for a zero-width bit-field to end, so a
559 // variant always has storage.
560 for (auto [idx, memberTy] : llvm::enumerate(members))
561 if (auto bfTy = mlir::dyn_cast<cir::BitFieldType>(memberTy);
562 bfTy && !bfTy.ownsBytes())
563 return emitError() << "union bit-field member at index " << idx
564 << " must own its access unit storage";
565 return verifyRecordMemberKinds(emitError, members.size(), member_kinds);
566}
567
568// Accessors.
569llvm::ArrayRef<mlir::Type> UnionType::getMembers() const {
570 return getImpl()->members;
571}
572mlir::StringAttr UnionType::getName() const { return getImpl()->name; }
573bool UnionType::isIncomplete() const { return getImpl()->incomplete; }
574bool UnionType::getIncomplete() const { return getImpl()->incomplete; }
575bool UnionType::getPacked() const { return getImpl()->packed; }
576bool UnionType::getPadded() const { return getPadding() ? true : false; }
577mlir::Type UnionType::getPadding() const { return getImpl()->padding; }
578llvm::ArrayRef<RecordMemberKind> UnionType::getMemberKinds() const {
579 return getImpl()->member_kinds;
580}
581
582bool UnionType::isABIConvertedRecord() const {
583 return getName() && getName().getValue().starts_with(abi_conversion_prefix);
584}
585
586mlir::StringAttr UnionType::getABIConvertedName() const {
587 assert(!isABIConvertedRecord());
588 return StringAttr::get(getContext(),
589 abi_conversion_prefix + getName().getValue());
590}
591
592void UnionType::removeABIConversionNamePrefix() {
593 mlir::StringAttr recordName = getName();
594 if (recordName && recordName.getValue().starts_with(abi_conversion_prefix))
595 getImpl()->name = mlir::StringAttr::get(
596 recordName.getValue().drop_front(sizeof(abi_conversion_prefix) - 1),
597 recordName.getType());
598}
599
600void UnionType::complete(ArrayRef<Type> members, bool packed,
601 mlir::Type padding,
602 ArrayRef<RecordMemberKind> memberKinds) {
604 // mutate() bypasses the verifier, so check what get() would have checked.
605 assert(succeeded(verifyInvariants(
606 mlir::detail::getDefaultDiagnosticEmitFn(getContext()), members,
607 getName(), /*incomplete=*/false, packed, padding, memberKinds)) &&
608 "invalid union completion");
609 if (mutate(members, packed, padding, memberKinds).failed())
610 llvm_unreachable("failed to complete union");
611}
612
613mlir::Type
614UnionType::getUnionStorageType(const mlir::DataLayout &dataLayout) const {
615 return getUnionStorageType(dataLayout, getMembers());
616}
617
618mlir::Type UnionType::getUnionStorageType(const mlir::DataLayout &dataLayout,
619 llvm::ArrayRef<mlir::Type> members) {
620 if (members.empty())
621 return {};
622 mlir::Type largest = *std::max_element(
623 members.begin(), members.end(), [&](mlir::Type lhs, mlir::Type rhs) {
624 return dataLayout.getTypeABIAlignment(lhs) <
625 dataLayout.getTypeABIAlignment(rhs) ||
626 (dataLayout.getTypeABIAlignment(lhs) ==
627 dataLayout.getTypeABIAlignment(rhs) &&
628 dataLayout.getTypeAllocSize(lhs) <
629 dataLayout.getTypeAllocSize(rhs));
630 });
631 // A union's storage is bytes, and stands in for every variant rather than
632 // for the one bit-field that happened to be widest, so a bit-field variant
633 // contributes its access unit rather than itself.
634 return memberStorageType(largest);
635}
636
637bool UnionType::isLayoutIdentical(const UnionType &other) {
638 if (getImpl() == other.getImpl())
639 return true;
640 return getMembers() == other.getMembers() &&
641 getPadding() == other.getPadding();
642}
643
644//===----------------------------------------------------------------------===//
645// RecordType view-class method implementations
646//===----------------------------------------------------------------------===//
647
649 if (auto s = mlir::dyn_cast<StructType>(*this))
650 return s.getMembers();
651 return mlir::cast<UnionType>(*this).getMembers();
652}
653mlir::StringAttr RecordType::getName() const {
654 if (auto s = mlir::dyn_cast<StructType>(*this))
655 return s.getName();
656 return mlir::cast<UnionType>(*this).getName();
657}
659 if (auto s = mlir::dyn_cast<StructType>(*this))
660 return s.isIncomplete();
661 return mlir::cast<UnionType>(*this).isIncomplete();
662}
664 if (auto s = mlir::dyn_cast<StructType>(*this))
665 return s.getPacked();
666 return mlir::cast<UnionType>(*this).getPacked();
667}
669 if (auto s = mlir::dyn_cast<StructType>(*this))
670 return s.getPadded();
671 return mlir::cast<UnionType>(*this).getPadded();
672}
674 if (auto s = mlir::dyn_cast<StructType>(*this))
675 return s.getMemberKinds();
676 return mlir::cast<UnionType>(*this).getMemberKinds();
677}
679 if (auto s = mlir::dyn_cast<StructType>(*this))
680 return s.isClass();
681 return false;
682}
684 if (auto s = mlir::dyn_cast<StructType>(*this))
685 return s.isStruct();
686 return false;
687}
688std::string RecordType::getKindAsStr() const {
689 if (mlir::isa<UnionType>(*this))
690 return "union";
691 return mlir::cast<StructType>(*this).getKindAsStr();
692}
693std::string RecordType::getPrefixedName() const {
694 return getKindAsStr() + "." + getName().getValue().str();
695}
696void RecordType::complete(ArrayRef<Type> members, bool packed,
697 mlir::Type padding,
698 ArrayRef<RecordMemberKind> memberKinds) {
699 if (auto s = mlir::dyn_cast<StructType>(*this)) {
700 assert(!padding && "only a union takes a separate padding slot");
701 return s.complete(members, packed, memberKinds);
702 }
703 return mlir::cast<UnionType>(*this).complete(members, packed, padding,
704 memberKinds);
705}
706uint64_t RecordType::getElementOffset(const mlir::DataLayout &dataLayout,
707 unsigned idx) const {
708 if (mlir::isa<UnionType>(*this))
709 return 0;
710 return mlir::cast<StructType>(*this).getElementOffset(dataLayout, idx);
711}
713 if (auto s = mlir::dyn_cast<StructType>(*this)) {
714 if (auto so = mlir::dyn_cast<StructType>(other))
715 return s.isLayoutIdentical(so);
716 return false;
717 }
718 if (auto u = mlir::dyn_cast<UnionType>(*this)) {
719 if (auto uo = mlir::dyn_cast<UnionType>(other))
720 return u.isLayoutIdentical(uo);
721 return false;
722 }
723 return false;
724}
726 if (auto s = mlir::dyn_cast<StructType>(*this))
727 return s.isABIConvertedRecord();
728 return mlir::cast<UnionType>(*this).isABIConvertedRecord();
729}
730mlir::StringAttr RecordType::getABIConvertedName() const {
731 if (auto s = mlir::dyn_cast<StructType>(*this))
732 return s.getABIConvertedName();
733 return mlir::cast<UnionType>(*this).getABIConvertedName();
734}
736 if (auto s = mlir::dyn_cast<StructType>(*this))
737 return s.removeABIConversionNamePrefix();
738 return mlir::cast<UnionType>(*this).removeABIConversionNamePrefix();
739}
740
742 // An incomplete record has no members yet, which must not read as vacuously
743 // holding no data.
744 if (isIncomplete())
745 return false;
747 return false;
748 // An access unit of nothing but unnamed bit-fields is marked `empty`, since
749 // no field of the source reads it, but it is still storage that holds data
750 // for the ABI. This has to answer the way CIRGen's isEmptyFieldForABI does,
751 // which is where that rule lives.
752 return llvm::none_of(getMembers(), [](mlir::Type memberTy) {
753 auto bfTy = mlir::dyn_cast<cir::BitFieldType>(memberTy);
754 return bfTy && bfTy.ownsBytes();
755 });
756}
757
758//===----------------------------------------------------------------------===//
759// Data Layout information for types
760//===----------------------------------------------------------------------===//
761
762// The cir.ptr data-layout entry holds a #cir.ptr_spec attribute (see
763// cir::setMLIRDataLayout).
764namespace {
765constexpr static uint64_t kBitsInByte = 8;
766
767// Defaults used when the module carries no cir.ptr data-layout entry.
768constexpr static uint64_t kDefaultPointerSizeBits = 64;
769constexpr static uint64_t kDefaultPointerAlignment = 8;
770
771/// Returns the default-address-space #cir.ptr_spec entry, or a synthesized
772/// 64-bit default when there is none. Per-AS entries are not modeled yet.
773cir::PtrSpecAttr getPointerSpec(mlir::DataLayoutEntryListRef params,
774 cir::PointerType type) {
775 // FIXME: improve this in face of address spaces
777 for (mlir::DataLayoutEntryInterface entry : params) {
778 if (!entry.isTypeEntry())
779 continue;
780 auto key =
781 mlir::cast<cir::PointerType>(mlir::cast<mlir::Type>(entry.getKey()));
782 if (key.getAddrSpace())
783 continue;
784 if (auto spec = mlir::dyn_cast<cir::PtrSpecAttr>(entry.getValue()))
785 return spec;
786 }
787 return cir::PtrSpecAttr::get(type.getContext(), kDefaultPointerSizeBits,
788 kDefaultPointerAlignment * kBitsInByte,
789 kDefaultPointerAlignment * kBitsInByte,
790 kDefaultPointerSizeBits);
791}
792
793// TargetInfo::getBitIntMaxAlign() when the module has no #cir.bitint_spec
794// entry. That is LongLongAlign's initial value.
795constexpr static uint64_t kDefaultBitIntMaxAlignBits = 64;
796
797/// The _BitInt alignment cap in bits. The #cir.bitint_spec entry holds
798/// TargetInfo::getBitIntMaxAlign().
799uint64_t getBitIntMaxAlignBits(mlir::DataLayoutEntryListRef params) {
800 for (mlir::DataLayoutEntryInterface entry : params) {
801 if (!entry.isTypeEntry())
802 continue;
803 if (auto spec = mlir::dyn_cast<cir::BitIntSpecAttr>(entry.getValue()))
804 return spec.getMaxAlign();
805 }
806 return kDefaultBitIntMaxAlignBits;
807}
808} // namespace
809
810llvm::TypeSize
811PointerType::getTypeSizeInBits(const ::mlir::DataLayout &dataLayout,
812 ::mlir::DataLayoutEntryListRef params) const {
813 return llvm::TypeSize::getFixed(getPointerSpec(params, *this).getSize());
814}
815
817PointerType::getABIAlignment(const ::mlir::DataLayout &dataLayout,
818 ::mlir::DataLayoutEntryListRef params) const {
819 return getPointerSpec(params, *this).getAbi() / kBitsInByte;
820}
821
822uint64_t PointerType::getPreferredAlignment(
823 const ::mlir::DataLayout &dataLayout,
824 ::mlir::DataLayoutEntryListRef params) const {
825 return getPointerSpec(params, *this).getPreferred() / kBitsInByte;
826}
827
828std::optional<uint64_t>
829PointerType::getIndexBitwidth(const ::mlir::DataLayout &dataLayout,
830 ::mlir::DataLayoutEntryListRef params) const {
831 cir::PtrSpecAttr spec = getPointerSpec(params, *this);
832 if (spec.getIndex() == cir::PtrSpecAttr::kOptionalSpecValue)
833 return spec.getSize();
834 return spec.getIndex();
835}
836
837llvm::LogicalResult
838PointerType::verifyEntries(mlir::DataLayoutEntryListRef entries,
839 mlir::Location loc) const {
840 for (mlir::DataLayoutEntryInterface entry : entries) {
841 if (!entry.isTypeEntry())
842 continue;
843 auto key = mlir::cast<PointerType>(mlir::cast<mlir::Type>(entry.getKey()));
844 if (!mlir::isa<cir::PtrSpecAttr>(entry.getValue()))
845 return mlir::emitError(loc) << "expected layout attribute for " << key
846 << " to be a #cir.ptr_spec attribute";
847 if (!mlir::isa<cir::VoidType>(key.getPointee()))
848 return mlir::emitError(loc) << "expected !cir.ptr data layout entry for "
849 << key << " to use !cir.void as pointee";
850 // Per-address-space pointer layouts are not supported yet.
851 if (key.getAddrSpace())
852 return mlir::emitError(loc)
853 << "!cir.ptr data layout entries are currently limited to the "
854 "default address space";
855 }
856 return mlir::success();
857}
858
859bool PointerType::areCompatible(
860 mlir::DataLayoutEntryListRef oldLayout,
861 mlir::DataLayoutEntryListRef newLayout, mlir::DataLayoutSpecInterface,
862 const mlir::DataLayoutIdentifiedEntryMap &) const {
863 // A nested spec may only override with the same size and a compatible ABI
864 // alignment. TODO(cir): match by address space once per-AS specs exist.
865 cir::PtrSpecAttr oldSpec = getPointerSpec(oldLayout, *this);
866 uint64_t size = oldSpec.getSize();
867 uint64_t abi = oldSpec.getAbi();
868 for (mlir::DataLayoutEntryInterface newEntry : newLayout) {
869 if (!newEntry.isTypeEntry())
870 continue;
871 auto newSpec = mlir::cast<cir::PtrSpecAttr>(newEntry.getValue());
872 if (size != newSpec.getSize() || abi < newSpec.getAbi() ||
873 abi % newSpec.getAbi() != 0)
874 return false;
875 }
876 return true;
877}
878
879llvm::TypeSize
880StructType::getTypeSizeInBits(const mlir::DataLayout &dataLayout,
881 mlir::DataLayoutEntryListRef params) const {
882 auto recordSize = static_cast<uint64_t>(computeStructSize(dataLayout));
883 return llvm::TypeSize::getFixed(recordSize * 8);
884}
885
887StructType::getABIAlignment(const ::mlir::DataLayout &dataLayout,
888 ::mlir::DataLayoutEntryListRef params) const {
889 // Packed structures always have an ABI alignment of 1.
890 if (getPacked())
891 return 1;
892 return computeStructAlignment(dataLayout);
893}
894
895// Sums the storage member's alloc size (if present) with the padding field's
896// size (if present).
897// A union whose member list came out empty has no storage type, so its whole
898// size lives in the padding, which lowerUnion sizes from the ASTRecordLayout.
899llvm::TypeSize
900UnionType::getTypeSizeInBits(const mlir::DataLayout &dataLayout,
901 mlir::DataLayoutEntryListRef params) const {
902 llvm::TypeSize size = llvm::TypeSize::getFixed(0);
903 if (mlir::Type storage = getUnionStorageType(dataLayout))
904 size += dataLayout.getTypeAllocSize(storage) * 8;
905 if (mlir::Type pad = getPadding())
906 size += dataLayout.getTypeSizeInBits(pad);
907 return size;
908}
909
911UnionType::getABIAlignment(const ::mlir::DataLayout &dataLayout,
912 ::mlir::DataLayoutEntryListRef params) const {
913 if (getPacked())
914 return 1;
915 mlir::Type storage = getUnionStorageType(dataLayout);
916 if (!storage)
917 return 1;
918 return dataLayout.getTypeABIAlignment(storage);
919}
920
921unsigned
922StructType::computeStructSize(const mlir::DataLayout &dataLayout) const {
923 assert(isComplete() && "Cannot get layout of incomplete records");
924
925 // This is a similar algorithm to LLVM's StructLayout. A member that owns no
926 // bytes needs no special case: it reports size 0 and alignment 1, so the
927 // running size passes over it unchanged.
928 unsigned recordSize = 0;
929 uint64_t recordAlignment = 1;
930
931 for (mlir::Type ty : getMembers()) {
932 // This assumes that we're calculating size based on the ABI alignment, not
933 // the preferred alignment for each type.
934 const uint64_t tyAlign =
935 (getPacked() ? 1 : dataLayout.getTypeABIAlignment(ty));
936
937 // Add padding to the struct size to align it to the abi alignment of the
938 // element type before adding the element's alloc size.
939 recordSize = llvm::alignTo(recordSize, tyAlign);
940 recordSize += dataLayout.getTypeAllocSize(ty);
941
942 // The alignment requirement of a struct is equal to the strictest
943 // alignment requirement of its elements.
944 recordAlignment = std::max(tyAlign, recordAlignment);
945 }
946
947 // At the end, add padding to the struct to satisfy its own alignment
948 // requirement. Otherwise structs inside of arrays would be misaligned.
949 recordSize = llvm::alignTo(recordSize, recordAlignment);
950 return recordSize;
951}
952
953unsigned
954StructType::computeStructDataSize(const mlir::DataLayout &dataLayout) const {
955 assert(isComplete() && "Cannot get layout of incomplete records");
956
957 // Tail padding is the trailing run of pad members, which is what a derived
958 // class may reuse. A member that owns no bytes holds no storage, so it does
959 // not end that run. A member of any other kind stays inside the data size.
960 llvm::ArrayRef<mlir::Type> members = getMembers();
961 llvm::ArrayRef<RecordMemberKind> kinds = getMemberKinds();
962 assert(kinds.size() == members.size() &&
963 "the two drop_back calls below must stay in step");
964 while (!kinds.empty() && (kinds.back() == RecordMemberKind::Pad ||
965 !memberOwnsBytes(members.back()))) {
966 kinds = kinds.drop_back();
967 members = members.drop_back();
968 }
969
970 unsigned recordSize = 0;
971 for (mlir::Type ty : members) {
972 const uint64_t tyAlign =
973 (getPacked() ? 1 : dataLayout.getTypeABIAlignment(ty));
974 recordSize = llvm::alignTo(recordSize, tyAlign);
975 recordSize += dataLayout.getTypeAllocSize(ty);
976 }
977 return recordSize;
978}
979
980// We also compute the alignment as part of computeStructSize, but this is more
981// efficient. Ideally, we'd like to compute both at once and cache the result,
982// but that's not implemented yet.
983// TODO(CIR): Implement a way to cache the result.
985StructType::computeStructAlignment(const mlir::DataLayout &dataLayout) const {
986 assert(isComplete() && "Cannot get layout of incomplete records");
987
988 uint64_t recordAlignment = 1;
989 for (mlir::Type ty : getMembers())
990 recordAlignment =
991 std::max(dataLayout.getTypeABIAlignment(ty), recordAlignment);
992 return recordAlignment;
993}
994
995unsigned StructType::getLLVMFieldIndex(unsigned idx) const {
996 llvm::ArrayRef<mlir::Type> members = getMembers();
997 assert(idx < members.size() && "access not valid");
998 assert(memberOwnsBytes(members[idx]) &&
999 "a member that owns no bytes has no LLVM field");
1000
1001 unsigned llvmIdx = 0;
1002 for (unsigned i = 0; i != idx; ++i)
1003 if (memberOwnsBytes(members[i]))
1004 ++llvmIdx;
1005 return llvmIdx;
1006}
1007
1008uint64_t StructType::getElementOffset(const ::mlir::DataLayout &dataLayout,
1009 unsigned idx) const {
1010 assert(idx < getMembers().size() && "access not valid");
1011 if (idx == 0)
1012 return 0;
1013
1014 assert(isComplete() && "Cannot get layout of incomplete records");
1015 llvm::ArrayRef<mlir::Type> members = getMembers();
1016
1017 // A zero-width bit-field reports alignment 1 and size 0, so the running
1018 // offset passes over it unchanged and lands on where the storage ahead of it
1019 // ends, which is the offset it was declared at.
1020 unsigned offset = 0;
1021 for (unsigned i = 0; i != idx; ++i) {
1022 const llvm::Align tyAlign = llvm::Align(
1023 getPacked() ? 1 : dataLayout.getTypeABIAlignment(members[i]));
1024 offset = llvm::alignTo(offset, tyAlign);
1025 offset += dataLayout.getTypeAllocSize(members[i]);
1026 }
1027
1028 const llvm::Align tyAlign = llvm::Align(
1029 getPacked() ? 1 : dataLayout.getTypeABIAlignment(members[idx]));
1030 return llvm::alignTo(offset, tyAlign);
1031}
1032
1033//===----------------------------------------------------------------------===//
1034// IntType Definitions
1035//===----------------------------------------------------------------------===//
1036
1037Type IntType::parse(mlir::AsmParser &parser) {
1038 mlir::MLIRContext *context = parser.getBuilder().getContext();
1039 llvm::SMLoc loc = parser.getCurrentLocation();
1040 bool isSigned;
1041 unsigned width;
1042
1043 if (parser.parseLess())
1044 return {};
1045
1046 // Fetch integer sign.
1047 llvm::StringRef sign;
1048 if (parser.parseKeyword(&sign))
1049 return {};
1050 if (sign == "s")
1051 isSigned = true;
1052 else if (sign == "u")
1053 isSigned = false;
1054 else {
1055 parser.emitError(loc, "expected 's' or 'u'");
1056 return {};
1057 }
1058
1059 if (parser.parseComma())
1060 return {};
1061
1062 // Fetch integer size.
1063 if (parser.parseInteger(width))
1064 return {};
1065 if (width < IntType::minBitwidth() || width > IntType::maxBitwidth()) {
1066 parser.emitError(loc, "expected integer width to be from ")
1067 << IntType::minBitwidth() << " up to " << IntType::maxBitwidth();
1068 return {};
1069 }
1070
1071 bool isBitInt = false;
1072 if (succeeded(parser.parseOptionalComma())) {
1073 llvm::StringRef kw;
1074 if (parser.parseKeyword(&kw) || kw != "bitint") {
1075 parser.emitError(loc, "expected 'bitint'");
1076 return {};
1077 }
1078 isBitInt = true;
1079 }
1080
1081 if (parser.parseGreater())
1082 return {};
1083
1084 return IntType::get(context, width, isSigned, isBitInt);
1085}
1086
1087void IntType::print(mlir::AsmPrinter &printer) const {
1088 char sign = isSigned() ? 's' : 'u';
1089 printer << '<' << sign << ", " << getWidth();
1090 if (isBitInt())
1091 printer << ", bitint";
1092 printer << '>';
1093}
1094
1095llvm::TypeSize
1096IntType::getTypeSizeInBits(const mlir::DataLayout &dataLayout,
1097 mlir::DataLayoutEntryListRef params) const {
1098 return llvm::TypeSize::getFixed(getStorageTypeWidth(dataLayout));
1099}
1100
1101unsigned
1102IntType::getStorageTypeWidth(const mlir::DataLayout &dataLayout) const {
1103 if (!isBitInt())
1104 return getWidth();
1105 uint64_t alignBits = dataLayout.getTypeABIAlignment(*this) * 8;
1106 return static_cast<unsigned>(llvm::alignTo(getWidth(), alignBits));
1107}
1108
1110IntType::getStorageTypeAlignment(const mlir::DataLayout &dataLayout) const {
1111 if (!isBitInt())
1112 return getABIAlignment(dataLayout, {});
1113 auto storageTy =
1114 mlir::IntegerType::get(getContext(), getStorageTypeWidth(dataLayout));
1115 return dataLayout.getTypeABIAlignment(storageTy);
1116}
1117
1118uint64_t IntType::getABIAlignment(const mlir::DataLayout &dataLayout,
1119 mlir::DataLayoutEntryListRef params) const {
1120 unsigned width = getWidth();
1121 if (isBitInt()) {
1122 uint64_t maxAlignBits = getBitIntMaxAlignBits(params);
1123 uint64_t alignBits = std::min(
1124 static_cast<uint64_t>(llvm::PowerOf2Ceil(width)), maxAlignBits);
1125 return std::max(alignBits / 8, static_cast<uint64_t>(1));
1126 }
1127 // Round up to a power-of-two byte alignment. DataLayout consumers such as
1128 // llvm::Align require power-of-two alignments, and width / 8 is not a power
1129 // of two for non-fundamental widths (e.g. i24 -> 3). This leaves the
1130 // fundamental widths unchanged (i8 -> 1, i16 -> 2, i32 -> 4, i64 -> 8) and
1131 // keeps __int128 at 16.
1132 uint64_t alignBits = llvm::PowerOf2Ceil(width);
1133 return std::max(alignBits / 8, static_cast<uint64_t>(1));
1134}
1135
1136bool IntType::areCompatible(mlir::DataLayoutEntryListRef oldLayout,
1137 mlir::DataLayoutEntryListRef newLayout,
1138 mlir::DataLayoutSpecInterface,
1139 const mlir::DataLayoutIdentifiedEntryMap &) const {
1140 // A nested spec may only repeat the same _BitInt max alignment.
1141 uint64_t oldMax = getBitIntMaxAlignBits(oldLayout);
1142 for (mlir::DataLayoutEntryInterface newEntry : newLayout) {
1143 if (!newEntry.isTypeEntry())
1144 continue;
1145 auto newSpec = mlir::dyn_cast<cir::BitIntSpecAttr>(newEntry.getValue());
1146 if (newSpec && newSpec.getMaxAlign() != oldMax)
1147 return false;
1148 }
1149 return true;
1150}
1151
1152llvm::LogicalResult IntType::verifyEntries(mlir::DataLayoutEntryListRef entries,
1153 mlir::Location loc) const {
1154 cir::IntType keyTy = getBitIntMaxAlignKey(getContext());
1155 for (mlir::DataLayoutEntryInterface entry : entries) {
1156 if (!entry.isTypeEntry())
1157 continue;
1158 auto key = mlir::cast<IntType>(mlir::cast<mlir::Type>(entry.getKey()));
1159 if (key != keyTy)
1160 return mlir::emitError(loc)
1161 << "expected _BitInt data layout entry to be keyed on " << keyTy
1162 << ", got " << key;
1163 if (!mlir::isa<cir::BitIntSpecAttr>(entry.getValue()))
1164 return mlir::emitError(loc) << "expected layout attribute for " << key
1165 << " to be a #cir.bitint_spec attribute";
1166 }
1167 return mlir::success();
1168}
1169
1170mlir::LogicalResult
1171IntType::verify(llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
1172 unsigned width, bool isSigned, bool isBitInt) {
1173 if (width < IntType::minBitwidth() || width > IntType::maxBitwidth())
1174 return emitError() << "IntType only supports widths from "
1175 << IntType::minBitwidth() << " up to "
1176 << IntType::maxBitwidth();
1177 return mlir::success();
1178}
1179
1181 return width == 8 || width == 16 || width == 32 || width == 64;
1182}
1183
1184//===----------------------------------------------------------------------===//
1185// Floating-point type definitions
1186//===----------------------------------------------------------------------===//
1187
1188const llvm::fltSemantics &SingleType::getFloatSemantics() const {
1189 return llvm::APFloat::IEEEsingle();
1190}
1191
1192llvm::TypeSize
1193SingleType::getTypeSizeInBits(const mlir::DataLayout &dataLayout,
1194 mlir::DataLayoutEntryListRef params) const {
1195 return llvm::TypeSize::getFixed(getWidth());
1196}
1197
1199SingleType::getABIAlignment(const mlir::DataLayout &dataLayout,
1200 mlir::DataLayoutEntryListRef params) const {
1201 return (uint64_t)(getWidth() / 8);
1202}
1203
1204const llvm::fltSemantics &DoubleType::getFloatSemantics() const {
1205 return llvm::APFloat::IEEEdouble();
1206}
1207
1208llvm::TypeSize
1209DoubleType::getTypeSizeInBits(const mlir::DataLayout &dataLayout,
1210 mlir::DataLayoutEntryListRef params) const {
1211 return llvm::TypeSize::getFixed(getWidth());
1212}
1213
1215DoubleType::getABIAlignment(const mlir::DataLayout &dataLayout,
1216 mlir::DataLayoutEntryListRef params) const {
1217 return (uint64_t)(getWidth() / 8);
1218}
1219
1220const llvm::fltSemantics &FP16Type::getFloatSemantics() const {
1221 return llvm::APFloat::IEEEhalf();
1222}
1223
1224llvm::TypeSize
1225FP16Type::getTypeSizeInBits(const mlir::DataLayout &dataLayout,
1226 mlir::DataLayoutEntryListRef params) const {
1227 return llvm::TypeSize::getFixed(getWidth());
1228}
1229
1230uint64_t FP16Type::getABIAlignment(const mlir::DataLayout &dataLayout,
1231 mlir::DataLayoutEntryListRef params) const {
1232 return (uint64_t)(getWidth() / 8);
1233}
1234
1235const llvm::fltSemantics &BF16Type::getFloatSemantics() const {
1236 return llvm::APFloat::BFloat();
1237}
1238
1239llvm::TypeSize
1240BF16Type::getTypeSizeInBits(const mlir::DataLayout &dataLayout,
1241 mlir::DataLayoutEntryListRef params) const {
1242 return llvm::TypeSize::getFixed(getWidth());
1243}
1244
1245uint64_t BF16Type::getABIAlignment(const mlir::DataLayout &dataLayout,
1246 mlir::DataLayoutEntryListRef params) const {
1247 return (uint64_t)(getWidth() / 8);
1248}
1249
1250const llvm::fltSemantics &FP80Type::getFloatSemantics() const {
1251 return llvm::APFloat::x87DoubleExtended();
1252}
1253
1254llvm::TypeSize
1255FP80Type::getTypeSizeInBits(const mlir::DataLayout &dataLayout,
1256 mlir::DataLayoutEntryListRef params) const {
1257 // Though only 80 bits are used for the value, the type is 128 bits in size.
1258 return llvm::TypeSize::getFixed(128);
1259}
1260
1261uint64_t FP80Type::getABIAlignment(const mlir::DataLayout &dataLayout,
1262 mlir::DataLayoutEntryListRef params) const {
1263 return 16;
1264}
1265
1266const llvm::fltSemantics &FP128Type::getFloatSemantics() const {
1267 return llvm::APFloat::IEEEquad();
1268}
1269
1270llvm::TypeSize
1271FP128Type::getTypeSizeInBits(const mlir::DataLayout &dataLayout,
1272 mlir::DataLayoutEntryListRef params) const {
1273 return llvm::TypeSize::getFixed(getWidth());
1274}
1275
1276uint64_t FP128Type::getABIAlignment(const mlir::DataLayout &dataLayout,
1277 mlir::DataLayoutEntryListRef params) const {
1278 return 16;
1279}
1280
1281const llvm::fltSemantics &LongDoubleType::getFloatSemantics() const {
1282 return mlir::cast<cir::FPTypeInterface>(getUnderlying()).getFloatSemantics();
1283}
1284
1285llvm::TypeSize
1286LongDoubleType::getTypeSizeInBits(const mlir::DataLayout &dataLayout,
1287 mlir::DataLayoutEntryListRef params) const {
1288 return mlir::cast<mlir::DataLayoutTypeInterface>(getUnderlying())
1289 .getTypeSizeInBits(dataLayout, params);
1290}
1291
1293LongDoubleType::getABIAlignment(const mlir::DataLayout &dataLayout,
1294 mlir::DataLayoutEntryListRef params) const {
1295 return mlir::cast<mlir::DataLayoutTypeInterface>(getUnderlying())
1296 .getABIAlignment(dataLayout, params);
1297}
1298
1299//===----------------------------------------------------------------------===//
1300// ComplexType Definitions
1301//===----------------------------------------------------------------------===//
1302
1303llvm::TypeSize
1304cir::ComplexType::getTypeSizeInBits(const mlir::DataLayout &dataLayout,
1305 mlir::DataLayoutEntryListRef params) const {
1306 // C17 6.2.5p13:
1307 // Each complex type has the same representation and alignment requirements
1308 // as an array type containing exactly two elements of the corresponding
1309 // real type.
1310
1311 return dataLayout.getTypeSizeInBits(getElementType()) * 2;
1312}
1313
1315cir::ComplexType::getABIAlignment(const mlir::DataLayout &dataLayout,
1316 mlir::DataLayoutEntryListRef params) const {
1317 // C17 6.2.5p13:
1318 // Each complex type has the same representation and alignment requirements
1319 // as an array type containing exactly two elements of the corresponding
1320 // real type.
1321
1322 return dataLayout.getTypeABIAlignment(getElementType());
1323}
1324
1325FuncType FuncType::clone(TypeRange inputs, TypeRange results) const {
1326 assert(results.size() == 1 && "expected exactly one result type");
1327 return get(llvm::to_vector(inputs), results[0], isVarArg());
1328}
1329
1330// Custom parser that parses function parameters of form `(<type>*, ...)`.
1331static mlir::ParseResult
1333 bool &isVarArg) {
1334 isVarArg = false;
1335 return p.parseCommaSeparatedList(
1336 AsmParser::Delimiter::Paren, [&]() -> mlir::ParseResult {
1337 if (isVarArg)
1338 return p.emitError(p.getCurrentLocation(),
1339 "variadic `...` must be the last parameter");
1340 if (succeeded(p.parseOptionalEllipsis())) {
1341 isVarArg = true;
1342 return success();
1343 }
1344 mlir::Type type;
1345 if (failed(p.parseType(type)))
1346 return failure();
1347 params.push_back(type);
1348 return success();
1349 });
1350}
1351
1352static void printFuncTypeParams(mlir::AsmPrinter &p,
1353 mlir::ArrayRef<mlir::Type> params,
1354 bool isVarArg) {
1355 p << '(';
1356 llvm::interleaveComma(params, p,
1357 [&p](mlir::Type type) { p.printType(type); });
1358 if (isVarArg) {
1359 if (!params.empty())
1360 p << ", ";
1361 p << "...";
1362 }
1363 p << ')';
1364}
1365
1366/// Get the C-style return type of the function, which is !cir.void if the
1367/// function returns nothing and the actual return type otherwise.
1368mlir::Type FuncType::getReturnType() const {
1369 if (hasVoidReturn())
1370 return cir::VoidType::get(getContext());
1371 return getOptionalReturnType();
1372}
1373
1374/// Get the MLIR-style return type of the function, which is an empty
1375/// ArrayRef if the function returns nothing and a single-element ArrayRef
1376/// with the actual return type otherwise.
1377llvm::ArrayRef<mlir::Type> FuncType::getReturnTypes() const {
1378 if (hasVoidReturn())
1379 return {};
1380 // Can't use getOptionalReturnType() here because llvm::ArrayRef hold a
1381 // pointer to its elements and doesn't do lifetime extension. That would
1382 // result in returning a pointer to a temporary that has gone out of scope.
1383 return getImpl()->optionalReturnType;
1384}
1385
1386// Does the fuction type return nothing?
1387bool FuncType::hasVoidReturn() const { return !getOptionalReturnType(); }
1388
1389mlir::LogicalResult
1390FuncType::verify(llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
1391 llvm::ArrayRef<mlir::Type> argTypes, mlir::Type returnType,
1392 bool isVarArg) {
1393 if (mlir::isa_and_nonnull<cir::VoidType>(returnType))
1394 return emitError()
1395 << "!cir.func cannot have an explicit 'void' return type";
1396
1397 // The calling convention lowering pass expects all types in a function
1398 // signature to be CIR types. CIR types only nest CIR types, so checking the
1399 // signature's own types covers everything reachable from them.
1400 if (!llvm::all_of(argTypes, cir::isCIRType) ||
1401 (returnType && !cir::isCIRType(returnType)))
1402 return emitError()
1403 << "expected all types in the function signature to be CIR types";
1404
1405 return mlir::success();
1406}
1407
1408//===----------------------------------------------------------------------===//
1409// MethodType Definitions
1410//===----------------------------------------------------------------------===//
1411
1412static mlir::Type getMethodLayoutType(mlir::MLIRContext *ctx) {
1413 // With Itanium ABI, member function pointers have the same layout as the
1414 // following struct: struct { fnptr_t, ptrdiff_t }, where fnptr_t is a
1415 // function pointer type.
1416 // TODO: consider member function pointer layout in other ABIs
1417 auto voidPtrTy = cir::PointerType::get(cir::VoidType::get(ctx));
1418 mlir::Type fields[2]{voidPtrTy, voidPtrTy};
1419 return cir::StructType::get(ctx, fields, /*packed=*/false,
1420 /*is_class=*/false,
1422}
1423
1424llvm::TypeSize
1425MethodType::getTypeSizeInBits(const mlir::DataLayout &dataLayout,
1426 mlir::DataLayoutEntryListRef params) const {
1427 return dataLayout.getTypeSizeInBits(getMethodLayoutType(getContext()));
1428}
1429
1431MethodType::getABIAlignment(const mlir::DataLayout &dataLayout,
1432 mlir::DataLayoutEntryListRef params) const {
1433 return cast<cir::StructType>(getMethodLayoutType(getContext()))
1434 .getABIAlignment(dataLayout, params);
1435}
1436
1437//===----------------------------------------------------------------------===//
1438// BoolType
1439//===----------------------------------------------------------------------===//
1440
1441llvm::TypeSize
1442BoolType::getTypeSizeInBits(const ::mlir::DataLayout &dataLayout,
1443 ::mlir::DataLayoutEntryListRef params) const {
1444 return llvm::TypeSize::getFixed(8);
1445}
1446
1448BoolType::getABIAlignment(const ::mlir::DataLayout &dataLayout,
1449 ::mlir::DataLayoutEntryListRef params) const {
1450 return 1;
1451}
1452
1453//===----------------------------------------------------------------------===//
1454// DataMemberType Definitions
1455//===----------------------------------------------------------------------===//
1456
1457static mlir::Type getDataMemberLayoutType(const mlir::DataLayout &dataLayout,
1458 mlir::MLIRContext *ctx) {
1459 // Itanium ABI: a data member pointer is a ptrdiff_t, an integer of the
1460 // pointer index width.
1461 // TODO: consider data member pointer layout in other ABIs
1462 auto voidPtrTy = cir::PointerType::get(cir::VoidType::get(ctx));
1463 uint64_t width = dataLayout.getTypeIndexBitwidth(voidPtrTy).value_or(
1464 dataLayout.getTypeSizeInBits(voidPtrTy).getFixedValue());
1465 return cir::IntType::get(ctx, width, /*is_signed=*/true);
1466}
1467
1468llvm::TypeSize
1469DataMemberType::getTypeSizeInBits(const ::mlir::DataLayout &dataLayout,
1470 ::mlir::DataLayoutEntryListRef params) const {
1471 assert(!MissingFeatures::cxxABI());
1472 return dataLayout.getTypeSizeInBits(
1473 getDataMemberLayoutType(dataLayout, getContext()));
1474}
1475
1477DataMemberType::getABIAlignment(const ::mlir::DataLayout &dataLayout,
1478 ::mlir::DataLayoutEntryListRef params) const {
1479 assert(!MissingFeatures::cxxABI());
1480 return dataLayout.getTypeABIAlignment(
1481 getDataMemberLayoutType(dataLayout, getContext()));
1482}
1483
1484//===----------------------------------------------------------------------===//
1485// VPtrType Definitions
1486//===----------------------------------------------------------------------===//
1487
1488llvm::TypeSize
1489VPtrType::getTypeSizeInBits(const mlir::DataLayout &dataLayout,
1490 mlir::DataLayoutEntryListRef params) const {
1491 // A vtable pointer is an ordinary data pointer; size it as a cir.ptr.
1492 return dataLayout.getTypeSizeInBits(
1493 cir::PointerType::get(cir::VoidType::get(getContext())));
1494}
1495
1496uint64_t VPtrType::getABIAlignment(const mlir::DataLayout &dataLayout,
1497 mlir::DataLayoutEntryListRef params) const {
1498 return dataLayout.getTypeABIAlignment(
1499 cir::PointerType::get(cir::VoidType::get(getContext())));
1500}
1501
1502//===----------------------------------------------------------------------===//
1503// ArrayType Definitions
1504//===----------------------------------------------------------------------===//
1505
1506llvm::TypeSize
1507ArrayType::getTypeSizeInBits(const ::mlir::DataLayout &dataLayout,
1508 ::mlir::DataLayoutEntryListRef params) const {
1509 return getSize() * dataLayout.getTypeAllocSize(getElementType()) * 8;
1510}
1511
1513ArrayType::getABIAlignment(const ::mlir::DataLayout &dataLayout,
1514 ::mlir::DataLayoutEntryListRef params) const {
1515 return dataLayout.getTypeABIAlignment(getElementType());
1516}
1517
1518//===----------------------------------------------------------------------===//
1519// BitFieldType Definitions
1520//===----------------------------------------------------------------------===//
1521
1522mlir::LogicalResult
1523BitFieldType::verify(llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
1524 mlir::Type storageType,
1525 llvm::ArrayRef<cir::BitFieldDeclAttr> fields) {
1526 if (fields.empty())
1527 return emitError() << "bit-field member must hold at least one bit-field";
1528
1529 if (!storageType) {
1530 // Absent storage is the zero-width bit-field, which belongs to no access
1531 // unit and so keeps company with nothing.
1532 if (fields.size() != 1 || fields.front().getWidth() != 0)
1533 return emitError() << "a bit-field member without storage must hold a "
1534 "single zero-width bit-field";
1535 return mlir::success();
1536 }
1537
1538 if (!cir::isCIRType(storageType))
1539 return emitError() << "bit-field access unit storage must be a CIR type, "
1540 "got "
1541 << storageType;
1542
1543 if (mlir::isa<cir::BitFieldType>(storageType))
1544 return emitError() << "bit-field access unit storage cannot itself be a "
1545 "bit-field type";
1546
1547 if (!cir::isSized(storageType))
1548 return emitError() << "bit-field access unit storage must be sized, got "
1549 << storageType;
1550
1551 // A zero-width bit-field ends the run before it rather than joining a unit,
1552 // so it never appears alongside the fields that occupy one.
1553 if (llvm::any_of(fields, [](cir::BitFieldDeclAttr decl) {
1554 return decl.getWidth() == 0;
1555 }))
1556 return emitError() << "a zero-width bit-field cannot occupy an access unit";
1557
1558 return mlir::success();
1559}
1560
1561llvm::TypeSize
1562BitFieldType::getTypeSizeInBits(const mlir::DataLayout &dataLayout,
1563 mlir::DataLayoutEntryListRef params) const {
1564 // A unit is stored as its storage type. A zero-width bit-field has none,
1565 // and holds no bits of its own.
1566 if (mlir::Type storage = getStorageType())
1567 return dataLayout.getTypeSizeInBits(storage);
1568 return llvm::TypeSize::getFixed(0);
1569}
1570
1572BitFieldType::getABIAlignment(const mlir::DataLayout &dataLayout,
1573 mlir::DataLayoutEntryListRef params) const {
1574 // A member that occupies no bytes imposes no alignment, which is what lets
1575 // the record layout walk a zero-width bit-field without skipping it.
1576 if (mlir::Type storage = getStorageType())
1577 return dataLayout.getTypeABIAlignment(storage);
1578 return 1;
1579}
1580
1581//===----------------------------------------------------------------------===//
1582// VectorType Definitions
1583//===----------------------------------------------------------------------===//
1584
1585llvm::TypeSize cir::VectorType::getTypeSizeInBits(
1586 const ::mlir::DataLayout &dataLayout,
1587 ::mlir::DataLayoutEntryListRef params) const {
1588 // Clang packs a fixed-length bool vector one bit per element and rounds the
1589 // vector's size up to a power of two of at least a byte.
1590 if (mlir::isa<cir::BoolType>(getElementType()) && getSize().isFixed()) {
1591 assert(!cir::MissingFeatures::hlsl());
1592 return llvm::TypeSize::getFixed(llvm::PowerOf2Ceil(getBoolStorageWidth()));
1593 }
1594
1595 llvm::TypeSize elementSize = dataLayout.getTypeSizeInBits(getElementType());
1596 return llvm::TypeSize::get(
1597 getSize().getKnownMinValue() * elementSize.getFixedValue(), isScalable());
1598}
1599
1600uint64_t cir::VectorType::getBoolStorageWidth() const {
1601 assert(mlir::isa<cir::BoolType>(getElementType()) &&
1602 "only a bool vector is stored as an integer");
1603 return std::max<uint64_t>(getFixedSize(), 8);
1604}
1605
1607cir::VectorType::getABIAlignment(const ::mlir::DataLayout &dataLayout,
1608 ::mlir::DataLayoutEntryListRef params) const {
1609 // This hook answers in bytes, not bits.
1610 return llvm::PowerOf2Ceil(llvm::divideCeil(
1611 dataLayout.getTypeSizeInBits(*this).getKnownMinValue(), uint64_t{8}));
1612}
1613
1614mlir::LogicalResult cir::VectorType::verify(
1615 llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
1616 mlir::Type elementType, llvm::ElementCount size) {
1617 if (size.isZero())
1618 return emitError() << "the number of vector elements must be non-zero";
1619 return success();
1620}
1621
1622mlir::Type cir::VectorType::parse(::mlir::AsmParser &odsParser) {
1623
1624 llvm::SMLoc odsLoc = odsParser.getCurrentLocation();
1625 mlir::Builder odsBuilder(odsParser.getContext());
1626 mlir::FailureOr<::mlir::Type> elementType;
1627 mlir::FailureOr<uint64_t> size;
1628 bool isScalable = false;
1629
1630 // Parse literal '<'
1631 if (odsParser.parseLess())
1632 return {};
1633
1634 // Parse literal '[', if present, and set the scalability flag accordingly
1635 if (odsParser.parseOptionalLSquare().succeeded())
1636 isScalable = true;
1637
1638 // Parse variable 'size'
1639 size = mlir::FieldParser<uint64_t>::parse(odsParser);
1640 if (mlir::failed(size)) {
1641 odsParser.emitError(odsParser.getCurrentLocation(),
1642 "failed to parse CIR_VectorType parameter 'size' which "
1643 "is to be a `uint64_t`");
1644 return {};
1645 }
1646
1647 // Parse literal ']', which is expected when dealing with scalable
1648 // dim sizes
1649 if (isScalable && odsParser.parseRSquare().failed()) {
1650 odsParser.emitError(odsParser.getCurrentLocation(),
1651 "missing closing `]` for scalable dim size");
1652 return {};
1653 }
1654
1655 // Parse literal 'x'
1656 if (odsParser.parseKeyword("x"))
1657 return {};
1658
1659 // Parse variable 'elementType'
1660 elementType = mlir::FieldParser<::mlir::Type>::parse(odsParser);
1661 if (mlir::failed(elementType)) {
1662 odsParser.emitError(odsParser.getCurrentLocation(),
1663 "failed to parse CIR_VectorType parameter "
1664 "'elementType' which is to be a `mlir::Type`");
1665 return {};
1666 }
1667
1668 // Parse literal '>'
1669 if (odsParser.parseGreater())
1670 return {};
1671 return odsParser.getChecked<VectorType>(
1672 odsLoc, odsParser.getContext(), mlir::Type((*elementType)),
1673 llvm::ElementCount::get(*size, isScalable));
1674}
1675
1676void cir::VectorType::print(mlir::AsmPrinter &odsPrinter) const {
1677 mlir::Builder odsBuilder(getContext());
1678 odsPrinter << "<";
1679 if (isScalable())
1680 odsPrinter << "[";
1681
1682 odsPrinter.printStrippedAttrOrType(getSize().getKnownMinValue());
1683 if (isScalable())
1684 odsPrinter << "]";
1685 odsPrinter << ' ' << "x";
1686 odsPrinter << ' ';
1687 odsPrinter.printStrippedAttrOrType(getElementType());
1688 odsPrinter << ">";
1689}
1690
1691//===----------------------------------------------------------------------===//
1692// MatrixType Definitions
1693//===----------------------------------------------------------------------===//
1694
1695llvm::TypeSize cir::MatrixType::getTypeSizeInBits(
1696 const ::mlir::DataLayout &dataLayout,
1697 ::mlir::DataLayoutEntryListRef params) const {
1698 return llvm::TypeSize::getFixed(
1699 getNumRows() * getNumColumns() *
1700 dataLayout.getTypeSizeInBits(getElementType()));
1701}
1702
1704cir::MatrixType::getABIAlignment(const ::mlir::DataLayout &dataLayout,
1705 ::mlir::DataLayoutEntryListRef params) const {
1706 return dataLayout.getTypeABIAlignment(getElementType());
1707}
1708
1709mlir::LogicalResult cir::MatrixType::verify(
1710 llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
1711 mlir::Type elementType, uint64_t row, uint64_t column) {
1712 if (row == 0)
1713 return emitError() << "the number of matrix rows must be non-zero";
1714 if (column == 0)
1715 return emitError() << "the number of matrix columns must be non-zero";
1716 return success();
1717}
1718
1719//===----------------------------------------------------------------------===//
1720// AddressSpace definitions
1721//===----------------------------------------------------------------------===//
1722
1724 mlir::ptr::MemorySpaceAttrInterface memorySpace) {
1725 return mlir::isa<cir::LangAddressSpaceAttr, cir::TargetAddressSpaceAttr>(
1726 memorySpace);
1727}
1728
1729cir::LangAddressSpace cir::toCIRLangAddressSpace(clang::LangAS langAS) {
1730 using clang::LangAS;
1731 switch (langAS) {
1732 case LangAS::Default:
1733 return LangAddressSpace::Default;
1734 case LangAS::opencl_global:
1735 case LangAS::sycl_global:
1736 return LangAddressSpace::OffloadGlobal;
1737 case LangAS::opencl_local:
1738 case LangAS::cuda_shared:
1739 case LangAS::sycl_local:
1740 // Local means local among the work-group (OpenCL, SYCL) or block (CUDA).
1741 // All threads inside the kernel can access local memory.
1742 return LangAddressSpace::OffloadLocal;
1743 case LangAS::cuda_device:
1744 return LangAddressSpace::OffloadGlobal;
1745 case LangAS::opencl_constant:
1746 case LangAS::cuda_constant:
1747 case LangAS::sycl_constant:
1748 return LangAddressSpace::OffloadConstant;
1749 case LangAS::opencl_private:
1750 case LangAS::sycl_private:
1751 return LangAddressSpace::OffloadPrivate;
1752 case LangAS::opencl_generic:
1753 case LangAS::sycl_generic:
1754 return LangAddressSpace::OffloadGeneric;
1755 case LangAS::opencl_global_device:
1756 case LangAS::sycl_global_device:
1757 return LangAddressSpace::OffloadGlobalDevice;
1758 case LangAS::opencl_global_host:
1759 case LangAS::sycl_global_host:
1760 return LangAddressSpace::OffloadGlobalHost;
1761 case LangAS::ptr32_sptr:
1762 case LangAS::ptr32_uptr:
1763 case LangAS::ptr64:
1764 case LangAS::hlsl_groupshared:
1765 case LangAS::wasm_funcref:
1766 llvm_unreachable("NYI");
1767 default:
1768 llvm_unreachable("unknown/unsupported clang language address space");
1769 }
1770}
1771
1772mlir::ParseResult parseMemorySpace(mlir::AsmParser &p,
1773 mlir::ptr::MemorySpaceAttrInterface &attr) {
1774
1775 llvm::SMLoc loc = p.getCurrentLocation();
1776
1777 // Try to parse target address space first.
1778 attr = nullptr;
1779 if (p.parseOptionalKeyword("target_address_space").succeeded()) {
1780 unsigned val;
1781 if (p.parseLParen())
1782 return p.emitError(loc, "expected '(' after 'target_address_space'");
1783
1784 if (p.parseInteger(val))
1785 return p.emitError(loc, "expected target address space value");
1786
1787 if (p.parseRParen())
1788 return p.emitError(loc, "expected ')'");
1789
1790 attr = cir::TargetAddressSpaceAttr::get(p.getContext(), val);
1791 return mlir::success();
1792 }
1793
1794 // Try to parse language specific address space.
1795 if (p.parseOptionalKeyword("lang_address_space").succeeded()) {
1796 if (p.parseLParen())
1797 return p.emitError(loc, "expected '(' after 'lang_address_space'");
1798
1799 mlir::FailureOr<cir::LangAddressSpace> result =
1800 mlir::FieldParser<cir::LangAddressSpace>::parse(p);
1801 if (mlir::failed(result))
1802 return mlir::failure();
1803
1804 if (p.parseRParen())
1805 return p.emitError(loc, "expected ')'");
1806
1807 attr = cir::LangAddressSpaceAttr::get(p.getContext(), result.value());
1808 return mlir::success();
1809 }
1810
1811 llvm::StringRef keyword;
1812 if (p.parseOptionalKeyword(&keyword).succeeded())
1813 return p.emitError(loc, "unknown address space specifier '")
1814 << keyword << "'; expected 'target_address_space' or "
1815 << "'lang_address_space'";
1816
1817 return mlir::success();
1818}
1819
1820void printMemorySpace(mlir::AsmPrinter &p,
1821 mlir::ptr::MemorySpaceAttrInterface attr) {
1822 if (!attr)
1823 return;
1824
1825 if (auto language = dyn_cast<cir::LangAddressSpaceAttr>(attr)) {
1826 p << "lang_address_space("
1827 << cir::stringifyLangAddressSpace(language.getValue()) << ')';
1828 return;
1829 }
1830
1831 if (auto target = dyn_cast<cir::TargetAddressSpaceAttr>(attr)) {
1832 p << "target_address_space(" << target.getValue() << ')';
1833 return;
1834 }
1835
1836 llvm_unreachable("unexpected address-space attribute kind");
1837}
1838
1839mlir::OptionalParseResult
1841 mlir::ptr::MemorySpaceAttrInterface &attr) {
1842
1843 mlir::SMLoc loc = p.getCurrentLocation();
1844 if (parseMemorySpace(p, attr).failed())
1845 return p.emitError(loc, "failed to parse Address Space Value for GlobalOp");
1846 return mlir::success();
1847}
1848
1849void cir::printGlobalMemorySpace(mlir::AsmPrinter &printer, cir::GlobalOp,
1850 mlir::ptr::MemorySpaceAttrInterface attr) {
1851 printMemorySpace(printer, attr);
1852}
1853
1854mlir::ptr::MemorySpaceAttrInterface cir::normalizeDefaultAddressSpace(
1855 mlir::ptr::MemorySpaceAttrInterface addrSpace) {
1856 if (auto langAS =
1857 mlir::dyn_cast_if_present<cir::LangAddressSpaceAttr>(addrSpace))
1858 if (langAS.getValue() == cir::LangAddressSpace::Default)
1859 return {};
1860 return addrSpace;
1861}
1862
1863mlir::ptr::MemorySpaceAttrInterface
1864cir::toCIRAddressSpaceAttr(mlir::MLIRContext &ctx, clang::LangAS langAS) {
1865 using clang::LangAS;
1866
1867 if (langAS == LangAS::Default)
1868 return cir::LangAddressSpaceAttr::get(&ctx, cir::LangAddressSpace::Default);
1869
1870 if (clang::isTargetAddressSpace(langAS)) {
1871 unsigned targetAS = clang::toTargetAddressSpace(langAS);
1872 return cir::TargetAddressSpaceAttr::get(&ctx, targetAS);
1873 }
1874
1875 return cir::LangAddressSpaceAttr::get(&ctx, toCIRLangAddressSpace(langAS));
1876}
1877
1878bool cir::isMatchingAddressSpace(mlir::ptr::MemorySpaceAttrInterface cirAS,
1879 clang::LangAS as) {
1880 cirAS = normalizeDefaultAddressSpace(cirAS);
1881 if (!cirAS)
1882 return as == clang::LangAS::Default;
1883 mlir::ptr::MemorySpaceAttrInterface expected = normalizeDefaultAddressSpace(
1884 toCIRAddressSpaceAttr(*cirAS.getContext(), as));
1885 return expected == cirAS;
1886}
1887
1888//===----------------------------------------------------------------------===//
1889// PointerType Definitions
1890//===----------------------------------------------------------------------===//
1891
1892mlir::LogicalResult cir::PointerType::verify(
1893 llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
1894 mlir::Type pointee, mlir::ptr::MemorySpaceAttrInterface addrSpace) {
1895 if (addrSpace) {
1896 if (!isSupportedCIRMemorySpaceAttr(addrSpace)) {
1897 return emitError() << "unsupported address space attribute; expected "
1898 "'target_address_space' or 'lang_address_space'";
1899 }
1900 }
1901
1902 return success();
1903}
1904
1905//===----------------------------------------------------------------------===//
1906// CIR Dialect
1907//===----------------------------------------------------------------------===//
1908
1909void CIRDialect::registerTypes() {
1910 // Register tablegen'd types.
1911 addTypes<
1912#define GET_TYPEDEF_LIST
1913#include "clang/CIR/Dialect/IR/CIROpsTypes.cpp.inc"
1914 >();
1915
1916 // Register raw C++ types.
1917 // TODO(CIR) addTypes<RecordType>();
1918}
Provides definitions for the various language-specific address spaces.
mlir::ParseResult parseMemorySpace(mlir::AsmParser &p, mlir::ptr::MemorySpaceAttrInterface &attr)
static mlir::LogicalResult verifyRecordMemberTypes(function_ref< mlir::InFlightDiagnostic()> emitError, llvm::ArrayRef< mlir::Type > members)
Members must be CIR types other than void, which has no layout.
Definition CIRTypes.cpp:170
static const llvm::StringRef memberKindMarks[]
The keywords that spell a member kind.
Definition CIRTypes.cpp:185
static void printRecordBody(mlir::AsmPrinter &printer, RecordTy self, mlir::StringAttr name, bool hasClassPrefix, bool isPacked, bool isIncomplete, llvm::ArrayRef< mlir::Type > members, mlir::Type padding, llvm::ArrayRef< RecordMemberKind > memberKinds)
Print a complete CIR record body: '<' ['class '] [name] ['packed '] body '>' where body is "incomplet...
Definition CIRTypes.cpp:228
static mlir::LogicalResult verifyRecordMemberKinds(function_ref< mlir::InFlightDiagnostic()> emitError, size_t numMembers, llvm::ArrayRef< RecordMemberKind > memberKinds)
An incomplete record has no members, so a kind for one is caught by the same check.
Definition CIRTypes.cpp:159
static mlir::ParseResult parseFuncTypeParams(mlir::AsmParser &p, llvm::SmallVector< mlir::Type > &params, bool &isVarArg)
void printMemorySpace(mlir::AsmPrinter &printer, mlir::ptr::MemorySpaceAttrInterface attr)
static mlir::Type getMethodLayoutType(mlir::MLIRContext *ctx)
static void printFuncTypeParams(mlir::AsmPrinter &p, mlir::ArrayRef< mlir::Type > params, bool isVarArg)
static mlir::ParseResult parseRecordBody(mlir::AsmParser &parser, bool &incomplete, llvm::SmallVector< mlir::Type > &members, llvm::SmallVectorImpl< RecordMemberKind > &memberKinds)
Parse "incomplete" or "{mark type, mark type, ...}", writing results into incomplete,...
Definition CIRTypes.cpp:204
static std::optional< RecordMemberKind > parseMemberKind(mlir::AsmParser &parser)
Definition CIRTypes.cpp:189
static mlir::Type getDataMemberLayoutType(const mlir::DataLayout &dataLayout, mlir::MLIRContext *ctx)
static LiveVariablesImpl & getImpl(void *x)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
bool isLayoutIdentical(const RecordType &other)
Definition CIRTypes.cpp:712
bool isABIConvertedRecord() const
Definition CIRTypes.cpp:725
bool isIncomplete() const
Definition CIRTypes.cpp:658
bool isEmptyForABI() const
Whether no member holds data.
Definition CIRTypes.cpp:741
std::string getPrefixedName() const
Definition CIRTypes.cpp:693
llvm::ArrayRef< mlir::Type > getMembers() const
Definition CIRTypes.cpp:648
bool isClass() const
Definition CIRTypes.cpp:678
void removeABIConversionNamePrefix()
Definition CIRTypes.cpp:735
bool getPacked() const
Definition CIRTypes.cpp:663
static llvm::SmallVector< RecordMemberKind > getAllDataKinds(llvm::ArrayRef< mlir::Type > members)
One Data kind per member.
Definition CIRTypes.cpp:151
RecordType(StructType t)
Definition CIRTypes.h:158
mlir::StringAttr getName() const
Definition CIRTypes.cpp:653
void complete(llvm::ArrayRef< mlir::Type > members, bool packed, mlir::Type padding, llvm::ArrayRef< RecordMemberKind > memberKinds)
padding is union-only.
Definition CIRTypes.cpp:696
mlir::StringAttr getABIConvertedName() const
Definition CIRTypes.cpp:730
std::string getKindAsStr() const
Definition CIRTypes.cpp:688
bool isStruct() const
Definition CIRTypes.cpp:683
bool getPadded() const
Definition CIRTypes.cpp:668
llvm::ArrayRef< RecordMemberKind > getMemberKinds() const
Definition CIRTypes.cpp:673
uint64_t getElementOffset(const mlir::DataLayout &dataLayout, unsigned idx) const
Definition CIRTypes.cpp:706
bool isMatchingAddressSpace(mlir::ptr::MemorySpaceAttrInterface cirAS, clang::LangAS as)
cir::LangAddressSpace toCIRLangAddressSpace(clang::LangAS langAS)
mlir::Type memberStorageType(mlir::Type memberTy)
The storage a member is stored as: the access unit for a bit-field member, and the member type itself...
Definition CIRTypes.h:135
bool memberOwnsBytes(mlir::Type memberTy)
Whether a record member occupies bytes of its record.
Definition CIRTypes.h:126
bool isValidFundamentalIntWidth(unsigned width)
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:43
mlir::ptr::MemorySpaceAttrInterface toCIRAddressSpaceAttr(mlir::MLIRContext &ctx, clang::LangAS langAS)
Convert an AST LangAS to the appropriate CIR address space attribute interface.
mlir::OptionalParseResult parseGlobalMemorySpace(mlir::AsmParser &p, mlir::ptr::MemorySpaceAttrInterface &attr)
bool anyMemberHoldsDataForABI(llvm::ArrayRef< RecordMemberKind > kinds)
Whether any member holds data for argument passing on its mark alone.
Definition CIRTypes.h:53
mlir::ptr::MemorySpaceAttrInterface normalizeDefaultAddressSpace(mlir::ptr::MemorySpaceAttrInterface addrSpace)
Normalize LangAddressSpace::Default to null (empty attribute).
bool isSized(mlir::Type ty)
Returns true if the type is a CIR sized type.
Definition CIRTypes.cpp:36
void printGlobalMemorySpace(mlir::AsmPrinter &printer, cir::GlobalOp op, mlir::ptr::MemorySpaceAttrInterface attr)
bool isSupportedCIRMemorySpaceAttr(mlir::ptr::MemorySpaceAttrInterface memorySpace)
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
StringRef getName(const HeaderType T)
Definition HeaderFile.h:38
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
bool isTargetAddressSpace(LangAS AS)
unsigned toTargetAddressSpace(LangAS AS)
LangAS
Defines the address space values used by the address space qualifier of QualType.
float __ovld __cnfn sign(float)
Returns 1.0 if x > 0, -0.0 if x = -0.0, +0.0 if x = +0.0, or -1.0 if x < 0.
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
#define true
Definition stdbool.h:25
static bool unsizedTypes()
static bool dataLayoutPtrHandlingBasedOnLangAS()
static bool astRecordDeclAttr()