clang 24.0.0git
CIRAttrs.cpp
Go to the documentation of this file.
1//===- CIRAttrs.cpp - MLIR CIR Attributes ---------------------------------===//
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 attributes in the CIR dialect.
10//
11//===----------------------------------------------------------------------===//
12
13#include "mlir/Dialect/Ptr/IR/MemorySpaceInterfaces.h"
15
16#include "mlir/IR/Attributes.h"
17#include "mlir/IR/DialectImplementation.h"
18#include "llvm/Support/MathExtras.h"
19
20//===-----------------------------------------------------------------===//
21// RecordMembers
22//===-----------------------------------------------------------------===//
23
24static void printRecordMembers(mlir::AsmPrinter &p, mlir::ArrayAttr members);
25static mlir::ParseResult parseRecordMembers(mlir::AsmParser &parser,
26 mlir::ArrayAttr &members);
27
28//===-----------------------------------------------------------------===//
29// IntLiteral
30//===-----------------------------------------------------------------===//
31
32static void printIntLiteral(mlir::AsmPrinter &p, llvm::APInt value,
33 cir::IntTypeInterface ty);
34static mlir::ParseResult parseIntLiteral(mlir::AsmParser &parser,
35 llvm::APInt &value,
36 cir::IntTypeInterface ty);
37//===-----------------------------------------------------------------===//
38// FloatLiteral
39//===-----------------------------------------------------------------===//
40
41static void printFloatLiteral(mlir::AsmPrinter &p, llvm::APFloat value,
42 mlir::Type ty);
43static mlir::ParseResult
44parseFloatLiteral(mlir::AsmParser &parser,
45 mlir::FailureOr<llvm::APFloat> &value,
46 cir::FPTypeInterface fpType);
47
48static mlir::ParseResult parseConstPtr(mlir::AsmParser &parser,
49 mlir::IntegerAttr &value);
50
51static void printConstPtr(mlir::AsmPrinter &p, mlir::IntegerAttr value);
52
53static mlir::ParseResult
54parseDataMemberPath(mlir::AsmParser &parser,
55 mlir::DenseI32ArrayAttr &memberPath);
56
57static void printDataMemberPath(mlir::AsmPrinter &p,
58 mlir::DenseI32ArrayAttr memberPath);
59
60#define GET_ATTRDEF_CLASSES
61#include "clang/CIR/Dialect/IR/CIROpsAttributes.cpp.inc"
62
63using namespace mlir;
64using namespace cir;
65
66//===----------------------------------------------------------------------===//
67// MemorySpaceAttrInterface implementations for Lang and Target address space
68// attributes
69//===----------------------------------------------------------------------===//
70
71bool LangAddressSpaceAttr::isValidLoad(
72 mlir::Type type, mlir::ptr::AtomicOrdering ordering,
73 std::optional<int64_t> alignment, const mlir::DataLayout *dataLayout,
74 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) const {
75 llvm_unreachable("isValidLoad for LangAddressSpaceAttr NYI");
76}
77
78bool LangAddressSpaceAttr::isValidStore(
79 mlir::Type type, mlir::ptr::AtomicOrdering ordering,
80 std::optional<int64_t> alignment, const mlir::DataLayout *dataLayout,
81 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) const {
82 llvm_unreachable("isValidStore for LangAddressSpaceAttr NYI");
83}
84
85bool LangAddressSpaceAttr::isValidAtomicOp(
86 mlir::ptr::AtomicBinOp op, mlir::Type type,
87 mlir::ptr::AtomicOrdering ordering, std::optional<int64_t> alignment,
88 const mlir::DataLayout *dataLayout,
89 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) const {
90 llvm_unreachable("isValidAtomicOp for LangAddressSpaceAttr NYI");
91}
92
93bool LangAddressSpaceAttr::isValidAtomicXchg(
94 mlir::Type type, mlir::ptr::AtomicOrdering successOrdering,
95 mlir::ptr::AtomicOrdering failureOrdering, std::optional<int64_t> alignment,
96 const mlir::DataLayout *dataLayout,
97 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) const {
98 llvm_unreachable("isValidAtomicXchg for LangAddressSpaceAttr NYI");
99}
100
101bool LangAddressSpaceAttr::isValidAddrSpaceCast(
102 mlir::Type tgt, mlir::Type src,
103 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) const {
104 llvm_unreachable("isValidAddrSpaceCast for LangAddressSpaceAttr NYI");
105}
106
107bool LangAddressSpaceAttr::isValidPtrIntCast(
108 mlir::Type intLikeTy, mlir::Type ptrLikeTy,
109 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) const {
110 llvm_unreachable("isValidPtrIntCast for LangAddressSpaceAttr NYI");
111}
112
113bool TargetAddressSpaceAttr::isValidLoad(
114 mlir::Type type, mlir::ptr::AtomicOrdering ordering,
115 std::optional<int64_t> alignment, const mlir::DataLayout *dataLayout,
116 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) const {
117 llvm_unreachable("isValidLoad for TargetAddressSpaceAttr NYI");
118}
119
120bool TargetAddressSpaceAttr::isValidStore(
121 mlir::Type type, mlir::ptr::AtomicOrdering ordering,
122 std::optional<int64_t> alignment, const mlir::DataLayout *dataLayout,
123 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) const {
124 llvm_unreachable("isValidStore for TargetAddressSpaceAttr NYI");
125}
126
127bool TargetAddressSpaceAttr::isValidAtomicOp(
128 mlir::ptr::AtomicBinOp op, mlir::Type type,
129 mlir::ptr::AtomicOrdering ordering, std::optional<int64_t> alignment,
130 const mlir::DataLayout *dataLayout,
131 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) const {
132 llvm_unreachable("isValidAtomicOp for TargetAddressSpaceAttr NYI");
133}
134
135bool TargetAddressSpaceAttr::isValidAtomicXchg(
136 mlir::Type type, mlir::ptr::AtomicOrdering successOrdering,
137 mlir::ptr::AtomicOrdering failureOrdering, std::optional<int64_t> alignment,
138 const mlir::DataLayout *dataLayout,
139 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) const {
140 llvm_unreachable("isValidAtomicXchg for TargetAddressSpaceAttr NYI");
141}
142
143bool TargetAddressSpaceAttr::isValidAddrSpaceCast(
144 mlir::Type tgt, mlir::Type src,
145 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) const {
146 llvm_unreachable("isValidAddrSpaceCast for TargetAddressSpaceAttr NYI");
147}
148
149bool TargetAddressSpaceAttr::isValidPtrIntCast(
150 mlir::Type intLikeTy, mlir::Type ptrLikeTy,
151 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) const {
152 llvm_unreachable("isValidPtrIntCast for TargetAddressSpaceAttr NYI");
153}
154
155//===----------------------------------------------------------------------===//
156// PtrSpecAttr definitions
157//===----------------------------------------------------------------------===//
158
159LogicalResult PtrSpecAttr::verify(function_ref<InFlightDiagnostic()> emitError,
160 uint32_t size, uint32_t abi,
161 uint32_t preferred, uint32_t index) {
162 constexpr unsigned kBitsInByte = 8;
163 if (size % kBitsInByte != 0)
164 return emitError() << "size entry must be divisible by 8";
165 if (abi % kBitsInByte != 0)
166 return emitError() << "abi entry must be divisible by 8";
167 if (preferred % kBitsInByte != 0)
168 return emitError() << "preferred entry must be divisible by 8";
169 if (index != kOptionalSpecValue && index % kBitsInByte != 0)
170 return emitError() << "index entry must be divisible by 8";
171 if (abi > preferred)
172 return emitError() << "preferred alignment is expected to be at least "
173 "as large as ABI alignment";
174 return success();
175}
176
177//===----------------------------------------------------------------------===//
178// BitIntSpecAttr definitions
179//===----------------------------------------------------------------------===//
180
181LogicalResult
182BitIntSpecAttr::verify(function_ref<InFlightDiagnostic()> emitError,
183 uint32_t maxAlign) {
184 // TargetInfo::getBitIntMaxAlign() is a power of two, at least the char
185 // width. Char width is 8 bits.
186 if (maxAlign < 8 || !llvm::isPowerOf2_32(maxAlign))
187 return emitError() << "max_align must be a power of two of at least 8";
188 return success();
189}
190
191//===----------------------------------------------------------------------===//
192// VectorSpecAttr definitions
193//===----------------------------------------------------------------------===//
194
195LogicalResult
196VectorSpecAttr::verify(function_ref<InFlightDiagnostic()> emitError,
197 uint32_t maxAlign) {
198 // TargetInfo::getMaxVectorAlign() is a power of two, at least the char
199 // width, when the target imposes a cap. Char width is 8 bits.
200 if (maxAlign < 8 || !llvm::isPowerOf2_32(maxAlign))
201 return emitError() << "max_align must be a power of two of at least 8";
202 return success();
203}
204
205//===----------------------------------------------------------------------===//
206// BitFieldDeclAttr definitions
207//===----------------------------------------------------------------------===//
208
209LogicalResult
210BitFieldDeclAttr::verify(function_ref<InFlightDiagnostic()> emitError,
211 mlir::Type declaredType, uint64_t width,
212 bool isUnnamed) {
213 if (width == 0 && !isUnnamed)
214 return emitError() << "zero-width bit-field cannot be named";
215 return success();
216}
217
218//===----------------------------------------------------------------------===//
219// General CIR parsing / printing
220//===----------------------------------------------------------------------===//
221
222static void printRecordMembers(mlir::AsmPrinter &printer,
223 mlir::ArrayAttr members) {
224 printer << '{';
225 llvm::interleaveComma(members, printer);
226 printer << '}';
227}
228
229static ParseResult parseRecordMembers(mlir::AsmParser &parser,
230 mlir::ArrayAttr &members) {
232
233 auto delimiter = AsmParser::Delimiter::Braces;
234 auto result = parser.parseCommaSeparatedList(delimiter, [&]() {
235 mlir::TypedAttr attr;
236 if (parser.parseAttribute(attr).failed())
237 return mlir::failure();
238 elts.push_back(attr);
239 return mlir::success();
240 });
241
242 if (result.failed())
243 return mlir::failure();
244
245 members = mlir::ArrayAttr::get(parser.getContext(), elts);
246 return mlir::success();
247}
248
249//===----------------------------------------------------------------------===//
250// ConstRecordAttr definitions
251//===----------------------------------------------------------------------===//
252
253static bool isValidFlexibleArrayInit(mlir::Type memberType,
254 mlir::Type initType) {
255 auto memberArrayType = mlir::dyn_cast<cir::ArrayType>(memberType);
256 auto initArrayType = mlir::dyn_cast<cir::ArrayType>(initType);
257 return memberArrayType && memberArrayType.getSize() == 0 && initArrayType &&
258 memberArrayType.getElementType() == initArrayType.getElementType();
259}
260
261LogicalResult
262ConstRecordAttr::verify(function_ref<InFlightDiagnostic()> emitError,
263 mlir::Type type, ArrayAttr members) {
264 auto sTy = mlir::dyn_cast_if_present<cir::RecordType>(type);
265 if (!sTy)
266 return emitError() << "expected !cir.struct or !cir.union type";
267
268 // union record initializer is just a single element that has to match one of
269 // the fields in the union (the new active member).
270 if (sTy.isUnion()) {
271 if (members.size() != 1)
272 return emitError() << "union constant must have exactly one element, got "
273 << members.size();
274 auto m = mlir::cast<mlir::TypedAttr>(members[0]);
275 // A bit-field variant is initialized as the access unit it owns.
276 if (!llvm::any_of(sTy.getMembers(), [&](mlir::Type memberTy) {
277 mlir::Type storageType = cir::memberStorageType(memberTy);
278 return storageType == m.getType() ||
279 isValidFlexibleArrayInit(storageType, m.getType());
280 }))
281 return emitError() << "union element type " << m.getType()
282 << " is not a member of " << sTy;
283 return success();
284 }
285
286 // A member that owns no bytes is not stored, so it takes no element. A
287 // bit-field's bits are packed into the element of the member that owns its
288 // access unit, and a zero-width bit-field has no bits to store at all.
289 llvm::SmallVector<mlir::Type> storedMembers;
290 for (mlir::Type memberTy : sTy.getMembers())
291 if (cir::memberOwnsBytes(memberTy))
292 storedMembers.push_back(cir::memberStorageType(memberTy));
293
294 if (storedMembers.size() != members.size())
295 return emitError() << "number of elements must match";
296
297 for (const auto &[attrIdx, member] : llvm::enumerate(storedMembers)) {
298 auto m = mlir::cast<mlir::TypedAttr>(members[attrIdx]);
299
300 // As a special case, we allow a flexible array member. This can only be the
301 // last element, the rest of the array type has to match (that is, the
302 // element type has to match), and the array member must be size zero.
303 if (attrIdx == storedMembers.size() - 1) {
304 auto memArrayTy = dyn_cast<cir::ArrayType>(member);
305 if (memArrayTy && memArrayTy.getSize() == 0) {
306
307 // The FAM must only match another array type initializer.
308 if (!isa<cir::ArrayType>(m.getType()))
309 return emitError()
310 << "element at index " << attrIdx << " has type "
311 << m.getType() << " but the expected type for this element is "
312 << member;
313
314 cir::ArrayType initArrayTy = cast<cir::ArrayType>(m.getType());
315 // The FAM only matches an equivalent array type.
316 if (initArrayTy.getElementType() != memArrayTy.getElementType())
317 return emitError()
318 << "flexible array member at index " << attrIdx << " has type "
319 << m.getType()
320 << " which doesn't match the expected element type of member "
321 << member;
322 continue;
323 }
324 }
325
326 if (member != m.getType())
327 return emitError() << "element at index " << attrIdx << " has type "
328 << m.getType()
329 << " but the expected type for this element is "
330 << member;
331 }
332
333 return success();
334}
335
336//===----------------------------------------------------------------------===//
337// LoopHintAttr definitions
338//===----------------------------------------------------------------------===//
339
340LogicalResult LoopHintAttr::verify(
341 function_ref<InFlightDiagnostic()> emitError, mlir::UnitAttr mustProgress,
342 mlir::BoolAttr vectorizeEnable, uint32_t vectorizeWidth,
343 mlir::BoolAttr vectorizeScalable, mlir::BoolAttr vectorizePredicate,
344 uint32_t interleaveCount, std::optional<cir::LoopUnrollMode> unroll,
345 uint32_t unrollCount, std::optional<cir::LoopUnrollMode> unrollAndJam,
346 uint32_t unrollAndJamCount, mlir::BoolAttr distribute,
347 mlir::UnitAttr pipelineDisabled, uint32_t pipelineInitiationInterval,
348 mlir::UnitAttr licmDisabled, mlir::UnitAttr parallel, uint32_t codeAlign,
349 mlir::UnitAttr vectorized, mlir::Attribute unrollAndJamInner) {
350 if (!unrollAndJamInner)
351 return success();
352
353 auto inner = mlir::dyn_cast<LoopHintAttr>(unrollAndJamInner);
354 if (!inner)
355 return emitError() << "'unroll_and_jam_inner' must be a '#cir.loop_hint'";
356
357 if (!unrollAndJam && !unrollAndJamCount)
358 return emitError() << "'unroll_and_jam_inner' requires the loop to be "
359 "unrolled and jammed";
360
361 if (inner.getUnrollAndJamInner())
362 return emitError() << "'unroll_and_jam_inner' can't have its own "
363 "'unroll_and_jam_inner'";
364 return success();
365}
366
367//===----------------------------------------------------------------------===//
368// OptInfoAttr definitions
369//===----------------------------------------------------------------------===//
370
371LogicalResult OptInfoAttr::verify(function_ref<InFlightDiagnostic()> emitError,
372 unsigned level, unsigned size) {
373 if (level > 3)
374 return emitError()
375 << "optimization level must be between 0 and 3 inclusive";
376 if (size > 2)
377 return emitError()
378 << "size optimization level must be between 0 and 2 inclusive";
379 return success();
380}
381
382//===----------------------------------------------------------------------===//
383// ConstPtrAttr definitions
384//===----------------------------------------------------------------------===//
385
386// TODO(CIR): Consider encoding the null value differently and use conditional
387// assembly format instead of custom parsing/printing.
388static ParseResult parseConstPtr(AsmParser &parser, mlir::IntegerAttr &value) {
389
390 if (parser.parseOptionalKeyword("null").succeeded()) {
391 value = parser.getBuilder().getI64IntegerAttr(0);
392 return success();
393 }
394
395 return parser.parseAttribute(value);
396}
397
398static void printConstPtr(AsmPrinter &p, mlir::IntegerAttr value) {
399 if (!value.getInt())
400 p << "null";
401 else
402 p << value;
403}
404
405static ParseResult parseDataMemberPath(AsmParser &parser,
406 mlir::DenseI32ArrayAttr &memberPath) {
407 if (parser.parseOptionalKeyword("null").succeeded())
408 return success();
409
410 auto parsed = mlir::FieldParser<mlir::DenseI32ArrayAttr>::parse(parser);
411 if (mlir::failed(parsed))
412 return failure();
413 memberPath = *parsed;
414 return success();
415}
416
417static void printDataMemberPath(AsmPrinter &p,
418 mlir::DenseI32ArrayAttr memberPath) {
419 if (!memberPath)
420 p << "null";
421 else
422 p.printStrippedAttrOrType(memberPath);
423}
424
425//===----------------------------------------------------------------------===//
426// IntAttr definitions
427//===----------------------------------------------------------------------===//
428
429mlir::ParseResult parseIntLiteral(mlir::AsmParser &parser, llvm::APInt &value,
430 cir::IntTypeInterface ty) {
431 llvm::SMLoc loc = parser.getCurrentLocation();
432 llvm::APInt parsed;
433 mlir::OptionalParseResult result = parser.parseOptionalInteger(parsed);
434 if (!result.has_value() || failed(*result))
435 return parser.emitError(loc, "expected integer value");
436
437 const unsigned width = ty.getWidth();
438 const bool fits =
439 ty.isSigned() ? parsed.getSignificantBits() <= width
440 : !parsed.isNegative() && parsed.getActiveBits() <= width;
441 if (!fits)
442 return parser.emitError(loc, "integer value too large for the given type");
443
444 value = ty.isSigned() ? parsed.sextOrTrunc(width) : parsed.zextOrTrunc(width);
445 return success();
446}
447
448void printIntLiteral(mlir::AsmPrinter &p, llvm::APInt value,
449 cir::IntTypeInterface ty) {
451 value.toString(str, /*radix=*/10, /*isSigned=*/ty.isSigned());
452 p << str;
453}
454
455LogicalResult IntAttr::verify(function_ref<InFlightDiagnostic()> emitError,
456 cir::IntTypeInterface type, llvm::APInt value) {
457 if (value.getBitWidth() != type.getWidth())
458 return emitError() << "type and value bitwidth mismatch: "
459 << type.getWidth() << " != " << value.getBitWidth();
460 return success();
461}
462
463//===----------------------------------------------------------------------===//
464// FPAttr definitions
465//===----------------------------------------------------------------------===//
466
467static void printFloatLiteral(AsmPrinter &p, APFloat value, Type ty) {
468 p << value;
469}
470
471static ParseResult parseFloatLiteral(AsmParser &parser,
472 FailureOr<APFloat> &value,
473 cir::FPTypeInterface fpType) {
474
475 APFloat parsedValue(0.0);
476 if (parser.parseFloat(fpType.getFloatSemantics(), parsedValue))
477 return failure();
478
479 value.emplace(parsedValue);
480 return success();
481}
482
483//===----------------------------------------------------------------------===//
484// MemoryEffectsAttr definitions
485//===----------------------------------------------------------------------===//
486
487MemoryEffectsAttr MemoryEffectsAttr::none(MLIRContext *ctx) {
488 return get(ctx, ModRefInfo::NoModRef);
489}
490
491MemoryEffectsAttr MemoryEffectsAttr::readOnly(MLIRContext *ctx) {
492 return get(ctx, ModRefInfo::Ref);
493}
494
495MemoryEffectsAttr MemoryEffectsAttr::writeOnly(MLIRContext *ctx) {
496 return get(ctx, ModRefInfo::Mod);
497}
498
499MemoryEffectsAttr MemoryEffectsAttr::argMemOnly(MLIRContext *ctx,
500 ModRefInfo mr) {
501 return get(ctx, /*other=*/ModRefInfo::NoModRef, /*arg_mem=*/mr,
502 /*inaccessible_mem=*/ModRefInfo::NoModRef,
503 /*errno_mem=*/ModRefInfo::NoModRef,
504 /*target_mem0=*/ModRefInfo::NoModRef,
505 /*target_mem1=*/ModRefInfo::NoModRef);
506}
507
508MemoryEffectsAttr MemoryEffectsAttr::inaccessibleMemOnly(MLIRContext *ctx,
509 ModRefInfo mr) {
510 return get(ctx, /*other=*/ModRefInfo::NoModRef,
511 /*arg_mem=*/ModRefInfo::NoModRef, /*inaccessible_mem=*/mr,
512 /*errno_mem=*/ModRefInfo::NoModRef,
513 /*target_mem0=*/ModRefInfo::NoModRef,
514 /*target_mem1=*/ModRefInfo::NoModRef);
515}
516
517MemoryEffectsAttr MemoryEffectsAttr::errnoMemOnly(MLIRContext *ctx,
518 ModRefInfo mr) {
519 return get(ctx, /*other=*/ModRefInfo::NoModRef,
520 /*arg_mem=*/ModRefInfo::NoModRef,
521 /*inaccessible_mem=*/ModRefInfo::NoModRef, /*errno_mem=*/mr,
522 /*target_mem0=*/ModRefInfo::NoModRef,
523 /*target_mem1=*/ModRefInfo::NoModRef);
524}
525
526MemoryEffectsAttr MemoryEffectsAttr::otherMemOnly(MLIRContext *ctx,
527 ModRefInfo mr) {
528 return get(ctx, /*other=*/mr, /*arg_mem=*/ModRefInfo::NoModRef,
529 /*inaccessible_mem=*/ModRefInfo::NoModRef,
530 /*errno_mem=*/ModRefInfo::NoModRef,
531 /*target_mem0=*/ModRefInfo::NoModRef,
532 /*target_mem1=*/ModRefInfo::NoModRef);
533}
534
535MemoryEffectsAttr MemoryEffectsAttr::inaccessibleOrArgMemOnly(MLIRContext *ctx,
536 ModRefInfo mr) {
537 return get(ctx, /*other=*/ModRefInfo::NoModRef, /*arg_mem=*/mr,
538 /*inaccessible_mem=*/mr, /*errno_mem=*/ModRefInfo::NoModRef,
539 /*target_mem0=*/ModRefInfo::NoModRef,
540 /*target_mem1=*/ModRefInfo::NoModRef);
541}
542
543MemoryEffectsAttr MemoryEffectsAttr::inaccessibleOrErrnoMemOnly(
544 MLIRContext *ctx, ModRefInfo inaccessibleMr, ModRefInfo errnoMr) {
545 return get(ctx, /*other=*/ModRefInfo::NoModRef,
546 /*arg_mem=*/ModRefInfo::NoModRef,
547 /*inaccessible_mem=*/inaccessibleMr, /*errno_mem=*/errnoMr,
548 /*target_mem0=*/ModRefInfo::NoModRef,
549 /*target_mem1=*/ModRefInfo::NoModRef);
550}
551
552MemoryEffectsAttr MemoryEffectsAttr::inaccessibleOrArgOrErrnoMemOnly(
553 MLIRContext *ctx, ModRefInfo inaccessibleOrArgMr, ModRefInfo errnoMr) {
554 return get(ctx, /*other=*/ModRefInfo::NoModRef,
555 /*arg_mem=*/inaccessibleOrArgMr,
556 /*inaccessible_mem=*/inaccessibleOrArgMr, /*errno_mem=*/errnoMr,
557 /*target_mem0=*/ModRefInfo::NoModRef,
558 /*target_mem1=*/ModRefInfo::NoModRef);
559}
560
561MemoryEffectsAttr
562MemoryEffectsAttr::argumentOrErrnoMemOnly(MLIRContext *ctx, ModRefInfo argMr,
563 ModRefInfo errnoMr) {
564 return get(ctx, /*other=*/ModRefInfo::NoModRef, /*arg_mem=*/argMr,
565 /*inaccessible_mem=*/ModRefInfo::NoModRef, /*errno_mem=*/errnoMr,
566 /*target_mem0=*/ModRefInfo::NoModRef,
567 /*target_mem1=*/ModRefInfo::NoModRef);
568}
569
570FPAttr FPAttr::getZero(Type type) {
571 return get(type,
572 APFloat::getZero(
573 mlir::cast<cir::FPTypeInterface>(type).getFloatSemantics()));
574}
575
576LogicalResult FPAttr::verify(function_ref<InFlightDiagnostic()> emitError,
577 cir::FPTypeInterface fpType, APFloat value) {
578 if (APFloat::SemanticsToEnum(fpType.getFloatSemantics()) !=
579 APFloat::SemanticsToEnum(value.getSemantics()))
580 return emitError() << "floating-point semantics mismatch";
581
582 return success();
583}
584
585//===----------------------------------------------------------------------===//
586// CmpThreeWayInfoAttr definitions
587//===----------------------------------------------------------------------===//
588
589std::string CmpThreeWayInfoAttr::getAlias() const {
590 std::string alias = "cmpinfo";
591
592 switch (getOrdering()) {
593 case CmpOrdering::Strong:
594 alias.append("_strong_");
595 break;
596 case CmpOrdering::Weak:
597 alias.append("_weak_");
598 break;
599 case CmpOrdering::Partial:
600 alias.append("_partial_");
601 break;
602 }
603
604 auto appendInt = [&](int64_t value) {
605 if (value < 0) {
606 alias.push_back('n');
607 value = -value;
608 }
609 alias.append(std::to_string(value));
610 };
611
612 alias.append("lt");
613 appendInt(getLt());
614 alias.append("eq");
615 appendInt(getEq());
616 alias.append("gt");
617 appendInt(getGt());
618
619 if (std::optional<int> unordered = getUnordered()) {
620 alias.append("un");
621 appendInt(unordered.value());
622 }
623
624 return alias;
625}
626
627LogicalResult
628CmpThreeWayInfoAttr::verify(function_ref<InFlightDiagnostic()> emitError,
629 CmpOrdering ordering, int64_t lt, int64_t eq,
630 int64_t gt, std::optional<int64_t> unordered) {
631 // The presence of unordered must match the value of ordering.
632 if ((ordering == CmpOrdering::Strong || ordering == CmpOrdering::Weak) &&
633 unordered) {
634 emitError() << "strong and weak ordering do not include unordered";
635 return failure();
636 }
637 if (ordering == CmpOrdering::Partial && !unordered) {
638 emitError() << "partial ordering requires unordered value";
639 return failure();
640 }
641
642 return success();
643}
644
645//===----------------------------------------------------------------------===//
646// ConstComplexAttr definitions
647//===----------------------------------------------------------------------===//
648
649LogicalResult
650ConstComplexAttr::verify(function_ref<InFlightDiagnostic()> emitError,
651 cir::ComplexType type, mlir::TypedAttr real,
652 mlir::TypedAttr imag) {
653 mlir::Type elemType = type.getElementType();
654 if (real.getType() != elemType)
655 return emitError()
656 << "type of the real part does not match the complex type";
657
658 if (imag.getType() != elemType)
659 return emitError()
660 << "type of the imaginary part does not match the complex type";
661
662 return success();
663}
664
665//===----------------------------------------------------------------------===//
666// CIR_CUDAVarRegistrationInfoAttr definitions
667//===----------------------------------------------------------------------===//
668
669void CUDAVarRegistrationInfoAttr::print(AsmPrinter &p) const {
670 p << "<" << getDeviceSideName();
671 p << ", " << stringifyEnum(getKind());
672 if (getIsExtern())
673 p << ", extern";
674 if (getIsConstant())
675 p << ", constant";
676 if (getIsManaged())
677 p << ", managed";
678 if (getKind() == CUDADeviceVarKind::Surface)
679 p << ", surface_type = " << getSurfTexType();
680 else if (getKind() == CUDADeviceVarKind::Texture) {
681 p << ", texture_type = " << getSurfTexType();
682 if (getNormalized())
683 p << ", normalized";
684 }
685 p << ">";
686}
687
688Attribute CUDAVarRegistrationInfoAttr::parse(AsmParser &parser, Type odsType) {
689 if (parser.parseLess())
690 return {};
691
692 std::string deviceSideName;
693 if (parser.parseKeywordOrString(&deviceSideName)) {
694 parser.emitError(parser.getCurrentLocation(),
695 "expected device variable name");
696 return {};
697 }
698
699 if (parser.parseComma())
700 return {};
701
702 // Parse the device variable kind (Variable, Surface, Texture)
703 StringRef kindStr;
704 if (parser.parseKeyword(&kindStr))
705 return {};
706
707 std::optional<CUDADeviceVarKind> kind = symbolizeCUDADeviceVarKind(kindStr);
708 if (!kind) {
709 parser.emitError(parser.getCurrentLocation(),
710 "unknown device variable kind: ")
711 << kindStr;
712 return {};
713 }
714
715 // Parse optional flags: extern, constant, managed
716 bool isExtern = false;
717 bool isConstant = false;
718 bool isManaged = false;
719 int32_t surfTexType = 0;
720 bool normalized = false;
721
722 while (parser.parseOptionalGreater().failed()) {
723 if (parser.parseComma())
724 return {};
725
726 StringRef flag;
727 if (parser.parseKeyword(&flag))
728 return {};
729
730 if (flag == "extern")
731 isExtern = true;
732 else if (flag == "constant")
733 isConstant = true;
734 else if (flag == "managed")
735 isManaged = true;
736 else if (flag == "normalized") {
737 if (*kind != CUDADeviceVarKind::Texture) {
738 parser.emitError(parser.getCurrentLocation(),
739 "'normalized' is only valid for Texture");
740 return {};
741 }
742 normalized = true;
743 } else if (flag == "surface_type") {
744 if (*kind != CUDADeviceVarKind::Surface) {
745 parser.emitError(parser.getCurrentLocation(),
746 "'surface_type' is only valid for Surface");
747 return {};
748 }
749 if (parser.parseEqual() || parser.parseInteger(surfTexType))
750 return {};
751 } else if (flag == "texture_type") {
752 if (*kind != CUDADeviceVarKind::Texture) {
753 parser.emitError(parser.getCurrentLocation(),
754 "'texture_type' is only valid for Texture");
755 return {};
756 }
757 if (parser.parseEqual() || parser.parseInteger(surfTexType))
758 return {};
759 } else {
760 parser.emitError(parser.getCurrentLocation(), "unknown flag: ") << flag;
761 return {};
762 }
763 }
764
765 return get(parser.getContext(), deviceSideName, *kind, isExtern, isConstant,
766 isManaged, surfTexType, normalized);
767}
768
769//===----------------------------------------------------------------------===//
770// DataMemberAttr definitions
771//===----------------------------------------------------------------------===//
772
773LogicalResult
774DataMemberAttr::verify(function_ref<InFlightDiagnostic()> emitError,
775 cir::DataMemberType ty,
776 mlir::DenseI32ArrayAttr memberPath) {
777 if (!memberPath)
778 return success(); // null pointer — always valid
779
780 if (memberPath.empty())
781 return emitError() << "#cir.data_member path must not be empty";
782
783 mlir::Type currentTy = ty.getClassTy();
784 for (auto [step, idx] : llvm::enumerate(memberPath.asArrayRef())) {
785 auto recTy = mlir::dyn_cast<cir::RecordType>(currentTy);
786 if (!recTy)
787 return emitError() << "#cir.data_member path step " << step
788 << " reaches a non-record type";
789
790 if (recTy.isIncomplete())
791 return success(); // cannot validate further; trust the builder
792
793 if (idx < 0 || static_cast<unsigned>(idx) >= recTy.getNumElements())
794 return emitError() << "#cir.data_member path index " << idx << " at step "
795 << step << " is out of range";
796
797 currentTy = recTy.getMembers()[idx];
798 }
799
800 if (currentTy != ty.getMemberTy())
801 return emitError()
802 << "member type of a #cir.data_member attribute must match "
803 "the attribute type";
804
805 return success();
806}
807
808//===----------------------------------------------------------------------===//
809// MethodAttr definitions
810//===----------------------------------------------------------------------===//
811
812LogicalResult MethodAttr::verify(function_ref<InFlightDiagnostic()> emitError,
813 cir::MethodType type,
814 std::optional<FlatSymbolRefAttr> symbol,
815 std::optional<uint64_t> vtable_index) {
816 if (symbol.has_value() && vtable_index.has_value())
817 return emitError()
818 << "at most one of symbol and vtable_index can be present "
819 "in #cir.method";
820
821 return success();
822}
823
824Attribute MethodAttr::parse(AsmParser &parser, Type odsType) {
825 auto ty = mlir::cast<cir::MethodType>(odsType);
826
827 if (parser.parseLess().failed())
828 return {};
829
830 // Try to parse the null pointer constant.
831 if (parser.parseOptionalKeyword("null").succeeded()) {
832 if (parser.parseGreater().failed())
833 return {};
834 return get(ty);
835 }
836
837 // Try to parse a flat symbol ref for a pointer to non-virtual member
838 // function.
839 FlatSymbolRefAttr symbol;
840 mlir::OptionalParseResult parseSymbolRefResult =
841 parser.parseOptionalAttribute(symbol);
842 if (parseSymbolRefResult.has_value()) {
843 if (parseSymbolRefResult.value().failed())
844 return {};
845 if (parser.parseGreater().failed())
846 return {};
847 return get(ty, symbol);
848 }
849
850 // Parse a uint64 that represents the vtable index.
851 std::uint64_t vtableIndex = 0;
852 if (parser.parseKeyword("vtable_index"))
853 return {};
854 if (parser.parseEqual())
855 return {};
856 if (parser.parseInteger(vtableIndex))
857 return {};
858
859 if (parser.parseGreater())
860 return {};
861
862 return get(ty, vtableIndex);
863}
864
865void MethodAttr::print(AsmPrinter &printer) const {
866 auto symbol = getSymbol();
867 auto vtableIndex = getVtableIndex();
868
869 printer << '<';
870 if (symbol.has_value()) {
871 printer << *symbol;
872 } else if (vtableIndex.has_value()) {
873 printer << "vtable_index = " << *vtableIndex;
874 } else {
875 printer << "null";
876 }
877 printer << '>';
878}
879
880//===----------------------------------------------------------------------===//
881// CIR ConstArrayAttr
882//===----------------------------------------------------------------------===//
883
884LogicalResult
885ConstArrayAttr::verify(function_ref<InFlightDiagnostic()> emitError, Type type,
886 Attribute elts, int trailingZerosNum) {
887
888 if (!(mlir::isa<ArrayAttr, StringAttr>(elts)))
889 return emitError() << "constant array expects ArrayAttr or StringAttr";
890
891 if (auto strAttr = mlir::dyn_cast<StringAttr>(elts)) {
892 const auto arrayTy = mlir::cast<ArrayType>(type);
893 const auto intTy = mlir::dyn_cast<IntType>(arrayTy.getElementType());
894
895 // TODO: add CIR type for char.
896 if (!intTy || intTy.getWidth() != 8)
897 return emitError()
898 << "constant array element for string literals expects "
899 "!cir.int<u, 8> element type";
900 return success();
901 }
902
903 assert(mlir::isa<ArrayAttr>(elts));
904 const auto arrayAttr = mlir::cast<mlir::ArrayAttr>(elts);
905 const auto arrayTy = mlir::cast<ArrayType>(type);
906
907 // Make sure both number of elements and subelement types match type.
908 if (arrayAttr.size() > arrayTy.getSize())
909 return emitError() << "constant array has " << arrayAttr.size()
910 << " values but array type has size "
911 << arrayTy.getSize();
912 if (arrayTy.getSize() != arrayAttr.size() + trailingZerosNum)
913 return emitError() << "constant array size should match type size";
914 return success();
915}
916
917Attribute ConstArrayAttr::parse(AsmParser &parser, Type type) {
918 mlir::FailureOr<Type> resultTy;
919 mlir::FailureOr<Attribute> resultVal;
920
921 // Parse literal '<'
922 if (parser.parseLess())
923 return {};
924
925 // Parse variable 'value'
926 resultVal = FieldParser<Attribute>::parse(parser);
927 if (failed(resultVal)) {
928 parser.emitError(
929 parser.getCurrentLocation(),
930 "failed to parse ConstArrayAttr parameter 'value' which is "
931 "to be a `Attribute`");
932 return {};
933 }
934
935 // ArrayAttrrs have per-element type, not the type of the array...
936 if (mlir::isa<ArrayAttr>(*resultVal)) {
937 // Array has implicit type: infer from const array type.
938 if (parser.parseOptionalColon().failed()) {
939 resultTy = type;
940 } else { // Array has explicit type: parse it.
941 resultTy = FieldParser<Type>::parse(parser);
942 if (failed(resultTy)) {
943 parser.emitError(
944 parser.getCurrentLocation(),
945 "failed to parse ConstArrayAttr parameter 'type' which is "
946 "to be a `::mlir::Type`");
947 return {};
948 }
949 }
950 } else {
951 auto ta = mlir::cast<TypedAttr>(*resultVal);
952 resultTy = ta.getType();
953 if (mlir::isa<mlir::NoneType>(*resultTy)) {
954 parser.emitError(parser.getCurrentLocation(),
955 "expected type declaration for string literal");
956 return {};
957 }
958 }
959
960 unsigned zeros = 0;
961 if (parser.parseOptionalComma().succeeded()) {
962 if (parser.parseOptionalKeyword("trailing_zeros").succeeded()) {
963 unsigned totalSize = mlir::cast<cir::ArrayType>(type).getSize();
964 mlir::Attribute elts = resultVal.value();
965 if (auto str = mlir::dyn_cast<mlir::StringAttr>(elts))
966 zeros = totalSize - str.size();
967 else
968 zeros = totalSize - mlir::cast<mlir::ArrayAttr>(elts).size();
969 } else {
970 return {};
971 }
972 }
973
974 // Parse literal '>'
975 if (parser.parseGreater())
976 return {};
977
978 return parser.getChecked<ConstArrayAttr>(parser.getCurrentLocation(),
979 parser.getContext(), type,
980 resultVal.value(), zeros);
981}
982
983void ConstArrayAttr::print(AsmPrinter &printer) const {
984 printer << "<";
985 printer.printStrippedAttrOrType(getElts());
986 if (getTrailingZerosNum())
987 printer << ", trailing_zeros";
988 printer << ">";
989}
990
991//===----------------------------------------------------------------------===//
992// CIR ConstVectorAttr
993//===----------------------------------------------------------------------===//
994
995LogicalResult
996cir::ConstVectorAttr::verify(function_ref<InFlightDiagnostic()> emitError,
997 Type type, ArrayAttr elts) {
998
999 if (!mlir::isa<cir::VectorType>(type))
1000 return emitError() << "type of cir::ConstVectorAttr is not a "
1001 "cir::VectorType: "
1002 << type;
1003
1004 const auto vecType = mlir::cast<cir::VectorType>(type);
1005
1006 if (vecType.isScalable())
1007 return emitError() << "scalable vector constants are not supported";
1008
1009 if (vecType.getFixedSize() != elts.size())
1010 return emitError()
1011 << "number of constant elements should match vector size";
1012
1013 // Check if the types of the elements match
1014 LogicalResult elementTypeCheck = success();
1015 elts.walkImmediateSubElements(
1016 [&](Attribute element) {
1017 if (elementTypeCheck.failed()) {
1018 // An earlier element didn't match
1019 return;
1020 }
1021 auto typedElement = mlir::dyn_cast<TypedAttr>(element);
1022 if (!typedElement ||
1023 typedElement.getType() != vecType.getElementType()) {
1024 elementTypeCheck = failure();
1025 emitError() << "constant type should match vector element type";
1026 }
1027 },
1028 [&](Type) {});
1029
1030 return elementTypeCheck;
1031}
1032
1033//===----------------------------------------------------------------------===//
1034// CIR VTableAttr
1035//===----------------------------------------------------------------------===//
1036
1037LogicalResult cir::VTableAttr::verify(
1038 llvm::function_ref<mlir::InFlightDiagnostic()> emitError, mlir::Type type,
1039 mlir::ArrayAttr data, mlir::ArrayAttr addressPoints) {
1040 auto sTy = mlir::dyn_cast_if_present<cir::RecordType>(type);
1041 if (!sTy)
1042 return emitError() << "expected !cir.struct or !cir.union type result";
1043 if (sTy.getMembers().empty() || data.empty())
1044 return emitError() << "expected record type with one or more subtype";
1045
1046 if (cir::ConstRecordAttr::verify(emitError, type, data).failed())
1047 return failure();
1048
1049 if (addressPoints.size() != data.size())
1050 return emitError() << "expected one address point for each vtable, got "
1051 << addressPoints.size() << " for " << data.size()
1052 << " vtables";
1053
1054 for (const auto &[idx, element] :
1055 llvm::enumerate(data.getAsRange<mlir::Attribute>())) {
1056 const auto &constArrayAttr = mlir::dyn_cast<cir::ConstArrayAttr>(element);
1057 if (!constArrayAttr)
1058 return emitError() << "expected constant array subtype";
1059
1060 auto arrayTy = mlir::cast<cir::ArrayType>(constArrayAttr.getType());
1061 auto addressPoint =
1062 mlir::dyn_cast<cir::AddressPointAttr>(addressPoints[idx]);
1063 if (!addressPoint)
1064 return emitError() << "expected an address point for vtable " << idx;
1065 if (addressPoint.getIndex() != static_cast<int32_t>(idx))
1066 return emitError() << "address point " << idx << " refers to vtable "
1067 << addressPoint.getIndex();
1068 if (addressPoint.getOffset() < 0 ||
1069 static_cast<uint64_t>(addressPoint.getOffset()) > arrayTy.getSize())
1070 return emitError() << "address point offset " << addressPoint.getOffset()
1071 << " is out of range of vtable " << idx;
1072
1073 LogicalResult eltTypeCheck = success();
1074 auto arrayElts = mlir::cast<ArrayAttr>(constArrayAttr.getElts());
1075 arrayElts.walkImmediateSubElements(
1076 [&](mlir::Attribute attr) {
1077 if (mlir::isa<ConstPtrAttr, GlobalViewAttr>(attr))
1078 return;
1079
1080 eltTypeCheck = emitError()
1081 << "expected GlobalViewAttr or ConstPtrAttr";
1082 },
1083 [&](mlir::Type type) {});
1084 if (eltTypeCheck.failed())
1085 return eltTypeCheck;
1086 }
1087 return success();
1088}
1089
1090//===----------------------------------------------------------------------===//
1091// DynamicCastInfoAtttr definitions
1092//===----------------------------------------------------------------------===//
1093
1094std::string DynamicCastInfoAttr::getAlias() const {
1095 // The alias looks like: `dyn_cast_info_<src>_<dest>`
1096
1097 std::string alias = "dyn_cast_info_";
1098
1099 alias.append(getSrcRtti().getSymbol().getValue());
1100 alias.push_back('_');
1101 alias.append(getDestRtti().getSymbol().getValue());
1102
1103 return alias;
1104}
1105
1106// TODO: Give type_info a distinct CIR type so we can verify that a
1107// FlatSymbolRefAttr actually names a type_info global.
1108static bool isRttiPtr(mlir::Type ty) {
1109 auto ptrTy = mlir::dyn_cast<cir::PointerType>(ty);
1110 if (!ptrTy)
1111 return false;
1112
1113 auto pointeeIntTy = mlir::dyn_cast<cir::IntType>(ptrTy.getPointee());
1114 if (!pointeeIntTy)
1115 return false;
1116
1117 return pointeeIntTy.isUnsigned() && pointeeIntTy.getWidth() == 8;
1118}
1119
1120LogicalResult DynamicCastInfoAttr::verify(
1121 function_ref<InFlightDiagnostic()> emitError, cir::GlobalViewAttr srcRtti,
1122 cir::GlobalViewAttr destRtti, mlir::FlatSymbolRefAttr runtimeFunc,
1123 mlir::FlatSymbolRefAttr badCastFunc, cir::IntAttr offsetHint) {
1124 if (!isRttiPtr(srcRtti.getType()))
1125 return emitError() << "srcRtti must be an RTTI pointer";
1126
1127 if (!isRttiPtr(destRtti.getType()))
1128 return emitError() << "destRtti must be an RTTI pointer";
1129
1130 return success();
1131}
1132
1133//===----------------------------------------------------------------------===//
1134// EhFilterAttr definitions
1135//===----------------------------------------------------------------------===//
1136
1137LogicalResult EhFilterAttr::verify(function_ref<InFlightDiagnostic()> emitError,
1138 mlir::ArrayAttr permittedTypes) {
1139 for (mlir::Attribute typeAttr : permittedTypes) {
1140 auto rtti = mlir::dyn_cast<cir::GlobalViewAttr>(typeAttr);
1141 if (!rtti || !isRttiPtr(rtti.getType()))
1142 return emitError() << "permitted type list must contain only type info "
1143 "symbols";
1144 }
1145
1146 return success();
1147}
1148
1149//===----------------------------------------------------------------------===//
1150// RecordLayoutAttr
1151//===----------------------------------------------------------------------===//
1152
1153Attribute RecordLayoutAttr::parse(AsmParser &parser, Type odsType) {
1154 (void)odsType;
1155 SMLoc loc = parser.getCurrentLocation();
1156 if (parser.parseLess() || parser.parseKeyword("arg_passing_kind") ||
1157 parser.parseEqual())
1158 return {};
1159
1160 FailureOr<ArgPassingKind> kind = FieldParser<ArgPassingKind>::parse(parser);
1161 if (failed(kind))
1162 return {};
1163
1164 if (parser.parseComma() || parser.parseKeyword("has_trivial_dtor") ||
1165 parser.parseEqual())
1166 return {};
1167 FailureOr<bool> hasTrivialDtor = FieldParser<bool>::parse(parser);
1168 if (failed(hasTrivialDtor))
1169 return {};
1170
1171 if (parser.parseComma() || parser.parseKeyword("record_align") ||
1172 parser.parseEqual())
1173 return {};
1174 FailureOr<uint64_t> recordAlign = FieldParser<uint64_t>::parse(parser);
1175 if (failed(recordAlign))
1176 return {};
1177
1178 // An omitted unadjusted_align stores the record alignment. The optional
1179 // fields may follow record_align in any order.
1180 uint64_t unadjustedAlign = *recordAlign;
1181 bool transparentUnion = false;
1182 bool flexibleArrayMember = false;
1183 while (succeeded(parser.parseOptionalComma())) {
1184 if (succeeded(parser.parseOptionalKeyword("unadjusted_align"))) {
1185 if (parser.parseEqual())
1186 return {};
1187 FailureOr<uint64_t> parsed = FieldParser<uint64_t>::parse(parser);
1188 if (failed(parsed))
1189 return {};
1190 unadjustedAlign = *parsed;
1191 continue;
1192 }
1193 if (succeeded(parser.parseOptionalKeyword("transparent_union"))) {
1194 if (parser.parseEqual())
1195 return {};
1196 FailureOr<bool> parsed = FieldParser<bool>::parse(parser);
1197 if (failed(parsed))
1198 return {};
1199 transparentUnion = *parsed;
1200 continue;
1201 }
1202 if (succeeded(parser.parseOptionalKeyword("flexible_array_member"))) {
1203 if (parser.parseEqual())
1204 return {};
1205 FailureOr<bool> parsed = FieldParser<bool>::parse(parser);
1206 if (failed(parsed))
1207 return {};
1208 flexibleArrayMember = *parsed;
1209 continue;
1210 }
1211 parser.emitError(parser.getCurrentLocation(),
1212 "expected unadjusted_align, transparent_union or "
1213 "flexible_array_member");
1214 return {};
1215 }
1216
1217 if (parser.parseGreater())
1218 return {};
1219 return parser.getChecked<RecordLayoutAttr>(
1220 loc, parser.getContext(), *kind, *hasTrivialDtor, *recordAlign,
1221 unadjustedAlign, transparentUnion, flexibleArrayMember);
1222}
1223
1224void RecordLayoutAttr::print(AsmPrinter &printer) const {
1225 printer << "<arg_passing_kind = ";
1226 printer.printStrippedAttrOrType(getArgPassingKind());
1227 printer << ", has_trivial_dtor = ";
1228 printer.printStrippedAttrOrType(getHasTrivialDtor());
1229 printer << ", record_align = ";
1230 printer.printStrippedAttrOrType(getRecordAlign());
1231 // Print unadjusted_align only when it differs from record_align.
1232 if (getUnadjustedAlign() != getRecordAlign()) {
1233 printer << ", unadjusted_align = ";
1234 printer.printStrippedAttrOrType(getUnadjustedAlign());
1235 }
1236 if (getTransparentUnion()) {
1237 printer << ", transparent_union = ";
1238 printer.printStrippedAttrOrType(getTransparentUnion());
1239 }
1240 if (getFlexibleArrayMember()) {
1241 printer << ", flexible_array_member = ";
1242 printer.printStrippedAttrOrType(getFlexibleArrayMember());
1243 }
1244 printer << '>';
1245}
1246
1247//===----------------------------------------------------------------------===//
1248// RecordLayout lookup
1249//===----------------------------------------------------------------------===//
1250
1251RecordLayoutAttr cir::tryGetRecordLayout(mlir::ModuleOp mod,
1252 mlir::StringAttr name) {
1253 if (!name)
1254 return {};
1255 auto dict = mod->getAttrOfType<mlir::DictionaryAttr>(
1256 CIRDialect::getRecordLayoutsAttrName());
1257 if (!dict)
1258 return {};
1259 return dict.getAs<RecordLayoutAttr>(name);
1260}
1261
1262RecordLayoutAttr cir::getRecordLayout(mlir::ModuleOp mod,
1263 mlir::StringAttr name) {
1264 RecordLayoutAttr attr = tryGetRecordLayout(mod, name);
1265 assert(attr && "record layout entry missing for named record");
1266 return attr;
1267}
1268
1269//===----------------------------------------------------------------------===//
1270// TBAA attributes
1271//===----------------------------------------------------------------------===//
1272
1273bool TBAATypeDescriptorAttr::classof(mlir::Attribute attr) {
1274 return mlir::isa<TBAAOmnipotentCharAttr, TBAAScalarAttr, TBAAStructAttr>(
1275 attr);
1276}
1277
1278LogicalResult
1279TBAAStructAttr::verify(function_ref<InFlightDiagnostic()> emitError,
1280 llvm::StringRef id, ArrayRef<TBAAMemberAttr> members) {
1281 if (!llvm::is_sorted(members, [](TBAAMemberAttr a, TBAAMemberAttr b) {
1282 return a.getOffset() < b.getOffset();
1283 }))
1284 return emitError() << "expected the member offsets of TBAA struct '" << id
1285 << "' to be non-decreasing";
1286 return success();
1287}
1288
1289LogicalResult TBAATagAttr::verify(function_ref<InFlightDiagnostic()> emitError,
1292 uint64_t offset) {
1293 if (!mlir::isa<TBAAOmnipotentCharAttr, TBAAScalarAttr>(access))
1294 return emitError() << "expected the access type to be a scalar TBAA type "
1295 "descriptor";
1296 if (!mlir::isa<TBAAStructAttr>(base) && (base != access || offset != 0))
1297 return emitError() << "expected a non-struct base to match the access "
1298 "type at offset zero";
1299
1300 // Walk the access path like the LLVM TBAA verifier; the access type must be
1301 // on it.
1303 uint64_t remaining = offset;
1304 while (auto record = mlir::dyn_cast<TBAAStructAttr>(node)) {
1305 ArrayRef<TBAAMemberAttr> members = record.getMembers();
1306 auto it = llvm::upper_bound(members, remaining,
1307 [](uint64_t off, TBAAMemberAttr member) {
1308 return off < member.getOffset();
1309 });
1310 if (it == members.begin())
1311 return emitError() << "TBAA struct '" << record.getId()
1312 << "' has no member at offset " << remaining;
1313 --it;
1314 remaining -= it->getOffset();
1315 node = it->getTypeDesc();
1316 }
1317 if (remaining != 0)
1318 return emitError() << "TBAA access offset " << offset
1319 << " does not point at the start of a scalar member";
1320 while (node != access) {
1321 auto scalar = mlir::dyn_cast<TBAAScalarAttr>(node);
1322 if (!scalar)
1323 return emitError() << "TBAA access type is not on the access path of "
1324 "the base type at offset "
1325 << offset;
1326 node = scalar.getParent()
1327 ? TBAATypeDescriptorAttr(scalar.getParent())
1328 : TBAAOmnipotentCharAttr::get(scalar.getContext());
1329 }
1330 return success();
1331}
static mlir::ParseResult parseFloatLiteral(mlir::AsmParser &parser, mlir::FailureOr< llvm::APFloat > &value, cir::FPTypeInterface fpType)
static void printConstPtr(mlir::AsmPrinter &p, mlir::IntegerAttr value)
static void printRecordMembers(mlir::AsmPrinter &p, mlir::ArrayAttr members)
Definition CIRAttrs.cpp:222
static mlir::ParseResult parseIntLiteral(mlir::AsmParser &parser, llvm::APInt &value, cir::IntTypeInterface ty)
Definition CIRAttrs.cpp:429
static void printIntLiteral(mlir::AsmPrinter &p, llvm::APInt value, cir::IntTypeInterface ty)
Definition CIRAttrs.cpp:448
static mlir::ParseResult parseConstPtr(mlir::AsmParser &parser, mlir::IntegerAttr &value)
static void printFloatLiteral(mlir::AsmPrinter &p, llvm::APFloat value, mlir::Type ty)
static mlir::ParseResult parseDataMemberPath(mlir::AsmParser &parser, mlir::DenseI32ArrayAttr &memberPath)
static bool isRttiPtr(mlir::Type ty)
static void printDataMemberPath(mlir::AsmPrinter &p, mlir::DenseI32ArrayAttr memberPath)
static mlir::ParseResult parseRecordMembers(mlir::AsmParser &parser, mlir::ArrayAttr &members)
Definition CIRAttrs.cpp:229
static bool isValidFlexibleArrayInit(mlir::Type memberType, mlir::Type initType)
Definition CIRAttrs.cpp:253
static Decl::Kind getKind(const Decl *D)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
Base class of the TBAA type descriptor attributes.
Definition CIRAttrs.h:48
static bool classof(mlir::Attribute attr)
RecordLayoutAttr tryGetRecordLayout(mlir::ModuleOp mod, mlir::StringAttr name)
Same lookup as getRecordLayout, but returns a null attribute instead of asserting when the record has...
RecordLayoutAttr getRecordLayout(mlir::ModuleOp mod, mlir::StringAttr name)
Look up the RecordLayoutAttr for a named record in the module's cir.record_layouts dictionary.
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:138
bool memberOwnsBytes(mlir::Type memberTy)
Whether a record member occupies bytes of its record.
Definition CIRTypes.h:129
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
RangeSelector member(std::string ID)
Given a MemberExpr, selects the member token. ID is the node's binding in the match result.
RangeSelector node(std::string ID)
Selects a node, including trailing semicolon, if any (for declarations and non-expression statements)...
float __ovld __cnfn step(float, float)
Returns 0.0 if x < edge, otherwise it returns 1.0.
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t