19#include "mlir/IR/Attributes.h"
20#include "mlir/IR/DialectImplementation.h"
21#include "mlir/IR/PatternMatch.h"
22#include "mlir/Interfaces/ControlFlowInterfaces.h"
23#include "mlir/Interfaces/FunctionImplementation.h"
24#include "mlir/Support/LLVM.h"
26#include "clang/CIR/Dialect/IR/CIROpsDialect.cpp.inc"
27#include "clang/CIR/Dialect/IR/CIROpsEnums.cpp.inc"
29#include "llvm/ADT/SetOperations.h"
30#include "llvm/ADT/SmallSet.h"
31#include "llvm/ADT/TypeSwitch.h"
32#include "llvm/Support/LogicalResult.h"
41struct CIROpAsmDialectInterface :
public OpAsmDialectInterface {
42 using OpAsmDialectInterface::OpAsmDialectInterface;
44 AliasResult getAlias(Type type, raw_ostream &os)
const final {
45 if (
auto recordType = dyn_cast<cir::RecordType>(type)) {
48 os <<
"rec_anon_" <<
recordType.getKindAsStr();
50 os <<
"rec_" << nameAttr.getValue();
51 return AliasResult::OverridableAlias;
53 if (
auto intType = dyn_cast<cir::IntType>(type)) {
56 unsigned width = intType.getWidth();
57 if (width < 8 || !llvm::isPowerOf2_32(width))
58 return AliasResult::NoAlias;
59 os << intType.getAlias();
60 return AliasResult::OverridableAlias;
62 if (
auto voidType = dyn_cast<cir::VoidType>(type)) {
63 os << voidType.getAlias();
64 return AliasResult::OverridableAlias;
67 return AliasResult::NoAlias;
70 AliasResult getAlias(Attribute attr, raw_ostream &os)
const final {
71 if (
auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr)) {
72 os << (boolAttr.getValue() ?
"true" :
"false");
73 return AliasResult::FinalAlias;
75 if (
auto bitfield = mlir::dyn_cast<cir::BitfieldInfoAttr>(attr)) {
76 os <<
"bfi_" << bitfield.getName().str();
77 return AliasResult::FinalAlias;
79 if (
auto dynCastInfoAttr = mlir::dyn_cast<cir::DynamicCastInfoAttr>(attr)) {
80 os << dynCastInfoAttr.getAlias();
81 return AliasResult::FinalAlias;
83 if (
auto cmpThreeWayInfoAttr =
84 mlir::dyn_cast<cir::CmpThreeWayInfoAttr>(attr)) {
85 os << cmpThreeWayInfoAttr.getAlias();
86 return AliasResult::FinalAlias;
88 return AliasResult::NoAlias;
93void cir::CIRDialect::initialize() {
98#include "clang/CIR/Dialect/IR/CIROps.cpp.inc"
100 addInterfaces<CIROpAsmDialectInterface>();
103Operation *cir::CIRDialect::materializeConstant(mlir::OpBuilder &builder,
104 mlir::Attribute value,
106 mlir::Location loc) {
107 return cir::ConstantOp::create(builder, loc, type,
108 mlir::cast<mlir::TypedAttr>(value));
120 for (
auto en : llvm::enumerate(keywords)) {
121 if (succeeded(parser.parseOptionalKeyword(en.value())))
128template <
typename Ty>
struct EnumTraits {};
130#define REGISTER_ENUM_TYPE(Ty) \
131 template <> struct EnumTraits<cir::Ty> { \
132 static llvm::StringRef stringify(cir::Ty value) { \
133 return stringify##Ty(value); \
135 static unsigned getMaxEnumVal() { return cir::getMaxEnumValFor##Ty(); } \
147template <
typename EnumTy,
typename RetTy = EnumTy>
150 for (
unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
151 names.push_back(EnumTraits<EnumTy>::stringify(
static_cast<EnumTy
>(i)));
155 return static_cast<RetTy
>(defaultValue);
156 return static_cast<RetTy
>(index);
160template <
typename EnumTy,
typename RetTy = EnumTy>
163 for (
unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
164 names.push_back(EnumTraits<EnumTy>::stringify(
static_cast<EnumTy
>(i)));
169 result =
static_cast<RetTy
>(index);
177 Location eLoc = parser.getEncodedSourceLoc(parser.getCurrentLocation());
178 OpBuilder builder(parser.getBuilder().getContext());
183 builder.createBlock(®ion);
185 Block &block = region.back();
187 if (!block.empty() && block.back().hasTrait<OpTrait::IsTerminator>())
191 if (!region.hasOneBlock())
192 return parser.emitError(errLoc,
193 "multi-block region must not omit terminator");
196 builder.setInsertionPointToEnd(&block);
197 cir::YieldOp::create(builder, eLoc);
203 const auto singleNonEmptyBlock = r.hasOneBlock() && !r.back().empty();
204 const auto yieldsNothing = [&r]() {
205 auto y = dyn_cast<cir::YieldOp>(r.back().getTerminator());
206 return y && y.getArgs().empty();
208 return singleNonEmptyBlock && yieldsNothing();
216 cir::InlineKindAttr &inlineKindAttr) {
218 static constexpr llvm::StringRef keywords[] = {
"no_inline",
"always_inline",
222 llvm::StringRef keyword;
223 if (parser.parseOptionalKeyword(&keyword, keywords).failed()) {
229 auto inlineKindResult = ::cir::symbolizeEnum<::cir::InlineKind>(keyword);
230 if (!inlineKindResult) {
231 return parser.emitError(parser.getCurrentLocation(),
"expected one of [")
233 <<
"] for inlineKind, got: " << keyword;
237 ::cir::InlineKindAttr::get(parser.getContext(), *inlineKindResult);
242 if (inlineKindAttr) {
243 p <<
" " << stringifyInlineKind(inlineKindAttr.getValue());
251 mlir::Region ®ion) {
252 auto regionLoc = parser.getCurrentLocation();
253 if (parser.parseRegion(region))
262 mlir::Region ®ion) {
263 printer.printRegion(region,
268mlir::OptionalParseResult
270 mlir::ptr::MemorySpaceAttrInterface &attr);
273 mlir::ptr::MemorySpaceAttrInterface attr);
279void cir::AllocaOp::build(mlir::OpBuilder &odsBuilder,
280 mlir::OperationState &odsState, mlir::Type addr,
281 mlir::Type allocaType, llvm::StringRef name,
282 mlir::IntegerAttr alignment) {
283 odsState.addAttribute(getAllocaTypeAttrName(odsState.name),
284 mlir::TypeAttr::get(allocaType));
285 odsState.addAttribute(getNameAttrName(odsState.name),
286 odsBuilder.getStringAttr(name));
288 odsState.addAttribute(getAlignmentAttrName(odsState.name), alignment);
290 odsState.addTypes(addr);
298 auto ptrTy = mlir::cast<cir::PointerType>(op.getAddr().getType());
299 mlir::Type pointeeTy = ptrTy.getPointee();
301 mlir::Block &body = op.getBody().front();
302 if (body.getNumArguments() != 1)
303 return op.emitOpError(
"body must have exactly one block argument");
305 auto expectedEltPtrTy =
306 mlir::dyn_cast<cir::PointerType>(body.getArgument(0).getType());
307 if (!expectedEltPtrTy)
308 return op.emitOpError(
"block argument must be a !cir.ptr type");
310 if (op.getNumElements()) {
311 auto recTy = mlir::dyn_cast<cir::RecordType>(pointeeTy);
313 return op.emitOpError(
314 "when 'num_elements' is present, 'addr' must be a pointer to a "
317 if (expectedEltPtrTy != ptrTy)
318 return op.emitOpError(
"when 'num_elements' is present, 'addr' type must "
319 "match the block argument type");
321 auto arrayTy = mlir::dyn_cast<cir::ArrayType>(pointeeTy);
323 return op.emitOpError(
324 "when 'num_elements' is absent, 'addr' must be a pointer to a "
327 mlir::Type innerEltTy = arrayTy.getElementType();
328 while (
auto nested = mlir::dyn_cast<cir::ArrayType>(innerEltTy))
329 innerEltTy = nested.getElementType();
331 auto recTy = mlir::dyn_cast<cir::RecordType>(innerEltTy);
333 return op.emitOpError(
334 "the block argument type must be a pointer to a !cir.record type");
336 if (expectedEltPtrTy.getPointee() != innerEltTy)
337 return op.emitOpError(
338 "block argument pointee type must match the innermost array "
345LogicalResult cir::ArrayCtor::verify() {
349 mlir::Region &partialDtor = getPartialDtor();
350 if (!partialDtor.empty()) {
351 mlir::Block &dtorBlock = partialDtor.front();
352 if (dtorBlock.getNumArguments() != 1)
353 return emitOpError(
"partial_dtor must have exactly one block argument");
355 auto bodyArgTy = getBody().front().getArgument(0).getType();
356 if (dtorBlock.getArgument(0).getType() != bodyArgTy)
357 return emitOpError(
"partial_dtor block argument type must match "
358 "the body block argument type");
368LogicalResult cir::DeleteArrayOp::verify() {
369 if (getDtorMayThrow() && !getElementDtorAttr())
371 "'dtor_may_throw' requires an 'element_dtor' to be present");
379LogicalResult cir::BreakOp::verify() {
380 if (!getOperation()->getParentOfType<LoopOpInterface>() &&
381 !getOperation()->getParentOfType<SwitchOp>())
382 return emitOpError(
"must be within a loop");
390LogicalResult cir::LocalInitOp::verify() {
391 if (!getOperation()->getParentOfType<FuncOp>())
392 return emitOpError(
"must be inside of a 'cir.func'");
397cir::LocalInitOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
398 cir::GlobalOp global = getReferencedGlobal(symbolTable);
400 return emitOpError(
"'")
401 << getGlobalName() <<
"' does not reference a valid cir.global";
403 if (getTls() && !global.getTlsModel())
404 return emitOpError(
"access to global not marked thread local");
406 if (!global.getStaticLocalGuard().has_value())
407 return emitOpError(
"static_local attribute mismatch");
420void cir::ConditionOp::getSuccessorRegions(
426 if (
auto loopOp = dyn_cast<LoopOpInterface>(getOperation()->getParentOp())) {
427 regions.emplace_back(&loopOp.getBody());
428 regions.push_back(RegionSuccessor::parent());
433 auto await = cast<AwaitOp>(getOperation()->getParentOp());
434 regions.emplace_back(&await.getResume());
435 regions.emplace_back(&await.getSuspend());
439cir::ConditionOp::getMutableSuccessorOperands(RegionSuccessor point) {
441 return MutableOperandRange(getOperation(), 0, 0);
445cir::ResumeOp::getMutableSuccessorOperands(RegionSuccessor point) {
447 return MutableOperandRange(getOperation(), 0, 0);
450LogicalResult cir::ConditionOp::verify() {
451 if (!isa<LoopOpInterface, AwaitOp>(getOperation()->getParentOp()))
452 return emitOpError(
"condition must be within a conditional region");
461 mlir::Attribute attrType) {
462 if (isa<cir::ConstPtrAttr>(attrType)) {
463 if (!mlir::isa<cir::PointerType>(opType))
464 return op->emitOpError(
465 "pointer constant initializing a non-pointer type");
469 if (isa<cir::DataMemberAttr, cir::MethodAttr>(attrType)) {
475 if (isa<cir::ZeroAttr>(attrType)) {
476 if (isa<cir::RecordType, cir::ArrayType, cir::VectorType, cir::ComplexType>(
479 return op->emitOpError(
480 "zero expects struct, array, vector, or complex type");
483 if (mlir::isa<cir::UndefAttr>(attrType)) {
484 if (!mlir::isa<cir::VoidType>(opType))
486 return op->emitOpError(
"undef expects non-void type");
489 if (mlir::isa<cir::BoolAttr>(attrType)) {
490 if (!mlir::isa<cir::BoolType>(opType))
491 return op->emitOpError(
"result type (")
492 << opType <<
") must be '!cir.bool' for '" << attrType <<
"'";
496 if (mlir::isa<cir::IntAttr, cir::FPAttr>(attrType)) {
497 auto at = cast<TypedAttr>(attrType);
498 if (at.getType() != opType) {
499 return op->emitOpError(
"result type (")
500 << opType <<
") does not match value type (" << at.getType()
506 if (mlir::isa<cir::ConstArrayAttr, cir::ConstVectorAttr,
507 cir::ConstComplexAttr, cir::ConstRecordAttr,
508 cir::GlobalViewAttr, cir::PoisonAttr, cir::TypeInfoAttr,
509 cir::VTableAttr>(attrType))
512 assert(isa<TypedAttr>(attrType) &&
"What else could we be looking at here?");
513 return op->emitOpError(
"global with type ")
514 << cast<TypedAttr>(attrType).getType() <<
" not yet supported";
517LogicalResult cir::ConstantOp::verify() {
524OpFoldResult cir::ConstantOp::fold(FoldAdaptor ) {
532LogicalResult cir::ContinueOp::verify() {
533 if (!getOperation()->getParentOfType<LoopOpInterface>())
534 return emitOpError(
"must be within a loop");
542LogicalResult cir::CastOp::verify() {
543 mlir::Type resType =
getType();
544 mlir::Type srcType = getSrc().getType();
548 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
549 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
550 if (srcPtrTy && resPtrTy && (
getKind() != cir::CastKind::address_space))
551 if (srcPtrTy.getAddrSpace() != resPtrTy.getAddrSpace()) {
552 return emitOpError() <<
"result type address space does not match the "
553 "address space of the operand";
556 if (mlir::isa<cir::VectorType>(srcType) &&
557 mlir::isa<cir::VectorType>(resType)) {
560 srcType = mlir::dyn_cast<cir::VectorType>(srcType).getElementType();
561 resType = mlir::dyn_cast<cir::VectorType>(resType).getElementType();
565 case cir::CastKind::int_to_bool: {
566 if (!mlir::isa<cir::BoolType>(resType))
567 return emitOpError() <<
"requires !cir.bool type for result";
568 if (!mlir::isa<cir::IntType>(srcType))
569 return emitOpError() <<
"requires !cir.int type for source";
572 case cir::CastKind::ptr_to_bool: {
573 if (!mlir::isa<cir::BoolType>(resType))
574 return emitOpError() <<
"requires !cir.bool type for result";
575 if (!mlir::isa<cir::PointerType>(srcType))
576 return emitOpError() <<
"requires !cir.ptr type for source";
579 case cir::CastKind::integral: {
580 if (!mlir::isa<cir::IntType>(resType))
581 return emitOpError() <<
"requires !cir.int type for result";
582 if (!mlir::isa<cir::IntType>(srcType))
583 return emitOpError() <<
"requires !cir.int type for source";
586 case cir::CastKind::array_to_ptrdecay: {
587 const auto arrayPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
588 const auto flatPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
589 if (!arrayPtrTy || !flatPtrTy)
590 return emitOpError() <<
"requires !cir.ptr type for source and result";
595 case cir::CastKind::bitcast: {
597 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
598 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
600 if (srcPtrTy && resPtrTy) {
606 case cir::CastKind::floating: {
607 if (!mlir::isa<cir::FPTypeInterface>(srcType) ||
608 !mlir::isa<cir::FPTypeInterface>(resType))
609 return emitOpError() <<
"requires !cir.float type for source and result";
612 case cir::CastKind::float_to_int: {
613 if (!mlir::isa<cir::FPTypeInterface>(srcType))
614 return emitOpError() <<
"requires !cir.float type for source";
615 if (!mlir::dyn_cast<cir::IntType>(resType))
616 return emitOpError() <<
"requires !cir.int type for result";
619 case cir::CastKind::int_to_ptr: {
620 if (!mlir::dyn_cast<cir::IntType>(srcType))
621 return emitOpError() <<
"requires !cir.int type for source";
622 if (!mlir::dyn_cast<cir::PointerType>(resType))
623 return emitOpError() <<
"requires !cir.ptr type for result";
626 case cir::CastKind::ptr_to_int: {
627 if (!mlir::dyn_cast<cir::PointerType>(srcType))
628 return emitOpError() <<
"requires !cir.ptr type for source";
629 if (!mlir::dyn_cast<cir::IntType>(resType))
630 return emitOpError() <<
"requires !cir.int type for result";
633 case cir::CastKind::float_to_bool: {
634 if (!mlir::isa<cir::FPTypeInterface>(srcType))
635 return emitOpError() <<
"requires !cir.float type for source";
636 if (!mlir::isa<cir::BoolType>(resType))
637 return emitOpError() <<
"requires !cir.bool type for result";
640 case cir::CastKind::bool_to_int: {
641 if (!mlir::isa<cir::BoolType>(srcType))
642 return emitOpError() <<
"requires !cir.bool type for source";
643 if (!mlir::isa<cir::IntType>(resType))
644 return emitOpError() <<
"requires !cir.int type for result";
647 case cir::CastKind::int_to_float: {
648 if (!mlir::isa<cir::IntType>(srcType))
649 return emitOpError() <<
"requires !cir.int type for source";
650 if (!mlir::isa<cir::FPTypeInterface>(resType))
651 return emitOpError() <<
"requires !cir.float type for result";
654 case cir::CastKind::bool_to_float: {
655 if (!mlir::isa<cir::BoolType>(srcType))
656 return emitOpError() <<
"requires !cir.bool type for source";
657 if (!mlir::isa<cir::FPTypeInterface>(resType))
658 return emitOpError() <<
"requires !cir.float type for result";
661 case cir::CastKind::address_space: {
662 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
663 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
664 if (!srcPtrTy || !resPtrTy)
665 return emitOpError() <<
"requires !cir.ptr type for source and result";
666 if (srcPtrTy.getPointee() != resPtrTy.getPointee())
667 return emitOpError() <<
"requires two types differ in addrspace only";
670 case cir::CastKind::float_to_complex: {
671 if (!mlir::isa<cir::FPTypeInterface>(srcType))
672 return emitOpError() <<
"requires !cir.float type for source";
673 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
675 return emitOpError() <<
"requires !cir.complex type for result";
676 if (srcType != resComplexTy.getElementType())
677 return emitOpError() <<
"requires source type match result element type";
680 case cir::CastKind::int_to_complex: {
681 if (!mlir::isa<cir::IntType>(srcType))
682 return emitOpError() <<
"requires !cir.int type for source";
683 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
685 return emitOpError() <<
"requires !cir.complex type for result";
686 if (srcType != resComplexTy.getElementType())
687 return emitOpError() <<
"requires source type match result element type";
690 case cir::CastKind::float_complex_to_real: {
691 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
693 return emitOpError() <<
"requires !cir.complex type for source";
694 if (!mlir::isa<cir::FPTypeInterface>(resType))
695 return emitOpError() <<
"requires !cir.float type for result";
696 if (srcComplexTy.getElementType() != resType)
697 return emitOpError() <<
"requires source element type match result type";
700 case cir::CastKind::int_complex_to_real: {
701 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
703 return emitOpError() <<
"requires !cir.complex type for source";
704 if (!mlir::isa<cir::IntType>(resType))
705 return emitOpError() <<
"requires !cir.int type for result";
706 if (srcComplexTy.getElementType() != resType)
707 return emitOpError() <<
"requires source element type match result type";
710 case cir::CastKind::float_complex_to_bool: {
711 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
712 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
714 <<
"requires floating point !cir.complex type for source";
715 if (!mlir::isa<cir::BoolType>(resType))
716 return emitOpError() <<
"requires !cir.bool type for result";
719 case cir::CastKind::int_complex_to_bool: {
720 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
721 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
723 <<
"requires floating point !cir.complex type for source";
724 if (!mlir::isa<cir::BoolType>(resType))
725 return emitOpError() <<
"requires !cir.bool type for result";
728 case cir::CastKind::float_complex: {
729 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
730 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
732 <<
"requires floating point !cir.complex type for source";
733 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
734 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
736 <<
"requires floating point !cir.complex type for result";
739 case cir::CastKind::float_complex_to_int_complex: {
740 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
741 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
743 <<
"requires floating point !cir.complex type for source";
744 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
745 if (!resComplexTy || !resComplexTy.isIntegerComplex())
746 return emitOpError() <<
"requires integer !cir.complex type for result";
749 case cir::CastKind::int_complex: {
750 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
751 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
752 return emitOpError() <<
"requires integer !cir.complex type for source";
753 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
754 if (!resComplexTy || !resComplexTy.isIntegerComplex())
755 return emitOpError() <<
"requires integer !cir.complex type for result";
758 case cir::CastKind::int_complex_to_float_complex: {
759 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
760 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
761 return emitOpError() <<
"requires integer !cir.complex type for source";
762 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
763 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
765 <<
"requires floating point !cir.complex type for result";
768 case cir::CastKind::member_ptr_to_bool: {
769 if (!mlir::isa<cir::DataMemberType, cir::MethodType>(srcType))
771 <<
"requires !cir.data_member or !cir.method type for source";
772 if (!mlir::isa<cir::BoolType>(resType))
773 return emitOpError() <<
"requires !cir.bool type for result";
777 llvm_unreachable(
"Unknown CastOp kind?");
781 auto kind = op.getKind();
782 return kind == cir::CastKind::bool_to_int ||
783 kind == cir::CastKind::int_to_bool ||
kind == cir::CastKind::integral;
787 const auto ptrTy = mlir::dyn_cast<cir::PointerType>(ty);
788 return ptrTy && mlir::isa<cir::FuncType>(ptrTy.getPointee());
792 cir::CastOp head = op, tail = op;
798 op = head.getSrc().getDefiningOp<cir::CastOp>();
804 if (head.getKind() == cir::CastKind::bool_to_int &&
805 tail.getKind() == cir::CastKind::int_to_bool)
806 return head.getSrc();
811 if (head.getKind() == cir::CastKind::int_to_bool &&
812 tail.getKind() == cir::CastKind::int_to_bool)
813 return head.getResult();
821 if (tail.getKind() == cir::CastKind::bitcast) {
822 auto *inner = tail.getSrc().getDefiningOp();
824 auto innerCast = mlir::dyn_cast<cir::CastOp>(inner);
825 if (innerCast && innerCast.getKind() == cir::CastKind::bitcast &&
826 innerCast.getSrc().getType() == tail.getType() &&
827 innerCast.getType() == tail.getSrc().getType()) {
828 return innerCast.getSrc();
836OpFoldResult cir::CastOp::fold(FoldAdaptor adaptor) {
837 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getSrc())) {
839 return cir::PoisonAttr::get(getContext(),
getType());
844 case cir::CastKind::integral: {
846 auto foldOrder = getSrc().getDefiningOp()->fold(foldResults);
847 if (foldOrder.succeeded() && mlir::isa<mlir::Attribute>(foldResults[0]))
848 return mlir::cast<mlir::Attribute>(foldResults[0]);
851 case cir::CastKind::bitcast:
852 case cir::CastKind::address_space:
853 case cir::CastKind::float_complex:
854 case cir::CastKind::int_complex: {
868 if (
auto srcConst = getSrc().getDefiningOp<cir::ConstantOp>()) {
870 case cir::CastKind::integral: {
871 mlir::Type srcTy = getSrc().getType();
873 assert(mlir::isa<cir::VectorType>(srcTy) ==
874 mlir::isa<cir::VectorType>(
getType()));
875 if (mlir::isa<cir::VectorType>(srcTy))
878 auto srcIntTy = mlir::cast<cir::IntType>(srcTy);
879 auto dstIntTy = mlir::cast<cir::IntType>(
getType());
882 ? srcConst.getIntValue().sextOrTrunc(dstIntTy.getWidth())
883 : srcConst.getIntValue().zextOrTrunc(dstIntTy.getWidth());
884 return cir::IntAttr::get(dstIntTy, newVal);
897mlir::OperandRange cir::CallOp::getArgOperands() {
899 return getArgs().drop_front(1);
903mlir::MutableOperandRange cir::CallOp::getArgOperandsMutable() {
904 mlir::MutableOperandRange args = getArgsMutable();
906 return args.slice(1, args.size() - 1);
910mlir::Value cir::CallOp::getIndirectCall() {
911 assert(isIndirect());
912 return getOperand(0);
916Value cir::CallOp::getArgOperand(
unsigned i) {
919 return getOperand(i);
923unsigned cir::CallOp::getNumArgOperands() {
925 return this->getOperation()->getNumOperands() - 1;
926 return this->getOperation()->getNumOperands();
929static mlir::ParseResult
931 mlir::OperationState &result) {
932 mlir::Block *normalDestSuccessor;
933 if (parser.parseSuccessor(normalDestSuccessor))
934 return mlir::failure();
936 if (parser.parseComma())
937 return mlir::failure();
939 mlir::Block *unwindDestSuccessor;
940 if (parser.parseSuccessor(unwindDestSuccessor))
941 return mlir::failure();
943 result.addSuccessors(normalDestSuccessor);
944 result.addSuccessors(unwindDestSuccessor);
945 return mlir::success();
949 mlir::OperationState &result,
950 bool hasDestinationBlocks =
false) {
953 mlir::FlatSymbolRefAttr calleeAttr;
957 .parseOptionalAttribute(calleeAttr, CIRDialect::getCalleeAttrName(),
960 OpAsmParser::UnresolvedOperand indirectVal;
962 if (parser.parseOperand(indirectVal).failed())
964 ops.push_back(indirectVal);
967 if (parser.parseLParen())
968 return mlir::failure();
970 opsLoc = parser.getCurrentLocation();
971 if (parser.parseOperandList(ops))
972 return mlir::failure();
973 if (parser.parseRParen())
974 return mlir::failure();
976 if (hasDestinationBlocks &&
978 return ::mlir::failure();
981 if (parser.parseOptionalKeyword(
"musttail").succeeded())
982 result.addAttribute(CIRDialect::getMustTailAttrName(),
983 mlir::UnitAttr::get(parser.getContext()));
985 if (parser.parseOptionalKeyword(
"nothrow").succeeded())
986 result.addAttribute(CIRDialect::getNoThrowAttrName(),
987 mlir::UnitAttr::get(parser.getContext()));
989 if (parser.parseOptionalKeyword(
"side_effect").succeeded()) {
990 if (parser.parseLParen().failed())
992 cir::SideEffect sideEffect;
995 if (parser.parseRParen().failed())
997 auto attr = cir::SideEffectAttr::get(parser.getContext(), sideEffect);
998 result.addAttribute(CIRDialect::getSideEffectAttrName(), attr);
1001 if (parser.parseOptionalAttrDict(result.attributes))
1002 return ::mlir::failure();
1004 if (parser.parseColon())
1005 return ::mlir::failure();
1011 if (call_interface_impl::parseFunctionSignature(parser, argTypes, argAttrs,
1012 resultTypes, resultAttrs))
1013 return mlir::failure();
1015 if (resultTypes.size() > 1 || resultAttrs.size() > 1)
1016 return parser.emitError(
1017 parser.getCurrentLocation(),
1018 "functions with multiple return types are not supported");
1020 result.addTypes(resultTypes);
1022 if (parser.resolveOperands(ops, argTypes, opsLoc, result.operands))
1023 return mlir::failure();
1025 if (!resultAttrs.empty() && resultAttrs[0])
1026 result.addAttribute(
1027 CIRDialect::getResAttrsAttrName(),
1028 mlir::ArrayAttr::get(parser.getContext(), {resultAttrs[0]}));
1033 bool argAttrsEmpty =
true;
1035 llvm::transform(argAttrs, std::back_inserter(convertedArgAttrs),
1036 [&](DictionaryAttr da) -> mlir::Attribute {
1038 argAttrsEmpty =
false;
1042 if (!argAttrsEmpty) {
1047 argAttrsRef = argAttrsRef.drop_front();
1049 result.addAttribute(CIRDialect::getArgAttrsAttrName(),
1050 mlir::ArrayAttr::get(parser.getContext(), argAttrsRef));
1053 return mlir::success();
1058 mlir::Value indirectCallee, mlir::OpAsmPrinter &printer,
1059 bool isNothrow, cir::SideEffect sideEffect, ArrayAttr argAttrs,
1060 ArrayAttr resAttrs, mlir::Block *normalDest =
nullptr,
1061 mlir::Block *unwindDest =
nullptr) {
1064 auto callLikeOp = mlir::cast<cir::CIRCallOpInterface>(op);
1065 auto ops = callLikeOp.getArgOperands();
1069 printer.printAttributeWithoutType(calleeSym);
1072 assert(indirectCallee);
1073 printer << indirectCallee;
1076 printer <<
"(" << ops <<
")";
1079 assert(unwindDest &&
"expected two successors");
1080 auto tryCall = cast<cir::TryCallOp>(op);
1081 printer <<
' ' << tryCall.getNormalDest();
1084 printer << tryCall.getUnwindDest();
1087 if (op->hasAttr(CIRDialect::getMustTailAttrName()))
1088 printer <<
" musttail";
1091 printer <<
" nothrow";
1093 if (sideEffect != cir::SideEffect::All) {
1094 printer <<
" side_effect(";
1095 printer << stringifySideEffect(sideEffect);
1100 CIRDialect::getCalleeAttrName(),
1101 CIRDialect::getMustTailAttrName(),
1102 CIRDialect::getNoThrowAttrName(),
1103 CIRDialect::getSideEffectAttrName(),
1104 CIRDialect::getOperandSegmentSizesAttrName(),
1105 llvm::StringRef(
"res_attrs"),
1106 llvm::StringRef(
"arg_attrs")};
1107 printer.printOptionalAttrDict(op->getAttrs(), elidedAttrs);
1109 if (calleeSym || !argAttrs) {
1110 call_interface_impl::printFunctionSignature(
1111 printer, op->getOperands().getTypes(), argAttrs,
1112 false, op->getResultTypes(), resAttrs);
1120 shimmedArgAttrs.push_back(mlir::DictionaryAttr::get(op->getContext(), {}));
1121 shimmedArgAttrs.append(argAttrs.begin(), argAttrs.end());
1122 call_interface_impl::printFunctionSignature(
1123 printer, op->getOperands().getTypes(),
1124 mlir::ArrayAttr::get(op->getContext(), shimmedArgAttrs),
1125 false, op->getResultTypes(), resAttrs);
1129mlir::ParseResult cir::CallOp::parse(mlir::OpAsmParser &parser,
1130 mlir::OperationState &result) {
1134void cir::CallOp::print(mlir::OpAsmPrinter &p) {
1135 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() :
nullptr;
1136 cir::SideEffect sideEffect = getSideEffect();
1137 printCallCommon(*
this, getCalleeAttr(), indirectCallee, p, getNothrow(),
1138 sideEffect, getArgAttrsAttr(), getResAttrsAttr());
1143 SymbolTableCollection &symbolTable) {
1145 op->getAttrOfType<FlatSymbolRefAttr>(CIRDialect::getCalleeAttrName());
1148 return mlir::success();
1151 auto fn = symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(op, fnAttr);
1153 return op->emitOpError() <<
"'" << fnAttr.getValue()
1154 <<
"' does not reference a valid function";
1156 auto callIf = dyn_cast<cir::CIRCallOpInterface>(op);
1157 assert(callIf &&
"expected CIR call interface to be always available");
1161 auto fnType = fn.getFunctionType();
1162 if (!fn.getNoProto()) {
1163 unsigned numCallOperands = callIf.getNumArgOperands();
1164 unsigned numFnOpOperands = fnType.getNumInputs();
1166 if (!fnType.isVarArg() && numCallOperands != numFnOpOperands)
1167 return op->emitOpError(
"incorrect number of operands for callee");
1168 if (fnType.isVarArg() && numCallOperands < numFnOpOperands)
1169 return op->emitOpError(
"too few operands for callee");
1171 for (
unsigned i = 0, e = numFnOpOperands; i != e; ++i)
1172 if (callIf.getArgOperand(i).getType() != fnType.getInput(i))
1173 return op->emitOpError(
"operand type mismatch: expected operand type ")
1174 << fnType.getInput(i) <<
", but provided "
1175 << op->getOperand(i).getType() <<
" for operand number " << i;
1181 if (fnType.hasVoidReturn() && op->getNumResults() != 0)
1182 return op->emitOpError(
"callee returns void but call has results");
1185 if (!fnType.hasVoidReturn() && op->getNumResults() != 1)
1186 return op->emitOpError(
"incorrect number of results for callee");
1189 if (!fnType.hasVoidReturn() &&
1190 op->getResultTypes().front() != fnType.getReturnType()) {
1191 return op->emitOpError(
"result type mismatch: expected ")
1192 << fnType.getReturnType() <<
", but provided "
1193 << op->getResult(0).getType();
1196 return mlir::success();
1200cir::CallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1208mlir::OperandRange cir::TryCallOp::getArgOperands() {
1210 return getArgs().drop_front(1);
1214mlir::MutableOperandRange cir::TryCallOp::getArgOperandsMutable() {
1215 mlir::MutableOperandRange args = getArgsMutable();
1217 return args.slice(1, args.size() - 1);
1221mlir::Value cir::TryCallOp::getIndirectCall() {
1222 assert(isIndirect());
1223 return getOperand(0);
1227Value cir::TryCallOp::getArgOperand(
unsigned i) {
1230 return getOperand(i);
1234unsigned cir::TryCallOp::getNumArgOperands() {
1236 return this->getOperation()->getNumOperands() - 1;
1237 return this->getOperation()->getNumOperands();
1241cir::TryCallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1245mlir::ParseResult cir::TryCallOp::parse(mlir::OpAsmParser &parser,
1246 mlir::OperationState &result) {
1250void cir::TryCallOp::print(::mlir::OpAsmPrinter &p) {
1251 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() :
nullptr;
1252 cir::SideEffect sideEffect = getSideEffect();
1253 printCallCommon(*
this, getCalleeAttr(), indirectCallee, p, getNothrow(),
1254 sideEffect, getArgAttrsAttr(), getResAttrsAttr(),
1255 getNormalDest(), getUnwindDest());
1263 cir::FuncOp function) {
1265 if (op.getNumOperands() > 1)
1266 return op.emitOpError() <<
"expects at most 1 return operand";
1269 auto expectedTy = function.getFunctionType().getReturnType();
1271 (op.getNumOperands() == 0 ? cir::VoidType::get(op.getContext())
1272 : op.getOperand(0).getType());
1273 if (actualTy != expectedTy)
1274 return op.emitOpError() <<
"returns " << actualTy
1275 <<
" but enclosing function returns " << expectedTy;
1277 return mlir::success();
1280mlir::LogicalResult cir::ReturnOp::verify() {
1283 auto *fnOp = getOperation()->getParentOp();
1284 while (!isa<cir::FuncOp>(fnOp))
1285 fnOp = fnOp->getParentOp();
1298ParseResult cir::IfOp::parse(OpAsmParser &parser, OperationState &result) {
1300 result.regions.reserve(2);
1301 Region *thenRegion = result.addRegion();
1302 Region *elseRegion = result.addRegion();
1304 mlir::Builder &builder = parser.getBuilder();
1305 OpAsmParser::UnresolvedOperand cond;
1306 Type boolType = cir::BoolType::get(builder.getContext());
1308 if (parser.parseOperand(cond) ||
1309 parser.resolveOperand(cond, boolType, result.operands))
1313 mlir::SMLoc parseThenLoc = parser.getCurrentLocation();
1314 if (parser.parseRegion(*thenRegion, {}, {}))
1321 if (!parser.parseOptionalKeyword(
"else")) {
1322 mlir::SMLoc parseElseLoc = parser.getCurrentLocation();
1323 if (parser.parseRegion(*elseRegion, {}, {}))
1330 if (parser.parseOptionalAttrDict(result.attributes))
1335void cir::IfOp::print(OpAsmPrinter &p) {
1336 p <<
" " << getCondition() <<
" ";
1337 mlir::Region &thenRegion = this->getThenRegion();
1338 p.printRegion(thenRegion,
1343 mlir::Region &elseRegion = this->getElseRegion();
1344 if (!elseRegion.empty()) {
1346 p.printRegion(elseRegion,
1351 p.printOptionalAttrDict(getOperation()->getAttrs());
1357 cir::YieldOp::create(builder, loc);
1365void cir::IfOp::getSuccessorRegions(mlir::RegionBranchPoint point,
1366 SmallVectorImpl<RegionSuccessor> ®ions) {
1368 if (!point.isParent()) {
1369 regions.push_back(RegionSuccessor::parent());
1374 Region *elseRegion = &this->getElseRegion();
1375 if (elseRegion->empty())
1376 elseRegion =
nullptr;
1379 regions.push_back(RegionSuccessor(&getThenRegion()));
1381 regions.push_back(RegionSuccessor(elseRegion));
1383 regions.push_back(RegionSuccessor::parent());
1386mlir::ValueRange cir::IfOp::getSuccessorInputs(RegionSuccessor successor) {
1387 return successor.isParent() ? ValueRange(getOperation()->getResults())
1391void cir::IfOp::build(OpBuilder &builder, OperationState &result,
Value cond,
1394 assert(thenBuilder &&
"the builder callback for 'then' must be present");
1395 result.addOperands(cond);
1397 OpBuilder::InsertionGuard guard(builder);
1398 Region *thenRegion = result.addRegion();
1399 builder.createBlock(thenRegion);
1400 thenBuilder(builder, result.location);
1402 Region *elseRegion = result.addRegion();
1403 if (!withElseRegion)
1406 builder.createBlock(elseRegion);
1407 elseBuilder(builder, result.location);
1419void cir::ScopeOp::getSuccessorRegions(
1420 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1422 if (!point.isParent()) {
1423 regions.push_back(RegionSuccessor::parent());
1428 regions.push_back(RegionSuccessor(&getScopeRegion()));
1431mlir::ValueRange cir::ScopeOp::getSuccessorInputs(RegionSuccessor successor) {
1432 return successor.isParent() ? ValueRange(getOperation()->getResults())
1436void cir::ScopeOp::build(
1437 OpBuilder &builder, OperationState &result,
1438 function_ref<
void(OpBuilder &, Type &, Location)> scopeBuilder) {
1439 assert(scopeBuilder &&
"the builder callback for 'then' must be present");
1441 OpBuilder::InsertionGuard guard(builder);
1442 Region *scopeRegion = result.addRegion();
1443 builder.createBlock(scopeRegion);
1447 scopeBuilder(builder, yieldTy, result.location);
1450 result.addTypes(TypeRange{yieldTy});
1453void cir::ScopeOp::build(
1454 OpBuilder &builder, OperationState &result,
1455 function_ref<
void(OpBuilder &, Location)> scopeBuilder) {
1456 assert(scopeBuilder &&
"the builder callback for 'then' must be present");
1457 OpBuilder::InsertionGuard guard(builder);
1458 Region *scopeRegion = result.addRegion();
1459 builder.createBlock(scopeRegion);
1461 scopeBuilder(builder, result.location);
1464LogicalResult cir::ScopeOp::verify() {
1466 return emitOpError() <<
"cir.scope must not be empty since it should "
1467 "include at least an implicit cir.yield ";
1470 mlir::Block &lastBlock =
getRegion().back();
1471 if (lastBlock.empty() || !lastBlock.mightHaveTerminator() ||
1472 !lastBlock.getTerminator()->hasTrait<OpTrait::IsTerminator>())
1473 return emitOpError() <<
"last block of cir.scope must be terminated";
1477LogicalResult cir::ScopeOp::fold(FoldAdaptor ,
1478 SmallVectorImpl<OpFoldResult> &results) {
1483 if (block.getOperations().size() != 1)
1486 auto yield = dyn_cast<cir::YieldOp>(block.front());
1491 if (getNumResults() != 1 || yield.getNumOperands() != 1)
1494 results.push_back(yield.getOperand(0));
1502void cir::CleanupScopeOp::getSuccessorRegions(
1503 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1504 if (!point.isParent()) {
1505 regions.push_back(RegionSuccessor::parent());
1510 regions.push_back(RegionSuccessor(&getBodyRegion()));
1511 regions.push_back(RegionSuccessor(&getCleanupRegion()));
1515cir::CleanupScopeOp::getSuccessorInputs(RegionSuccessor successor) {
1516 return ValueRange();
1519LogicalResult cir::CleanupScopeOp::canonicalize(CleanupScopeOp op,
1520 PatternRewriter &rewriter) {
1521 auto isRegionTrivial = [](Region ®ion) {
1522 assert(!region.empty() &&
"CleanupScopeOp regions must not be empty");
1523 if (!region.hasOneBlock())
1525 Block &block = llvm::getSingleElement(region);
1526 return llvm::hasSingleElement(block) &&
1527 isa<cir::YieldOp>(llvm::getSingleElement(block));
1530 Region &body = op.getBodyRegion();
1531 Region &
cleanup = op.getCleanupRegion();
1535 if (op.getCleanupKind() == CleanupKind::EH && isRegionTrivial(body)) {
1536 rewriter.eraseOp(op);
1542 if (!isRegionTrivial(
cleanup) || !body.hasOneBlock())
1545 Block &bodyBlock = body.front();
1546 if (!isa<cir::YieldOp>(bodyBlock.getTerminator()))
1549 Operation *yield = bodyBlock.getTerminator();
1550 rewriter.inlineBlockBefore(&bodyBlock, op);
1551 rewriter.eraseOp(yield);
1552 rewriter.eraseOp(op);
1556void cir::CleanupScopeOp::build(
1557 OpBuilder &builder, OperationState &result, CleanupKind cleanupKind,
1558 function_ref<
void(OpBuilder &, Location)> bodyBuilder,
1559 function_ref<
void(OpBuilder &, Location)> cleanupBuilder) {
1560 result.addAttribute(getCleanupKindAttrName(result.name),
1561 CleanupKindAttr::get(builder.getContext(), cleanupKind));
1563 OpBuilder::InsertionGuard guard(builder);
1566 Region *bodyRegion = result.addRegion();
1567 builder.createBlock(bodyRegion);
1569 bodyBuilder(builder, result.location);
1572 Region *cleanupRegion = result.addRegion();
1573 builder.createBlock(cleanupRegion);
1575 cleanupBuilder(builder, result.location);
1590LogicalResult cir::BrOp::canonicalize(BrOp op, PatternRewriter &rewriter) {
1591 Block *src = op->getBlock();
1592 Block *dst = op.getDest();
1599 if (src->getNumSuccessors() != 1 || dst->getSinglePredecessor() != src)
1604 if (isa<cir::LabelOp, cir::IndirectBrOp>(dst->front()))
1607 auto operands = op.getDestOperands();
1608 rewriter.eraseOp(op);
1609 rewriter.mergeBlocks(dst, src, operands);
1613mlir::SuccessorOperands cir::BrOp::getSuccessorOperands(
unsigned index) {
1614 assert(index == 0 &&
"invalid successor index");
1615 return mlir::SuccessorOperands(getDestOperandsMutable());
1626mlir::SuccessorOperands
1627cir::IndirectBrOp::getSuccessorOperands(
unsigned index) {
1628 assert(index < getNumSuccessors() &&
"invalid successor index");
1629 return mlir::SuccessorOperands(getSuccOperandsMutable()[index]);
1633 OpAsmParser &parser, Type &flagType,
1634 SmallVectorImpl<Block *> &succOperandBlocks,
1637 if (failed(parser.parseCommaSeparatedList(
1638 OpAsmParser::Delimiter::Square,
1640 Block *destination = nullptr;
1641 SmallVector<OpAsmParser::UnresolvedOperand> operands;
1642 SmallVector<Type> operandTypes;
1644 if (parser.parseSuccessor(destination).failed())
1647 if (succeeded(parser.parseOptionalLParen())) {
1648 if (failed(parser.parseOperandList(
1649 operands, OpAsmParser::Delimiter::None)) ||
1650 failed(parser.parseColonTypeList(operandTypes)) ||
1651 failed(parser.parseRParen()))
1654 succOperandBlocks.push_back(destination);
1655 succOperands.emplace_back(operands);
1656 succOperandsTypes.emplace_back(operandTypes);
1659 "successor blocks")))
1665 Type flagType, SuccessorRange succs,
1666 OperandRangeRange succOperands,
1667 const TypeRangeRange &succOperandsTypes) {
1670 llvm::zip(succs, succOperands),
1673 p.printSuccessorAndUseList(std::get<0>(i), std::get<1>(i));
1676 if (!succOperands.empty())
1685mlir::SuccessorOperands cir::BrCondOp::getSuccessorOperands(
unsigned index) {
1686 assert(index < getNumSuccessors() &&
"invalid successor index");
1687 return SuccessorOperands(index == 0 ? getDestOperandsTrueMutable()
1688 : getDestOperandsFalseMutable());
1692 if (IntegerAttr condAttr = dyn_cast_if_present<IntegerAttr>(operands.front()))
1693 return condAttr.getValue().isOne() ? getDestTrue() : getDestFalse();
1701void cir::CaseOp::getSuccessorRegions(
1702 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1703 if (!point.isParent()) {
1704 regions.push_back(RegionSuccessor::parent());
1707 regions.push_back(RegionSuccessor(&getCaseRegion()));
1710mlir::ValueRange cir::CaseOp::getSuccessorInputs(RegionSuccessor successor) {
1711 return successor.isParent() ? ValueRange(getOperation()->getResults())
1715void cir::CaseOp::build(OpBuilder &builder, OperationState &result,
1716 ArrayAttr value, CaseOpKind
kind,
1717 OpBuilder::InsertPoint &insertPoint) {
1718 OpBuilder::InsertionGuard guardSwitch(builder);
1719 result.addAttribute(
"value", value);
1720 result.getOrAddProperties<Properties>().
kind =
1721 cir::CaseOpKindAttr::get(builder.getContext(),
kind);
1722 Region *caseRegion = result.addRegion();
1723 builder.createBlock(caseRegion);
1725 insertPoint = builder.saveInsertionPoint();
1732void cir::SwitchOp::getSuccessorRegions(
1733 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ion) {
1734 if (!point.isParent()) {
1735 region.push_back(RegionSuccessor::parent());
1739 region.push_back(RegionSuccessor(&getBody()));
1742mlir::ValueRange cir::SwitchOp::getSuccessorInputs(RegionSuccessor successor) {
1743 return successor.isParent() ? ValueRange(getOperation()->getResults())
1747void cir::SwitchOp::build(OpBuilder &builder, OperationState &result,
1749 assert(switchBuilder &&
"the builder callback for regions must be present");
1750 OpBuilder::InsertionGuard guardSwitch(builder);
1751 Region *switchRegion = result.addRegion();
1752 builder.createBlock(switchRegion);
1753 result.addOperands({cond});
1754 switchBuilder(builder, result.location, result);
1758 walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
1760 if (isa<cir::SwitchOp>(op) && op != *
this)
1761 return WalkResult::skip();
1763 if (
auto caseOp = dyn_cast<cir::CaseOp>(op))
1764 cases.push_back(caseOp);
1766 return WalkResult::advance();
1771 collectCases(cases);
1773 if (getBody().empty())
1776 if (!isa<YieldOp>(getBody().front().back()))
1779 if (!llvm::all_of(getBody().front(),
1780 [](Operation &op) {
return isa<CaseOp, YieldOp>(op); }))
1783 return llvm::all_of(cases, [
this](CaseOp op) {
1784 return op->getParentOfType<SwitchOp>() == *
this;
1792void cir::SwitchFlatOp::build(OpBuilder &builder, OperationState &result,
1793 Value value, Block *defaultDestination,
1794 ValueRange defaultOperands,
1796 BlockRange caseDestinations,
1799 std::vector<mlir::Attribute> caseValuesAttrs;
1800 for (
const APInt &val : caseValues)
1801 caseValuesAttrs.push_back(cir::IntAttr::get(value.getType(), val));
1802 mlir::ArrayAttr attrs = ArrayAttr::get(builder.getContext(), caseValuesAttrs);
1804 build(builder, result, value, defaultOperands, caseOperands, attrs,
1805 defaultDestination, caseDestinations);
1811 OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues,
1812 SmallVectorImpl<Block *> &caseDestinations,
1816 if (failed(parser.parseLSquare()))
1818 if (succeeded(parser.parseOptionalRSquare()))
1822 auto parseCase = [&]() {
1824 if (failed(parser.parseInteger(value)))
1827 values.push_back(cir::IntAttr::get(flagType, value));
1832 if (parser.parseColon() || parser.parseSuccessor(destination))
1834 if (!parser.parseOptionalLParen()) {
1835 if (parser.parseOperandList(operands, OpAsmParser::Delimiter::None,
1837 parser.parseColonTypeList(operandTypes) || parser.parseRParen())
1840 caseDestinations.push_back(destination);
1841 caseOperands.emplace_back(operands);
1842 caseOperandTypes.emplace_back(operandTypes);
1845 if (failed(parser.parseCommaSeparatedList(parseCase)))
1848 caseValues = ArrayAttr::get(flagType.getContext(), values);
1850 return parser.parseRSquare();
1854 Type flagType, mlir::ArrayAttr caseValues,
1855 SuccessorRange caseDestinations,
1856 OperandRangeRange caseOperands,
1857 const TypeRangeRange &caseOperandTypes) {
1867 llvm::zip(caseValues, caseDestinations),
1870 mlir::Attribute a = std::get<0>(i);
1871 p << mlir::cast<cir::IntAttr>(a).getValue();
1873 p.printSuccessorAndUseList(std::get<1>(i), caseOperands[index++]);
1888 mlir::Attribute &valueAttr) {
1890 return parser.parseAttribute(valueAttr,
"value", attr);
1894 p.printAttribute(value);
1897mlir::LogicalResult cir::GlobalOp::verify() {
1900 if (getInitialValue().has_value()) {
1906 if ((getStaticLocalGuard().has_value() || getTlsModel()) &&
1907 (!getCtorRegion().empty() || !getDtorRegion().empty()))
1909 "Cannot have a thread-local or static-local global-op "
1910 "with a constructor or destructor, they require in-function "
1911 "initialization via LocalInitOp");
1913 if (getAliasee().has_value()) {
1914 if (getInitialValue().has_value() || !getCtorRegion().empty() ||
1915 !getDtorRegion().empty())
1916 return emitOpError(
"global alias shall not have an initializer or "
1917 "constructor/destructor regions");
1926void cir::GlobalOp::build(
1927 OpBuilder &odsBuilder, OperationState &odsState, llvm::StringRef sym_name,
1928 mlir::Type sym_type,
bool isConstant,
1929 mlir::ptr::MemorySpaceAttrInterface addrSpace,
1930 cir::GlobalLinkageKind linkage,
1931 function_ref<
void(OpBuilder &, Location)> ctorBuilder,
1932 function_ref<
void(OpBuilder &, Location)> dtorBuilder) {
1933 odsState.addAttribute(getSymNameAttrName(odsState.name),
1934 odsBuilder.getStringAttr(sym_name));
1935 odsState.addAttribute(getSymTypeAttrName(odsState.name),
1936 mlir::TypeAttr::get(sym_type));
1937 auto &properties = odsState.getOrAddProperties<cir::GlobalOp::Properties>();
1938 properties.setConstant(isConstant);
1942 odsState.addAttribute(getAddrSpaceAttrName(odsState.name), addrSpace);
1944 cir::GlobalLinkageKindAttr linkageAttr =
1945 cir::GlobalLinkageKindAttr::get(odsBuilder.getContext(), linkage);
1946 odsState.addAttribute(getLinkageAttrName(odsState.name), linkageAttr);
1948 Region *ctorRegion = odsState.addRegion();
1950 odsBuilder.createBlock(ctorRegion);
1951 ctorBuilder(odsBuilder, odsState.location);
1954 Region *dtorRegion = odsState.addRegion();
1956 odsBuilder.createBlock(dtorRegion);
1957 dtorBuilder(odsBuilder, odsState.location);
1966void cir::GlobalOp::getSuccessorRegions(
1967 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1969 if (!point.isParent()) {
1970 regions.push_back(RegionSuccessor::parent());
1975 Region *ctorRegion = &this->getCtorRegion();
1976 if (ctorRegion->empty())
1977 ctorRegion =
nullptr;
1980 Region *dtorRegion = &this->getDtorRegion();
1981 if (dtorRegion->empty())
1982 dtorRegion =
nullptr;
1986 regions.push_back(RegionSuccessor(ctorRegion));
1988 regions.push_back(RegionSuccessor(dtorRegion));
1991mlir::ValueRange cir::GlobalOp::getSuccessorInputs(RegionSuccessor successor) {
1992 return successor.isParent() ? ValueRange(getOperation()->getResults())
1997 TypeAttr type, Attribute initAttr,
1998 mlir::Region &ctorRegion,
1999 mlir::Region &dtorRegion) {
2000 auto printType = [&]() { p <<
": " << type; };
2003 if (op.isDeclaration() || op.getAliasee()) {
2009 if (!ctorRegion.empty()) {
2013 p.printRegion(ctorRegion,
2022 if (!dtorRegion.empty()) {
2024 p.printRegion(dtorRegion,
2032 Attribute &initialValueAttr,
2033 mlir::Region &ctorRegion,
2034 mlir::Region &dtorRegion) {
2036 if (parser.parseOptionalEqual().failed()) {
2039 if (parser.parseColonType(opTy))
2044 if (!parser.parseOptionalKeyword(
"ctor")) {
2045 if (parser.parseColonType(opTy))
2047 auto parseLoc = parser.getCurrentLocation();
2048 if (parser.parseRegion(ctorRegion, {}, {}))
2059 assert(mlir::isa<mlir::TypedAttr>(initialValueAttr) &&
2060 "Non-typed attrs shouldn't appear here.");
2061 auto typedAttr = mlir::cast<mlir::TypedAttr>(initialValueAttr);
2062 opTy = typedAttr.getType();
2067 if (!parser.parseOptionalKeyword(
"dtor")) {
2068 auto parseLoc = parser.getCurrentLocation();
2069 if (parser.parseRegion(dtorRegion, {}, {}))
2076 typeAttr = TypeAttr::get(opTy);
2085cir::GetGlobalOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2088 mlir::Operation *op =
2089 symbolTable.lookupNearestSymbolFrom(*
this, getNameAttr());
2090 if (op ==
nullptr || !(isa<GlobalOp>(op) || isa<FuncOp>(op)))
2091 return emitOpError(
"'")
2093 <<
"' does not reference a valid cir.global or cir.func";
2096 mlir::ptr::MemorySpaceAttrInterface symAddrSpaceAttr{};
2097 if (
auto g = dyn_cast<GlobalOp>(op)) {
2098 symTy = g.getSymType();
2099 symAddrSpaceAttr = g.getAddrSpaceAttr();
2102 if (getTls() && !g.getTlsModel())
2103 return emitOpError(
"access to global not marked thread local");
2108 bool getGlobalIsStaticLocal = getStaticLocal();
2109 bool globalIsStaticLocal = g.getStaticLocalGuard().has_value();
2110 if (getGlobalIsStaticLocal != globalIsStaticLocal &&
2111 !getOperation()->getParentOfType<cir::GlobalOp>())
2112 return emitOpError(
"static_local attribute mismatch");
2113 }
else if (
auto f = dyn_cast<FuncOp>(op)) {
2114 symTy = f.getFunctionType();
2116 llvm_unreachable(
"Unexpected operation for GetGlobalOp");
2119 auto resultType = dyn_cast<PointerType>(getAddr().
getType());
2120 if (!resultType || symTy != resultType.getPointee())
2121 return emitOpError(
"result type pointee type '")
2122 << resultType.getPointee() <<
"' does not match type " << symTy
2123 <<
" of the global @" <<
getName();
2125 if (symAddrSpaceAttr != resultType.getAddrSpace()) {
2126 return emitOpError()
2127 <<
"result type address space does not match the address "
2128 "space of the global @"
2140cir::VTableAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2146 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*
this, getNameAttr());
2148 return emitOpError(
"'")
2149 <<
name <<
"' does not reference a valid cir.global";
2150 std::optional<mlir::Attribute> init = op.getInitialValue();
2153 if (!isa<cir::VTableAttr>(*init))
2154 return emitOpError(
"Expected #cir.vtable in initializer for global '")
2164cir::VTTAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2173 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*
this, getNameAttr());
2175 return emitOpError(
"'")
2176 <<
name <<
"' does not reference a valid cir.global";
2177 std::optional<mlir::Attribute> init = op.getInitialValue();
2180 if (!isa<cir::ConstArrayAttr>(*init))
2182 "Expected constant array in initializer for global VTT '")
2187LogicalResult cir::VTTAddrPointOp::verify() {
2189 if (
getName() && getSymAddr())
2190 return emitOpError(
"should use either a symbol or value, but not both");
2196 mlir::Type resultType = getAddr().getType();
2197 mlir::Type resTy = cir::PointerType::get(
2198 cir::PointerType::get(cir::VoidType::get(getContext())));
2200 if (resultType != resTy)
2201 return emitOpError(
"result type must be ")
2202 << resTy <<
", but provided result type is " << resultType;
2214void cir::FuncOp::build(OpBuilder &builder, OperationState &result,
2215 StringRef name, FuncType type,
2216 GlobalLinkageKind linkage, CallingConv callingConv) {
2218 result.addAttribute(SymbolTable::getSymbolAttrName(),
2219 builder.getStringAttr(name));
2220 result.addAttribute(getFunctionTypeAttrName(result.name),
2221 TypeAttr::get(type));
2222 result.addAttribute(
2224 GlobalLinkageKindAttr::get(builder.getContext(), linkage));
2225 result.addAttribute(getCallingConvAttrName(result.name),
2226 CallingConvAttr::get(builder.getContext(), callingConv));
2234cir::AnnotationAttr::verify(function_ref<InFlightDiagnostic()> emitError,
2235 mlir::StringAttr name, mlir::ArrayAttr args) {
2238 for (mlir::Attribute arg : args) {
2239 if (!isa<mlir::StringAttr, mlir::IntegerAttr>(arg))
2240 return emitError() <<
"annotation args must be StringAttr or IntegerAttr,"
2246ParseResult cir::FuncOp::parse(OpAsmParser &parser, OperationState &state) {
2247 llvm::SMLoc loc = parser.getCurrentLocation();
2248 mlir::Builder &builder = parser.getBuilder();
2250 mlir::StringAttr builtinNameAttr = getBuiltinAttrName(state.name);
2251 mlir::StringAttr coroutineNameAttr = getCoroutineAttrName(state.name);
2252 mlir::StringAttr inlineKindNameAttr = getInlineKindAttrName(state.name);
2253 mlir::StringAttr lambdaNameAttr = getLambdaAttrName(state.name);
2254 mlir::StringAttr noProtoNameAttr = getNoProtoAttrName(state.name);
2255 mlir::StringAttr comdatNameAttr = getComdatAttrName(state.name);
2256 mlir::StringAttr visNameAttr = getSymVisibilityAttrName(state.name);
2257 mlir::StringAttr dsoLocalNameAttr = getDsoLocalAttrName(state.name);
2258 mlir::StringAttr specialMemberAttr = getCxxSpecialMemberAttrName(state.name);
2260 if (::mlir::succeeded(parser.parseOptionalKeyword(builtinNameAttr.strref())))
2261 state.addAttribute(builtinNameAttr, parser.getBuilder().getUnitAttr());
2262 if (::mlir::succeeded(
2263 parser.parseOptionalKeyword(coroutineNameAttr.strref())))
2264 state.addAttribute(coroutineNameAttr, parser.getBuilder().getUnitAttr());
2267 cir::InlineKindAttr inlineKindAttr;
2271 state.addAttribute(inlineKindNameAttr, inlineKindAttr);
2273 if (::mlir::succeeded(parser.parseOptionalKeyword(lambdaNameAttr.strref())))
2274 state.addAttribute(lambdaNameAttr, parser.getBuilder().getUnitAttr());
2275 if (parser.parseOptionalKeyword(noProtoNameAttr).succeeded())
2276 state.addAttribute(noProtoNameAttr, parser.getBuilder().getUnitAttr());
2278 if (parser.parseOptionalKeyword(comdatNameAttr).succeeded())
2279 state.addAttribute(comdatNameAttr, parser.getBuilder().getUnitAttr());
2283 GlobalLinkageKindAttr::get(
2284 parser.getContext(),
2286 parser, GlobalLinkageKind::ExternalLinkage)));
2288 ::llvm::StringRef visAttrStr;
2289 if (parser.parseOptionalKeyword(&visAttrStr, {
"private",
"public",
"nested"})
2291 state.addAttribute(visNameAttr,
2292 parser.getBuilder().getStringAttr(visAttrStr));
2295 state.getOrAddProperties<cir::FuncOp::Properties>().global_visibility =
2298 if (parser.parseOptionalKeyword(dsoLocalNameAttr).succeeded())
2299 state.addAttribute(dsoLocalNameAttr, parser.getBuilder().getUnitAttr());
2301 StringAttr nameAttr;
2302 if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
2308 bool isVariadic =
false;
2309 if (function_interface_impl::parseFunctionSignatureWithArguments(
2310 parser,
true, arguments, isVariadic, resultTypes,
2315 bool argAttrsEmpty =
true;
2316 for (OpAsmParser::Argument &arg : arguments) {
2317 argTypes.push_back(
arg.type);
2321 argAttrs.push_back(
arg.attrs);
2323 argAttrsEmpty =
false;
2327 if (resultTypes.size() > 1 || resultAttrs.size() > 1)
2328 return parser.emitError(
2329 loc,
"functions with multiple return types are not supported");
2331 mlir::Type returnType =
2332 (resultTypes.empty() ? cir::VoidType::get(builder.getContext())
2333 : resultTypes.front());
2335 cir::FuncType fnType = cir::FuncType::get(argTypes, returnType, isVariadic);
2339 state.addAttribute(getFunctionTypeAttrName(state.name),
2340 TypeAttr::get(fnType));
2342 if (!resultAttrs.empty() && resultAttrs[0])
2344 getResAttrsAttrName(state.name),
2345 mlir::ArrayAttr::get(parser.getContext(), {resultAttrs[0]}));
2348 state.addAttribute(getArgAttrsAttrName(state.name),
2349 mlir::ArrayAttr::get(parser.getContext(), argAttrs));
2351 bool hasAlias =
false;
2352 mlir::StringAttr aliaseeNameAttr = getAliaseeAttrName(state.name);
2353 if (parser.parseOptionalKeyword(
"alias").succeeded()) {
2354 if (parser.parseLParen().failed())
2356 mlir::StringAttr aliaseeAttr;
2357 if (parser.parseOptionalSymbolName(aliaseeAttr).failed())
2359 state.addAttribute(aliaseeNameAttr, FlatSymbolRefAttr::get(aliaseeAttr));
2360 if (parser.parseRParen().failed())
2365 mlir::StringAttr personalityNameAttr = getPersonalityAttrName(state.name);
2366 if (parser.parseOptionalKeyword(
"personality").succeeded()) {
2367 if (parser.parseLParen().failed())
2369 mlir::StringAttr personalityAttr;
2370 if (parser.parseOptionalSymbolName(personalityAttr).failed())
2372 state.addAttribute(personalityNameAttr,
2373 FlatSymbolRefAttr::get(personalityAttr));
2374 if (parser.parseRParen().failed())
2379 mlir::StringAttr callConvNameAttr = getCallingConvAttrName(state.name);
2380 cir::CallingConv callConv = cir::CallingConv::C;
2381 if (parser.parseOptionalKeyword(
"cc").succeeded()) {
2382 if (parser.parseLParen().failed())
2385 return parser.emitError(loc) <<
"unknown calling convention";
2386 if (parser.parseRParen().failed())
2389 state.addAttribute(callConvNameAttr,
2390 cir::CallingConvAttr::get(parser.getContext(), callConv));
2392 auto parseGlobalDtorCtor =
2393 [&](StringRef keyword,
2394 llvm::function_ref<void(std::optional<int> prio)> createAttr)
2395 -> mlir::LogicalResult {
2396 if (mlir::succeeded(parser.parseOptionalKeyword(keyword))) {
2397 std::optional<int> priority;
2398 if (mlir::succeeded(parser.parseOptionalLParen())) {
2399 auto parsedPriority = mlir::FieldParser<int>::parse(parser);
2400 if (mlir::failed(parsedPriority))
2401 return parser.emitError(parser.getCurrentLocation(),
2402 "failed to parse 'priority', of type 'int'");
2403 priority = parsedPriority.value_or(
int());
2405 if (parser.parseRParen())
2408 createAttr(priority);
2414 if (parser.parseOptionalKeyword(
"special_member").succeeded()) {
2415 if (parser.parseLess().failed())
2418 mlir::Attribute
attr;
2419 if (parser.parseAttribute(attr).failed())
2421 if (!mlir::isa<cir::CXXCtorAttr, cir::CXXDtorAttr, cir::CXXAssignAttr>(
2423 return parser.emitError(parser.getCurrentLocation(),
2424 "expected a C++ special member attribute");
2425 state.addAttribute(specialMemberAttr, attr);
2427 if (parser.parseGreater().failed())
2431 if (parseGlobalDtorCtor(
"global_ctor", [&](std::optional<int> priority) {
2432 mlir::IntegerAttr globalCtorPriorityAttr =
2433 builder.getI32IntegerAttr(priority.value_or(65535));
2434 state.addAttribute(getGlobalCtorPriorityAttrName(state.name),
2435 globalCtorPriorityAttr);
2439 if (parseGlobalDtorCtor(
"global_dtor", [&](std::optional<int> priority) {
2440 mlir::IntegerAttr globalDtorPriorityAttr =
2441 builder.getI32IntegerAttr(priority.value_or(65535));
2442 state.addAttribute(getGlobalDtorPriorityAttrName(state.name),
2443 globalDtorPriorityAttr);
2447 if (parser.parseOptionalKeyword(
"side_effect").succeeded()) {
2448 cir::SideEffect sideEffect;
2450 if (parser.parseLParen().failed() ||
2452 parser.parseRParen().failed())
2455 auto attr = cir::SideEffectAttr::get(parser.getContext(), sideEffect);
2456 state.addAttribute(CIRDialect::getSideEffectAttrName(), attr);
2460 mlir::StringAttr annotationsNameAttr = getAnnotationsAttrName(state.name);
2461 mlir::ArrayAttr annotationsAttr;
2462 if (parser.parseOptionalAttribute(annotationsAttr).has_value() &&
2464 state.addAttribute(annotationsNameAttr, annotationsAttr);
2467 NamedAttrList parsedAttrs;
2468 if (parser.parseOptionalAttrDictWithKeyword(parsedAttrs))
2471 for (StringRef disallowed : cir::FuncOp::getAttributeNames()) {
2472 if (parsedAttrs.get(disallowed))
2473 return parser.emitError(loc,
"attribute '")
2475 <<
"' should not be specified in the explicit attribute list";
2478 state.attributes.append(parsedAttrs);
2481 auto *body = state.addRegion();
2482 OptionalParseResult parseResult = parser.parseOptionalRegion(
2483 *body, arguments,
false);
2484 if (parseResult.has_value()) {
2486 return parser.emitError(loc,
"function alias shall not have a body");
2487 if (failed(*parseResult))
2491 return parser.emitError(loc,
"expected non-empty function body");
2500bool cir::FuncOp::isDeclaration() {
2503 std::optional<StringRef> aliasee = getAliasee();
2505 return getFunctionBody().empty();
2511bool cir::FuncOp::isCXXSpecialMemberFunction() {
2512 return getCxxSpecialMemberAttr() !=
nullptr;
2515bool cir::FuncOp::isCxxConstructor() {
2516 auto attr = getCxxSpecialMemberAttr();
2517 return attr && dyn_cast<CXXCtorAttr>(attr);
2520bool cir::FuncOp::isCxxDestructor() {
2521 auto attr = getCxxSpecialMemberAttr();
2522 return attr && dyn_cast<CXXDtorAttr>(attr);
2525bool cir::FuncOp::isCxxSpecialAssignment() {
2526 auto attr = getCxxSpecialMemberAttr();
2527 return attr && dyn_cast<CXXAssignAttr>(attr);
2530std::optional<CtorKind> cir::FuncOp::getCxxConstructorKind() {
2531 mlir::Attribute
attr = getCxxSpecialMemberAttr();
2533 if (
auto ctor = dyn_cast<CXXCtorAttr>(attr))
2534 return ctor.getCtorKind();
2536 return std::nullopt;
2539std::optional<AssignKind> cir::FuncOp::getCxxSpecialAssignKind() {
2540 mlir::Attribute
attr = getCxxSpecialMemberAttr();
2542 if (
auto assign = dyn_cast<CXXAssignAttr>(attr))
2543 return assign.getAssignKind();
2545 return std::nullopt;
2548bool cir::FuncOp::isCxxTrivialMemberFunction() {
2549 mlir::Attribute
attr = getCxxSpecialMemberAttr();
2551 if (
auto ctor = dyn_cast<CXXCtorAttr>(attr))
2552 return ctor.getIsTrivial();
2553 if (
auto dtor = dyn_cast<CXXDtorAttr>(attr))
2554 return dtor.getIsTrivial();
2555 if (
auto assign = dyn_cast<CXXAssignAttr>(attr))
2556 return assign.getIsTrivial();
2561mlir::Region *cir::FuncOp::getCallableRegion() {
2567void cir::FuncOp::print(OpAsmPrinter &p) {
2585 if (getLinkage() != GlobalLinkageKind::ExternalLinkage)
2586 p <<
' ' << stringifyGlobalLinkageKind(getLinkage());
2588 mlir::SymbolTable::Visibility vis = getVisibility();
2589 if (vis != mlir::SymbolTable::Visibility::Public)
2592 if (getGlobalVisibility() != cir::VisibilityKind::Default)
2593 p <<
' ' << stringifyVisibilityKind(getGlobalVisibility());
2599 p.printSymbolName(getSymName());
2600 cir::FuncType fnType = getFunctionType();
2601 function_interface_impl::printFunctionSignature(
2602 p, *
this, fnType.getInputs(), fnType.isVarArg(), fnType.getReturnTypes());
2604 if (std::optional<StringRef> aliaseeName = getAliasee()) {
2606 p.printSymbolName(*aliaseeName);
2610 if (getCallingConv() != cir::CallingConv::C) {
2612 p << stringifyCallingConv(getCallingConv());
2616 if (std::optional<StringRef> personalityName = getPersonality()) {
2617 p <<
" personality(";
2618 p.printSymbolName(*personalityName);
2622 if (
auto specialMemberAttr = getCxxSpecialMember()) {
2623 p <<
" special_member<";
2624 p.printAttribute(*specialMemberAttr);
2628 if (
auto globalCtorPriority = getGlobalCtorPriority()) {
2629 p <<
" global_ctor";
2630 if (globalCtorPriority.value() != 65535)
2631 p <<
"(" << globalCtorPriority.value() <<
")";
2634 if (
auto globalDtorPriority = getGlobalDtorPriority()) {
2635 p <<
" global_dtor";
2636 if (globalDtorPriority.value() != 65535)
2637 p <<
"(" << globalDtorPriority.value() <<
")";
2640 if (std::optional<cir::SideEffect> sideEffect = getSideEffect();
2641 sideEffect && *sideEffect != cir::SideEffect::All) {
2642 p <<
" side_effect(";
2643 p << stringifySideEffect(*sideEffect);
2647 if (mlir::ArrayAttr annotations = getAnnotationsAttr()) {
2649 p.printAttribute(annotations);
2652 function_interface_impl::printFunctionAttributes(
2653 p, *
this, cir::FuncOp::getAttributeNames());
2656 Region &body = getOperation()->getRegion(0);
2657 if (!body.empty()) {
2659 p.printRegion(body,
false,
2664mlir::LogicalResult cir::FuncOp::verify() {
2666 if (!isDeclaration() && getCoroutine()) {
2667 bool foundAwait =
false;
2668 int coroBodyCount = 0;
2669 this->walk([&](Operation *op) {
2670 if (
auto await = dyn_cast<AwaitOp>(op)) {
2672 }
else if (isa<CoroBodyOp>(op)) {
2674 if (coroBodyCount > 1) {
2675 return mlir::WalkResult::interrupt();
2678 return mlir::WalkResult::advance();
2681 return emitOpError()
2682 <<
"coroutine body must use at least one cir.await op";
2683 if (coroBodyCount != 1)
2684 return emitOpError()
2685 <<
"coroutine function must have exactly one cir.body op";
2688 llvm::SmallSet<llvm::StringRef, 16> labels;
2689 llvm::SmallSet<llvm::StringRef, 16> gotos;
2690 llvm::SmallSet<llvm::StringRef, 16> blockAddresses;
2691 bool invalidBlockAddress =
false;
2692 getOperation()->walk([&](mlir::Operation *op) {
2693 if (
auto lab = dyn_cast<cir::LabelOp>(op)) {
2694 labels.insert(lab.getLabel());
2695 }
else if (
auto goTo = dyn_cast<cir::GotoOp>(op)) {
2696 gotos.insert(goTo.getLabel());
2697 }
else if (
auto blkAdd = dyn_cast<cir::BlockAddressOp>(op)) {
2698 if (blkAdd.getBlockAddrInfoAttr().getFunc().getAttr() != getSymName()) {
2700 invalidBlockAddress =
true;
2701 return mlir::WalkResult::interrupt();
2703 blockAddresses.insert(blkAdd.getBlockAddrInfoAttr().getLabel());
2705 return mlir::WalkResult::advance();
2708 if (invalidBlockAddress)
2709 return emitOpError() <<
"blockaddress references a different function";
2711 llvm::SmallSet<llvm::StringRef, 16> mismatched;
2712 if (!labels.empty() || !gotos.empty()) {
2713 mismatched = llvm::set_difference(gotos, labels);
2715 if (!mismatched.empty())
2716 return emitOpError() <<
"goto/label mismatch";
2721 if (!labels.empty() || !blockAddresses.empty()) {
2722 mismatched = llvm::set_difference(blockAddresses, labels);
2724 if (!mismatched.empty())
2725 return emitOpError()
2726 <<
"expects an existing label target in the referenced function";
2738 bool noUnsignedWrap,
bool saturated,
2740 bool noWrap = noSignedWrap || noUnsignedWrap;
2741 if (!isa<cir::IntType>(op->getResultTypes()[0]) && noWrap)
2742 return op->emitError()
2743 <<
"only operations on integer values may have nsw/nuw flags";
2744 if (hasSat && saturated && !isa<cir::IntType>(op->getResultTypes()[0]))
2745 return op->emitError()
2746 <<
"only operations on integer values may have sat flag";
2747 if (hasSat && noWrap && saturated)
2748 return op->emitError()
2749 <<
"the nsw/nuw flags and the saturated flag are mutually exclusive";
2750 return mlir::success();
2753LogicalResult cir::AddOp::verify() {
2755 getNoUnsignedWrap(), getSaturated(),
2759LogicalResult cir::SubOp::verify() {
2761 getNoUnsignedWrap(), getSaturated(),
2765LogicalResult cir::MulOp::verify() {
2767 getNoUnsignedWrap(),
false,
2780void cir::TernaryOp::getSuccessorRegions(
2781 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
2783 if (!point.isParent()) {
2784 regions.push_back(RegionSuccessor::parent());
2790 regions.push_back(RegionSuccessor(&getTrueRegion()));
2791 regions.push_back(RegionSuccessor(&getFalseRegion()));
2794mlir::ValueRange cir::TernaryOp::getSuccessorInputs(RegionSuccessor successor) {
2795 return successor.isParent() ? ValueRange(getOperation()->getResults())
2799void cir::TernaryOp::build(
2800 OpBuilder &builder, OperationState &result,
Value cond,
2801 function_ref<
void(OpBuilder &, Location)> trueBuilder,
2802 function_ref<
void(OpBuilder &, Location)> falseBuilder) {
2803 result.addOperands(cond);
2804 OpBuilder::InsertionGuard guard(builder);
2805 Region *trueRegion = result.addRegion();
2806 builder.createBlock(trueRegion);
2807 trueBuilder(builder, result.location);
2808 Region *falseRegion = result.addRegion();
2809 builder.createBlock(falseRegion);
2810 falseBuilder(builder, result.location);
2815 if (trueRegion->back().mightHaveTerminator())
2816 yield = dyn_cast_or_null<cir::YieldOp>(trueRegion->back().getTerminator());
2817 if (!yield && falseRegion->back().mightHaveTerminator())
2818 yield = dyn_cast_or_null<cir::YieldOp>(falseRegion->back().getTerminator());
2820 assert((!yield || yield.getNumOperands() <= 1) &&
2821 "expected zero or one result type");
2822 if (yield && yield.getNumOperands() == 1)
2823 result.addTypes(TypeRange{yield.getOperandTypes().front()});
2830OpFoldResult cir::SelectOp::fold(FoldAdaptor adaptor) {
2831 mlir::Attribute
condition = adaptor.getCondition();
2833 bool conditionValue = mlir::cast<cir::BoolAttr>(
condition).getValue();
2834 return conditionValue ? getTrueValue() : getFalseValue();
2838 mlir::Attribute trueValue = adaptor.getTrueValue();
2839 mlir::Attribute falseValue = adaptor.getFalseValue();
2840 if (trueValue == falseValue)
2842 if (getTrueValue() == getFalseValue())
2843 return getTrueValue();
2848LogicalResult cir::SelectOp::verify() {
2850 auto condTy = dyn_cast<cir::VectorType>(getCondition().
getType());
2857 if (!isa<cir::VectorType>(getTrueValue().
getType()) ||
2858 !isa<cir::VectorType>(getFalseValue().
getType())) {
2859 return emitOpError()
2860 <<
"expected both true and false operands to be vector types "
2861 "when the condition is a vector boolean type";
2870LogicalResult cir::ShiftOp::verify() {
2871 mlir::Operation *op = getOperation();
2872 auto op0VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(0).getType());
2873 auto op1VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(1).getType());
2874 if (!op0VecTy ^ !op1VecTy)
2875 return emitOpError() <<
"input types cannot be one vector and one scalar";
2878 if (op0VecTy.getSize() != op1VecTy.getSize())
2879 return emitOpError() <<
"input vector types must have the same size";
2881 auto opResultTy = mlir::dyn_cast<cir::VectorType>(
getType());
2883 return emitOpError() <<
"the type of the result must be a vector "
2884 <<
"if it is vector shift";
2886 auto op0VecEleTy = mlir::cast<cir::IntType>(op0VecTy.getElementType());
2887 auto op1VecEleTy = mlir::cast<cir::IntType>(op1VecTy.getElementType());
2888 if (op0VecEleTy.getWidth() != op1VecEleTy.getWidth())
2889 return emitOpError()
2890 <<
"vector operands do not have the same elements sizes";
2892 auto resVecEleTy = mlir::cast<cir::IntType>(opResultTy.getElementType());
2893 if (op0VecEleTy.getWidth() != resVecEleTy.getWidth())
2894 return emitOpError() <<
"vector operands and result type do not have the "
2895 "same elements sizes";
2898 return mlir::success();
2905LogicalResult cir::LabelOp::verify() {
2906 mlir::Operation *op = getOperation();
2907 mlir::Block *blk = op->getBlock();
2908 if (&blk->front() != op)
2909 return emitError() <<
"must be the first operation in a block";
2911 return mlir::success();
2918OpFoldResult cir::IncOp::fold(FoldAdaptor adaptor) {
2919 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
2920 return adaptor.getInput();
2928OpFoldResult cir::DecOp::fold(FoldAdaptor adaptor) {
2929 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
2930 return adaptor.getInput();
2938OpFoldResult cir::MinusOp::fold(FoldAdaptor adaptor) {
2939 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
2940 return adaptor.getInput();
2943 if (
auto srcConst = getInput().getDefiningOp<cir::ConstantOp>())
2944 if (mlir::isa<cir::BoolType>(srcConst.getType()))
2945 return srcConst.getResult();
2948 if (mlir::Attribute attr = adaptor.getInput()) {
2949 if (
auto intAttr = mlir::dyn_cast<cir::IntAttr>(attr)) {
2950 APInt val = intAttr.getValue();
2952 return cir::IntAttr::get(
getType(), val);
2954 if (
auto fpAttr = mlir::dyn_cast<cir::FPAttr>(attr)) {
2955 APFloat val = fpAttr.getValue();
2957 return cir::FPAttr::get(
getType(), val);
2968OpFoldResult cir::NotOp::fold(FoldAdaptor adaptor) {
2969 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
2970 return adaptor.getInput();
2975 if (mlir::Attribute attr = adaptor.getInput()) {
2976 if (
auto intAttr = mlir::dyn_cast<cir::IntAttr>(attr)) {
2977 APInt val = intAttr.getValue();
2979 return cir::IntAttr::get(
getType(), val);
2981 if (
auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr))
2982 return cir::BoolAttr::get(getContext(), !boolAttr.getValue());
2993 mlir::Type resultTy) {
2996 mlir::Type inputMemberTy;
2997 mlir::Type resultMemberTy;
2998 if (mlir::isa<cir::DataMemberType>(src.getType())) {
3000 mlir::cast<cir::DataMemberType>(src.getType()).getMemberTy();
3001 resultMemberTy = mlir::cast<cir::DataMemberType>(resultTy).getMemberTy();
3004 if (inputMemberTy != resultMemberTy)
3005 return op->emitOpError()
3006 <<
"member types of the operand and the result do not match";
3008 return mlir::success();
3011LogicalResult cir::BaseDataMemberOp::verify() {
3015LogicalResult cir::DerivedDataMemberOp::verify() {
3023LogicalResult cir::BaseMethodOp::verify() {
3027LogicalResult cir::DerivedMethodOp::verify() {
3035void cir::AwaitOp::build(OpBuilder &builder, OperationState &result,
3039 result.addAttribute(getKindAttrName(result.name),
3040 cir::AwaitKindAttr::get(builder.getContext(),
kind));
3042 OpBuilder::InsertionGuard guard(builder);
3043 Region *readyRegion = result.addRegion();
3044 builder.createBlock(readyRegion);
3045 readyBuilder(builder, result.location);
3049 OpBuilder::InsertionGuard guard(builder);
3050 Region *suspendRegion = result.addRegion();
3051 builder.createBlock(suspendRegion);
3052 suspendBuilder(builder, result.location);
3056 OpBuilder::InsertionGuard guard(builder);
3057 Region *resumeRegion = result.addRegion();
3058 builder.createBlock(resumeRegion);
3059 resumeBuilder(builder, result.location);
3063void cir::AwaitOp::getSuccessorRegions(
3064 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
3067 if (!point.isParent()) {
3068 regions.push_back(RegionSuccessor::parent());
3075 regions.push_back(RegionSuccessor(&this->getReady()));
3076 regions.push_back(RegionSuccessor(&this->getSuspend()));
3077 regions.push_back(RegionSuccessor(&this->getResume()));
3080mlir::ValueRange cir::AwaitOp::getSuccessorInputs(RegionSuccessor successor) {
3081 if (successor.isParent())
3082 return getOperation()->getResults();
3083 if (successor == &getReady())
3084 return getReady().getArguments();
3085 if (successor == &getSuspend())
3086 return getSuspend().getArguments();
3087 if (successor == &getResume())
3088 return getResume().getArguments();
3089 llvm_unreachable(
"invalid region successor");
3092LogicalResult cir::AwaitOp::verify() {
3093 if (!isa<ConditionOp>(this->getReady().back().getTerminator()))
3094 return emitOpError(
"ready region must end with cir.condition");
3098LogicalResult cir::CoReturnOp::verify() {
3099 if (!getOperation()->getParentOfType<CoroBodyOp>())
3100 return emitOpError(
"must be inside a cir.coro.body");
3108void cir::CoroBodyOp::getSuccessorRegions(
3109 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
3110 if (!point.isParent()) {
3111 regions.push_back(RegionSuccessor::parent());
3115 regions.push_back(RegionSuccessor(&getBody()));
3119cir::CoroBodyOp::getSuccessorInputs(RegionSuccessor successor) {
3120 return ValueRange();
3123LogicalResult cir::CoroBodyOp::verify() {
3124 if (!getOperation()->getParentOfType<FuncOp>().getCoroutine())
3125 return emitOpError(
"enclosing function must be a coroutine");
3129void cir::CoroBodyOp::build(OpBuilder &builder, OperationState &result,
3131 assert(bodyBuilder &&
3132 "the builder callback for 'CoroBodyOp' must be present");
3133 OpBuilder::InsertionGuard guard(builder);
3135 Region *bodyRegion = result.addRegion();
3136 builder.createBlock(bodyRegion);
3137 bodyBuilder(builder, result.location);
3144LogicalResult cir::CopyOp::verify() {
3146 if (!
getType().getPointee().hasTrait<DataLayoutTypeInterface::Trait>())
3147 return emitError() <<
"missing data layout for pointee type";
3149 if (getSkipTailPadding() &&
3150 !mlir::isa<cir::RecordType>(
getType().getPointee()))
3152 <<
"skip_tail_padding is only valid for record pointee types";
3154 return mlir::success();
3161LogicalResult cir::GetRuntimeMemberOp::verify() {
3162 auto recordTy = mlir::cast<RecordType>(getAddr().
getType().getPointee());
3163 cir::DataMemberType memberPtrTy = getMember().getType();
3165 if (recordTy != memberPtrTy.getClassTy())
3166 return emitError() <<
"record type does not match the member pointer type";
3167 if (
getType().getPointee() != memberPtrTy.getMemberTy())
3168 return emitError() <<
"result type does not match the member pointer type";
3169 return mlir::success();
3176LogicalResult cir::GetMethodOp::verify() {
3177 cir::MethodType methodTy = getMethod().getType();
3180 cir::PointerType objectPtrTy = getObject().getType();
3181 mlir::Type objectTy = objectPtrTy.getPointee();
3183 if (methodTy.getClassTy() != objectTy)
3184 return emitError() <<
"method class type and object type do not match";
3187 auto calleeTy = mlir::cast<cir::FuncType>(getCallee().
getType().getPointee());
3188 cir::FuncType methodFuncTy = methodTy.getMemberFuncTy();
3195 if (methodFuncTy.getReturnType() != calleeTy.getReturnType())
3197 <<
"method return type and callee return type do not match";
3202 if (calleeArgsTy.empty())
3203 return emitError() <<
"callee parameter list lacks receiver object ptr";
3205 auto calleeThisArgPtrTy = mlir::dyn_cast<cir::PointerType>(calleeArgsTy[0]);
3206 if (!calleeThisArgPtrTy ||
3207 !mlir::isa<cir::VoidType>(calleeThisArgPtrTy.getPointee())) {
3209 <<
"the first parameter of callee must be a void pointer";
3212 if (calleeArgsTy.slice(1) != methodFuncArgsTy)
3214 <<
"callee parameters and method parameters do not match";
3216 return mlir::success();
3223LogicalResult cir::GetMemberOp::verify() {
3224 const auto recordTy = dyn_cast<RecordType>(getAddrTy().getPointee());
3226 return emitError() <<
"expected pointer to a record type";
3228 if (recordTy.getMembers().size() <=
getIndex())
3229 return emitError() <<
"member index out of bounds";
3232 return emitError() <<
"member type mismatch";
3234 return mlir::success();
3241LogicalResult cir::ExtractMemberOp::verify() {
3242 auto recordTy = mlir::cast<cir::RecordType>(getRecord().
getType());
3243 if (recordTy.getKind() == cir::RecordType::Union)
3245 <<
"cir.extract_member currently does not support unions";
3246 if (recordTy.getMembers().size() <=
getIndex())
3247 return emitError() <<
"member index out of bounds";
3249 return emitError() <<
"member type mismatch";
3250 return mlir::success();
3257LogicalResult cir::InsertMemberOp::verify() {
3258 auto recordTy = mlir::cast<cir::RecordType>(getRecord().
getType());
3259 if (recordTy.getKind() == cir::RecordType::Union)
3260 return emitError() <<
"cir.insert_member currently does not support unions";
3261 if (recordTy.getMembers().size() <=
getIndex())
3262 return emitError() <<
"member index out of bounds";
3264 return emitError() <<
"member type mismatch";
3266 return mlir::success();
3273OpFoldResult cir::VecCreateOp::fold(FoldAdaptor adaptor) {
3274 if (llvm::any_of(getElements(), [](mlir::Value value) {
3275 return !value.getDefiningOp<cir::ConstantOp>();
3279 return cir::ConstVectorAttr::get(
3280 getType(), mlir::ArrayAttr::get(getContext(), adaptor.getElements()));
3283LogicalResult cir::VecCreateOp::verify() {
3287 const cir::VectorType vecTy =
getType();
3288 if (getElements().size() != vecTy.getSize()) {
3289 return emitOpError() <<
"operand count of " << getElements().size()
3290 <<
" doesn't match vector type " << vecTy
3291 <<
" element count of " << vecTy.getSize();
3294 const mlir::Type elementType = vecTy.getElementType();
3295 for (
const mlir::Value element : getElements()) {
3296 if (element.getType() != elementType) {
3297 return emitOpError() <<
"operand type " << element.getType()
3298 <<
" doesn't match vector element type "
3310OpFoldResult cir::VecExtractOp::fold(FoldAdaptor adaptor) {
3311 const auto vectorAttr =
3312 llvm::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec());
3316 const auto indexAttr =
3317 llvm::dyn_cast_if_present<cir::IntAttr>(adaptor.getIndex());
3321 const mlir::ArrayAttr elements = vectorAttr.getElts();
3322 const uint64_t index = indexAttr.getUInt();
3323 if (index >= elements.size())
3326 return elements[index];
3333OpFoldResult cir::VecCmpOp::fold(FoldAdaptor adaptor) {
3335 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getLhs());
3337 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getRhs());
3338 if (!lhsVecAttr || !rhsVecAttr)
3341 mlir::Type inputElemTy =
3342 mlir::cast<cir::VectorType>(lhsVecAttr.getType()).getElementType();
3343 if (!isAnyIntegerOrFloatingPointType(inputElemTy))
3346 cir::CmpOpKind opKind = adaptor.getKind();
3347 mlir::ArrayAttr lhsVecElhs = lhsVecAttr.getElts();
3348 mlir::ArrayAttr rhsVecElhs = rhsVecAttr.getElts();
3349 uint64_t vecSize = lhsVecElhs.size();
3352 bool isIntAttr = vecSize && mlir::isa<cir::IntAttr>(lhsVecElhs[0]);
3353 for (uint64_t i = 0; i < vecSize; i++) {
3354 mlir::Attribute lhsAttr = lhsVecElhs[i];
3355 mlir::Attribute rhsAttr = rhsVecElhs[i];
3358 case cir::CmpOpKind::lt: {
3360 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <
3361 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3363 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <
3364 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3368 case cir::CmpOpKind::le: {
3370 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <=
3371 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3373 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <=
3374 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3378 case cir::CmpOpKind::gt: {
3380 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >
3381 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3383 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >
3384 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3388 case cir::CmpOpKind::ge: {
3390 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >=
3391 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3393 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >=
3394 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3398 case cir::CmpOpKind::eq: {
3400 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() ==
3401 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3403 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() ==
3404 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3408 case cir::CmpOpKind::ne: {
3410 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() !=
3411 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3413 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() !=
3414 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3418 case cir::CmpOpKind::one: {
3419 llvm::APFloat::cmpResult cr =
3420 mlir::cast<cir::FPAttr>(lhsAttr).getValue().compare(
3421 mlir::cast<cir::FPAttr>(rhsAttr).getValue());
3423 cr != llvm::APFloat::cmpUnordered && cr != llvm::APFloat::cmpEqual;
3426 case cir::CmpOpKind::uno: {
3427 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue().compare(
3428 mlir::cast<cir::FPAttr>(rhsAttr).getValue()) ==
3429 llvm::APFloat::cmpUnordered;
3434 elements[i] = cir::IntAttr::get(
getType().getElementType(), cmpResult);
3437 return cir::ConstVectorAttr::get(
3438 getType(), mlir::ArrayAttr::get(getContext(), elements));
3445OpFoldResult cir::VecShuffleOp::fold(FoldAdaptor adaptor) {
3447 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec1());
3449 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec2());
3450 if (!vec1Attr || !vec2Attr)
3453 mlir::Type vec1ElemTy =
3454 mlir::cast<cir::VectorType>(vec1Attr.getType()).getElementType();
3456 mlir::ArrayAttr vec1Elts = vec1Attr.getElts();
3457 mlir::ArrayAttr vec2Elts = vec2Attr.getElts();
3458 mlir::ArrayAttr indicesElts = adaptor.getIndices();
3461 elements.reserve(indicesElts.size());
3463 uint64_t vec1Size = vec1Elts.size();
3464 for (
const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
3465 if (idxAttr.getSInt() == -1) {
3466 elements.push_back(cir::UndefAttr::get(vec1ElemTy));
3470 uint64_t idxValue = idxAttr.getUInt();
3471 elements.push_back(idxValue < vec1Size ? vec1Elts[idxValue]
3472 : vec2Elts[idxValue - vec1Size]);
3475 return cir::ConstVectorAttr::get(
3476 getType(), mlir::ArrayAttr::get(getContext(), elements));
3479LogicalResult cir::VecShuffleOp::verify() {
3482 if (getIndices().size() != getResult().
getType().getSize()) {
3483 return emitOpError() <<
": the number of elements in " << getIndices()
3484 <<
" and " << getResult().getType() <<
" don't match";
3489 if (getVec1().
getType().getElementType() !=
3490 getResult().
getType().getElementType()) {
3491 return emitOpError() <<
": element types of " << getVec1().getType()
3492 <<
" and " << getResult().getType() <<
" don't match";
3495 const uint64_t maxValidIndex =
3496 getVec1().getType().getSize() + getVec2().getType().getSize() - 1;
3498 getIndices().getAsRange<cir::IntAttr>(), [&](cir::IntAttr idxAttr) {
3499 return idxAttr.getSInt() != -1 && idxAttr.getUInt() > maxValidIndex;
3501 return emitOpError() <<
": index for __builtin_shufflevector must be "
3502 "less than the total number of vector elements";
3511OpFoldResult cir::VecShuffleDynamicOp::fold(FoldAdaptor adaptor) {
3512 mlir::Attribute vec = adaptor.getVec();
3513 mlir::Attribute indices = adaptor.getIndices();
3514 if (mlir::isa_and_nonnull<cir::ConstVectorAttr>(vec) &&
3515 mlir::isa_and_nonnull<cir::ConstVectorAttr>(indices)) {
3516 auto vecAttr = mlir::cast<cir::ConstVectorAttr>(vec);
3517 auto indicesAttr = mlir::cast<cir::ConstVectorAttr>(indices);
3519 mlir::ArrayAttr vecElts = vecAttr.getElts();
3520 mlir::ArrayAttr indicesElts = indicesAttr.getElts();
3522 const uint64_t numElements = vecElts.size();
3525 elements.reserve(numElements);
3527 const uint64_t maskBits = llvm::NextPowerOf2(numElements - 1) - 1;
3528 for (
const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
3529 uint64_t idxValue = idxAttr.getUInt();
3530 uint64_t newIdx = idxValue & maskBits;
3531 elements.push_back(vecElts[newIdx]);
3534 return cir::ConstVectorAttr::get(
3535 getType(), mlir::ArrayAttr::get(getContext(), elements));
3541LogicalResult cir::VecShuffleDynamicOp::verify() {
3543 if (getVec().
getType().getSize() !=
3544 mlir::cast<cir::VectorType>(getIndices().
getType()).getSize()) {
3545 return emitOpError() <<
": the number of elements in " << getVec().getType()
3546 <<
" and " << getIndices().getType() <<
" don't match";
3555LogicalResult cir::VecTernaryOp::verify() {
3560 if (getCond().
getType().getSize() != getLhs().
getType().getSize()) {
3561 return emitOpError() <<
": the number of elements in "
3562 << getCond().getType() <<
" and " << getLhs().getType()
3568OpFoldResult cir::VecTernaryOp::fold(FoldAdaptor adaptor) {
3569 mlir::Attribute cond = adaptor.getCond();
3570 mlir::Attribute lhs = adaptor.getLhs();
3571 mlir::Attribute rhs = adaptor.getRhs();
3573 if (!mlir::isa_and_nonnull<cir::ConstVectorAttr>(cond) ||
3574 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(lhs) ||
3575 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(rhs))
3577 auto condVec = mlir::cast<cir::ConstVectorAttr>(cond);
3578 auto lhsVec = mlir::cast<cir::ConstVectorAttr>(lhs);
3579 auto rhsVec = mlir::cast<cir::ConstVectorAttr>(rhs);
3581 mlir::ArrayAttr condElts = condVec.getElts();
3584 elements.reserve(condElts.size());
3586 for (
const auto &[idx, condAttr] :
3587 llvm::enumerate(condElts.getAsRange<cir::IntAttr>())) {
3588 if (condAttr.getSInt()) {
3589 elements.push_back(lhsVec.getElts()[idx]);
3591 elements.push_back(rhsVec.getElts()[idx]);
3595 cir::VectorType vecTy = getLhs().getType();
3596 return cir::ConstVectorAttr::get(
3597 vecTy, mlir::ArrayAttr::get(getContext(), elements));
3604LogicalResult cir::ComplexCreateOp::verify() {
3607 <<
"operand type of cir.complex.create does not match its result type";
3614OpFoldResult cir::ComplexCreateOp::fold(FoldAdaptor adaptor) {
3615 mlir::Attribute real = adaptor.getReal();
3616 mlir::Attribute imag = adaptor.getImag();
3622 auto realAttr = mlir::cast<mlir::TypedAttr>(real);
3623 auto imagAttr = mlir::cast<mlir::TypedAttr>(imag);
3624 return cir::ConstComplexAttr::get(realAttr, imagAttr);
3631LogicalResult cir::ComplexRealOp::verify() {
3632 mlir::Type operandTy = getOperand().getType();
3633 if (
auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
3634 operandTy = complexOperandTy.getElementType();
3637 emitOpError() <<
": result type does not match operand type";
3644OpFoldResult cir::ComplexRealOp::fold(FoldAdaptor adaptor) {
3645 if (!mlir::isa<cir::ComplexType>(getOperand().
getType()))
3648 if (
auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
3649 return complexCreateOp.getOperand(0);
3652 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
3653 return complex ? complex.getReal() :
nullptr;
3660LogicalResult cir::ComplexImagOp::verify() {
3661 mlir::Type operandTy = getOperand().getType();
3662 if (
auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
3663 operandTy = complexOperandTy.getElementType();
3666 emitOpError() <<
": result type does not match operand type";
3673OpFoldResult cir::ComplexImagOp::fold(FoldAdaptor adaptor) {
3674 if (!mlir::isa<cir::ComplexType>(getOperand().
getType()))
3677 if (
auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
3678 return complexCreateOp.getOperand(1);
3681 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
3682 return complex ? complex.getImag() :
nullptr;
3689LogicalResult cir::ComplexRealPtrOp::verify() {
3690 mlir::Type resultPointeeTy =
getType().getPointee();
3691 cir::PointerType operandPtrTy = getOperand().getType();
3692 auto operandPointeeTy =
3693 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
3695 if (resultPointeeTy != operandPointeeTy.getElementType()) {
3696 return emitOpError() <<
": result type does not match operand type";
3706LogicalResult cir::ComplexImagPtrOp::verify() {
3707 mlir::Type resultPointeeTy =
getType().getPointee();
3708 cir::PointerType operandPtrTy = getOperand().getType();
3709 auto operandPointeeTy =
3710 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
3712 if (resultPointeeTy != operandPointeeTy.getElementType()) {
3713 return emitOpError()
3714 <<
"cir.complex.imag_ptr result type does not match operand type";
3725 llvm::function_ref<llvm::APInt(
const llvm::APInt &)> func,
3726 bool poisonZero =
false) {
3727 if (mlir::isa_and_present<cir::PoisonAttr>(inputAttr)) {
3732 auto input = mlir::dyn_cast_if_present<IntAttr>(inputAttr);
3736 llvm::APInt inputValue = input.getValue();
3737 if (poisonZero && inputValue.isZero())
3738 return cir::PoisonAttr::get(input.getType());
3740 llvm::APInt resultValue = func(inputValue);
3741 return IntAttr::get(input.getType(), resultValue);
3744OpFoldResult BitClrsbOp::fold(FoldAdaptor adaptor) {
3745 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3746 unsigned resultValue =
3747 inputValue.getBitWidth() - inputValue.getSignificantBits();
3748 return llvm::APInt(inputValue.getBitWidth(), resultValue);
3752OpFoldResult BitClzOp::fold(FoldAdaptor adaptor) {
3755 [](
const llvm::APInt &inputValue) {
3756 unsigned resultValue = inputValue.countLeadingZeros();
3757 return llvm::APInt(inputValue.getBitWidth(), resultValue);
3762OpFoldResult BitCtzOp::fold(FoldAdaptor adaptor) {
3765 [](
const llvm::APInt &inputValue) {
3766 return llvm::APInt(inputValue.getBitWidth(),
3767 inputValue.countTrailingZeros());
3772OpFoldResult BitFfsOp::fold(FoldAdaptor adaptor) {
3773 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3774 unsigned trailingZeros = inputValue.countTrailingZeros();
3776 trailingZeros == inputValue.getBitWidth() ? 0 : trailingZeros + 1;
3777 return llvm::APInt(inputValue.getBitWidth(), result);
3781OpFoldResult BitParityOp::fold(FoldAdaptor adaptor) {
3782 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3783 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount() % 2);
3787OpFoldResult BitPopcountOp::fold(FoldAdaptor adaptor) {
3788 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3789 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount());
3793OpFoldResult BitReverseOp::fold(FoldAdaptor adaptor) {
3794 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3795 return inputValue.reverseBits();
3799OpFoldResult ByteSwapOp::fold(FoldAdaptor adaptor) {
3800 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3801 return inputValue.byteSwap();
3805OpFoldResult RotateOp::fold(FoldAdaptor adaptor) {
3806 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()) ||
3807 mlir::isa_and_present<cir::PoisonAttr>(adaptor.getAmount())) {
3809 return cir::PoisonAttr::get(
getType());
3812 auto input = mlir::dyn_cast_if_present<IntAttr>(adaptor.getInput());
3813 auto amount = mlir::dyn_cast_if_present<IntAttr>(adaptor.getAmount());
3814 if (!input && !amount)
3823 llvm::APInt inputValue;
3825 inputValue = input.getValue();
3826 if (inputValue.isZero() || inputValue.isAllOnes()) {
3832 uint64_t amountValue;
3834 amountValue = amount.getValue().urem(getInput().
getType().getWidth());
3835 if (amountValue == 0) {
3841 if (!input || !amount)
3844 assert(inputValue.getBitWidth() == getInput().
getType().getWidth() &&
3845 "input value must have the same bit width as the input type");
3847 llvm::APInt resultValue;
3849 resultValue = inputValue.rotl(amountValue);
3851 resultValue = inputValue.rotr(amountValue);
3853 return IntAttr::get(input.getContext(), input.getType(), resultValue);
3860void cir::InlineAsmOp::print(OpAsmPrinter &p) {
3861 p <<
'(' << getAsmFlavor() <<
", ";
3866 auto *nameIt = names.begin();
3867 auto *attrIt = getOperandAttrs().begin();
3869 for (mlir::OperandRange ops : getAsmOperands()) {
3870 p << *nameIt <<
" = ";
3873 llvm::interleaveComma(llvm::make_range(ops.begin(), ops.end()), p,
3875 p.printOperand(value);
3876 p <<
" : " << value.getType();
3877 if (mlir::isa<mlir::UnitAttr>(*attrIt))
3878 p <<
" (maybe_memory)";
3887 p.printString(getAsmString());
3889 p.printString(getConstraints());
3893 if (getSideEffects())
3894 p <<
" side_effects";
3896 std::array elidedAttrs{
3897 llvm::StringRef(
"asm_flavor"), llvm::StringRef(
"asm_string"),
3898 llvm::StringRef(
"constraints"), llvm::StringRef(
"operand_attrs"),
3899 llvm::StringRef(
"operands_segments"), llvm::StringRef(
"side_effects")};
3900 p.printOptionalAttrDict(getOperation()->getAttrs(), elidedAttrs);
3902 if (
auto v = getRes())
3903 p <<
" -> " << v.getType();
3906void cir::InlineAsmOp::build(OpBuilder &odsBuilder, OperationState &odsState,
3908 StringRef asmString, StringRef constraints,
3909 bool sideEffects, cir::AsmFlavor asmFlavor,
3913 for (
auto operandRange : asmOperands) {
3914 segments.push_back(operandRange.size());
3915 odsState.addOperands(operandRange);
3918 odsState.addAttribute(
3919 "operands_segments",
3920 DenseI32ArrayAttr::get(odsBuilder.getContext(), segments));
3921 odsState.addAttribute(
"asm_string", odsBuilder.getStringAttr(asmString));
3922 odsState.addAttribute(
"constraints", odsBuilder.getStringAttr(constraints));
3923 odsState.addAttribute(
"asm_flavor",
3924 AsmFlavorAttr::get(odsBuilder.getContext(), asmFlavor));
3927 odsState.addAttribute(
"side_effects", odsBuilder.getUnitAttr());
3929 odsState.addAttribute(
"operand_attrs", odsBuilder.getArrayAttr(operandAttrs));
3932ParseResult cir::InlineAsmOp::parse(OpAsmParser &parser,
3933 OperationState &result) {
3936 std::string asmString, constraints;
3938 MLIRContext *ctxt = parser.getBuilder().getContext();
3940 auto error = [&](
const Twine &msg) -> LogicalResult {
3941 return parser.emitError(parser.getCurrentLocation(), msg);
3944 auto expected = [&](
const std::string &
c) {
3945 return error(
"expected '" +
c +
"'");
3948 if (parser.parseLParen().failed())
3949 return expected(
"(");
3951 auto flavor = FieldParser<AsmFlavor, AsmFlavor>::parse(parser);
3953 return error(
"Unknown AsmFlavor");
3955 if (parser.parseComma().failed())
3956 return expected(
",");
3958 auto parseValue = [&](
Value &v) {
3959 OpAsmParser::UnresolvedOperand op;
3961 if (parser.parseOperand(op) || parser.parseColon())
3962 return error(
"can't parse operand");
3965 if (parser.parseType(typ).failed())
3966 return error(
"can't parse operand type");
3968 if (parser.resolveOperand(op, typ, tmp))
3969 return error(
"can't resolve operand");
3971 return mlir::success();
3974 auto parseOperands = [&](llvm::StringRef
name) {
3975 if (parser.parseKeyword(name).failed())
3976 return error(
"expected " + name +
" operands here");
3977 if (parser.parseEqual().failed())
3978 return expected(
"=");
3979 if (parser.parseLSquare().failed())
3980 return expected(
"[");
3983 if (parser.parseOptionalRSquare().succeeded()) {
3984 operandsGroupSizes.push_back(size);
3985 if (parser.parseComma())
3986 return expected(
",");
3987 return mlir::success();
3990 auto parseOperand = [&]() {
3992 if (parseValue(val).succeeded()) {
3993 result.operands.push_back(val);
3996 if (parser.parseOptionalLParen().failed()) {
3997 operandAttrs.push_back(mlir::DictionaryAttr::get(ctxt));
3998 return mlir::success();
4001 if (parser.parseKeyword(
"maybe_memory").succeeded()) {
4002 operandAttrs.push_back(mlir::UnitAttr::get(ctxt));
4003 if (parser.parseRParen())
4004 return expected(
")");
4005 return mlir::success();
4007 return expected(
"maybe_memory");
4010 return mlir::failure();
4013 if (parser.parseCommaSeparatedList(parseOperand).failed())
4014 return mlir::failure();
4016 if (parser.parseRSquare().failed() || parser.parseComma().failed())
4017 return expected(
"]");
4018 operandsGroupSizes.push_back(size);
4019 return mlir::success();
4022 if (parseOperands(
"out").failed() || parseOperands(
"in").failed() ||
4023 parseOperands(
"in_out").failed())
4024 return error(
"failed to parse operands");
4026 if (parser.parseLBrace())
4027 return expected(
"{");
4028 if (parser.parseString(&asmString))
4029 return error(
"asm string parsing failed");
4030 if (parser.parseString(&constraints))
4031 return error(
"constraints string parsing failed");
4032 if (parser.parseRBrace())
4033 return expected(
"}");
4034 if (parser.parseRParen())
4035 return expected(
")");
4037 if (parser.parseOptionalKeyword(
"side_effects").succeeded())
4038 result.attributes.set(
"side_effects", UnitAttr::get(ctxt));
4040 if (parser.parseOptionalAttrDict(result.attributes).failed())
4041 return mlir::failure();
4043 if (parser.parseOptionalArrow().succeeded() &&
4044 parser.parseType(resType).failed())
4045 return mlir::failure();
4047 result.attributes.set(
"asm_flavor", AsmFlavorAttr::get(ctxt, *flavor));
4048 result.attributes.set(
"asm_string", StringAttr::get(ctxt, asmString));
4049 result.attributes.set(
"constraints", StringAttr::get(ctxt, constraints));
4050 result.attributes.set(
"operand_attrs", ArrayAttr::get(ctxt, operandAttrs));
4051 result.getOrAddProperties<InlineAsmOp::Properties>().operands_segments =
4052 parser.getBuilder().getDenseI32ArrayAttr(operandsGroupSizes);
4054 result.addTypes(TypeRange{resType});
4056 return mlir::success();
4063mlir::LogicalResult cir::ThrowOp::verify() {
4068 if (getNumOperands() != 0) {
4071 return emitOpError() <<
"'type_info' symbol attribute missing";
4081LogicalResult cir::AtomicFetchOp::verify() {
4082 if (getBinop() != cir::AtomicFetchKind::Add &&
4083 getBinop() != cir::AtomicFetchKind::Sub &&
4084 getBinop() != cir::AtomicFetchKind::Max &&
4085 getBinop() != cir::AtomicFetchKind::Min &&
4086 !mlir::isa<cir::IntType>(getVal().
getType()))
4087 return emitError(
"only atomic add, sub, max, and min operation could "
4088 "operate on floating-point values");
4096LogicalResult cir::TypeInfoAttr::verify(
4097 ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError,
4098 ::mlir::Type type, ::mlir::ArrayAttr typeInfoData) {
4100 if (cir::ConstRecordAttr::verify(emitError, type, typeInfoData).failed())
4110void cir::TryOp::getSuccessorRegions(
4111 mlir::RegionBranchPoint point,
4114 if (!point.isParent()) {
4115 regions.push_back(RegionSuccessor::parent());
4119 regions.push_back(mlir::RegionSuccessor(&getTryRegion()));
4123 for (mlir::Region &handlerRegion : this->getHandlerRegions())
4124 regions.push_back(mlir::RegionSuccessor(&handlerRegion));
4127mlir::ValueRange cir::TryOp::getSuccessorInputs(RegionSuccessor successor) {
4128 return successor.isParent() ? ValueRange(getOperation()->getResults())
4132LogicalResult cir::TryOp::verify() {
4133 mlir::ArrayAttr handlerTypes = getHandlerTypes();
4134 if (!handlerTypes) {
4135 if (!getHandlerRegions().empty())
4137 "handler regions must be empty when no handler types are present");
4141 mlir::MutableArrayRef<mlir::Region> handlerRegions = getHandlerRegions();
4145 if (handlerRegions.size() != handlerTypes.size())
4147 "number of handler regions and handler types must match");
4149 for (
const auto &[typeAttr, handlerRegion] :
4150 llvm::zip(handlerTypes, handlerRegions)) {
4152 mlir::Block &entryBlock = handlerRegion.front();
4153 if (entryBlock.getNumArguments() != 1 ||
4154 !mlir::isa<cir::EhTokenType>(entryBlock.getArgument(0).getType()))
4156 "handler region must have a single '!cir.eh_token' argument");
4159 if (mlir::isa<cir::UnwindAttr>(typeAttr))
4165 if (entryBlock.empty())
4166 return emitOpError(
"catch handler region must not be empty");
4167 mlir::Operation *firstOp = &entryBlock.front();
4168 if (mlir::isa_and_present<cir::ConstructCatchParamOp>(firstOp))
4169 firstOp = firstOp->getNextNode();
4170 if (!firstOp || !mlir::isa<cir::BeginCatchOp>(firstOp))
4172 "catch handler region must start with 'cir.begin_catch'");
4180 mlir::MutableArrayRef<mlir::Region> handlerRegions,
4181 mlir::ArrayAttr handlerTypes) {
4185 for (
const auto [typeIdx, typeAttr] : llvm::enumerate(handlerTypes)) {
4189 if (mlir::isa<cir::CatchAllAttr>(typeAttr)) {
4190 printer <<
"catch all ";
4191 }
else if (mlir::isa<cir::UnwindAttr>(typeAttr)) {
4192 printer <<
"unwind ";
4194 printer <<
"catch [type ";
4195 printer.printAttribute(typeAttr);
4200 mlir::Region ®ion = handlerRegions[typeIdx];
4201 if (!region.empty() && region.front().getNumArguments() > 0) {
4203 printer.printRegionArgument(region.front().getArgument(0));
4207 printer.printRegion(region,
4214 mlir::OpAsmParser &parser,
4216 mlir::ArrayAttr &handlerTypes) {
4218 auto parseCheckedCatcherRegion = [&]() -> mlir::ParseResult {
4219 handlerRegions.emplace_back(
new mlir::Region);
4221 mlir::Region &currRegion = *handlerRegions.back();
4225 if (parser.parseLParen())
4227 mlir::OpAsmParser::Argument arg;
4228 if (parser.parseArgument(arg,
true))
4230 regionArgs.push_back(arg);
4231 if (parser.parseRParen())
4234 mlir::SMLoc regionLoc = parser.getCurrentLocation();
4235 if (parser.parseRegion(currRegion, regionArgs)) {
4236 handlerRegions.clear();
4240 if (currRegion.empty())
4241 return parser.emitError(regionLoc,
"handler region shall not be empty");
4243 if (!(currRegion.back().mightHaveTerminator() &&
4244 currRegion.back().getTerminator()))
4245 return parser.emitError(
4246 regionLoc,
"blocks are expected to be explicitly terminated");
4251 bool hasCatchAll =
false;
4253 while (parser.parseOptionalKeyword(
"catch").succeeded()) {
4254 bool hasLSquare = parser.parseOptionalLSquare().succeeded();
4256 llvm::StringRef attrStr;
4257 if (parser.parseOptionalKeyword(&attrStr, {
"all",
"type"}).failed())
4258 return parser.emitError(parser.getCurrentLocation(),
4259 "expected 'all' or 'type' keyword");
4261 bool isCatchAll = attrStr ==
"all";
4264 return parser.emitError(parser.getCurrentLocation(),
4265 "can't have more than one catch all");
4269 mlir::Attribute exceptionRTTIAttr;
4270 if (!isCatchAll && parser.parseAttribute(exceptionRTTIAttr).failed())
4271 return parser.emitError(parser.getCurrentLocation(),
4272 "expected valid RTTI info attribute");
4274 catcherAttrs.push_back(isCatchAll
4275 ? cir::CatchAllAttr::get(parser.getContext())
4276 : exceptionRTTIAttr);
4278 if (hasLSquare && isCatchAll)
4279 return parser.emitError(parser.getCurrentLocation(),
4280 "catch all dosen't need RTTI info attribute");
4282 if (hasLSquare && parser.parseRSquare().failed())
4283 return parser.emitError(parser.getCurrentLocation(),
4284 "expected `]` after RTTI info attribute");
4286 if (parseCheckedCatcherRegion().failed())
4287 return mlir::failure();
4290 if (parser.parseOptionalKeyword(
"unwind").succeeded()) {
4292 return parser.emitError(parser.getCurrentLocation(),
4293 "unwind can't be used with catch all");
4295 catcherAttrs.push_back(cir::UnwindAttr::get(parser.getContext()));
4296 if (parseCheckedCatcherRegion().failed())
4297 return mlir::failure();
4300 handlerTypes = parser.getBuilder().getArrayAttr(catcherAttrs);
4301 return mlir::success();
4309cir::EhTypeIdOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
4310 Operation *op = symbolTable.lookupNearestSymbolFrom(*
this, getTypeSymAttr());
4311 if (!isa_and_nonnull<GlobalOp>(op))
4312 return emitOpError(
"'")
4313 << getTypeSym() <<
"' does not reference a valid cir.global";
4321LogicalResult cir::ConstructCatchParamOp::verifySymbolUses(
4322 SymbolTableCollection &symbolTable) {
4324 symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(*
this, getCopyFnAttr());
4326 return emitOpError(
"'")
4327 << getCopyFn() <<
"' does not reference a valid cir.func";
4329 if (!fn->hasAttr(cir::CIRDialect::getCatchCopyThunkAttrName()))
4330 return emitOpError(
"catch-init copy_fn must be tagged with the ")
4331 << cir::CIRDialect::getCatchCopyThunkAttrName() <<
" attribute";
4333 cir::FuncType fnType = fn.getFunctionType();
4334 if (fnType.getNumInputs() != 2 || !fnType.hasVoidReturn())
4335 return emitOpError(
"catch-init copy_fn must take two pointer arguments and "
4338 if (fnType.getInput(0) != getParamAddr().
getType())
4339 return emitOpError(
"first argument of catch-init copy_fn must match the "
4340 "type of 'param_addr'");
4342 if (fnType.getInput(1) != getParamAddr().
getType())
4344 "second argument of catch-init copy_fn must be a pointer "
4345 "to the catch type");
4356 SmallVectorImpl<Block *> &catchDestinations,
4357 Block *&defaultDestination,
4358 mlir::UnitAttr &defaultIsCatchAll) {
4360 if (parser.parseLSquare())
4364 bool hasCatchAll =
false;
4365 bool hasUnwind =
false;
4368 auto parseHandler = [&]() -> ParseResult {
4370 if (succeeded(parser.parseOptionalKeyword(
"catch_all"))) {
4372 return parser.emitError(parser.getCurrentLocation(),
4373 "duplicate 'catch_all' handler");
4375 return parser.emitError(parser.getCurrentLocation(),
4376 "cannot have both 'catch_all' and 'unwind'");
4379 if (parser.parseColon().failed())
4382 if (parser.parseSuccessor(defaultDestination).failed())
4388 if (succeeded(parser.parseOptionalKeyword(
"unwind"))) {
4390 return parser.emitError(parser.getCurrentLocation(),
4391 "duplicate 'unwind' handler");
4393 return parser.emitError(parser.getCurrentLocation(),
4394 "cannot have both 'catch_all' and 'unwind'");
4397 if (parser.parseColon().failed())
4400 if (parser.parseSuccessor(defaultDestination).failed())
4408 if (parser.parseKeyword(
"catch").failed())
4411 if (parser.parseLParen().failed())
4414 mlir::Attribute catchTypeAttr;
4415 if (parser.parseAttribute(catchTypeAttr).failed())
4417 handlerTypes.push_back(catchTypeAttr);
4419 if (parser.parseRParen().failed())
4422 if (parser.parseColon().failed())
4426 if (parser.parseSuccessor(dest).failed())
4428 catchDestinations.push_back(dest);
4432 if (parser.parseCommaSeparatedList(parseHandler).failed())
4435 if (parser.parseRSquare().failed())
4439 if (!hasCatchAll && !hasUnwind)
4440 return parser.emitError(parser.getCurrentLocation(),
4441 "must have either 'catch_all' or 'unwind' handler");
4444 if (!handlerTypes.empty())
4445 catchTypes = parser.getBuilder().getArrayAttr(handlerTypes);
4448 defaultIsCatchAll = parser.getBuilder().getUnitAttr();
4454 mlir::ArrayAttr catchTypes,
4455 SuccessorRange catchDestinations,
4456 Block *defaultDestination,
4457 mlir::UnitAttr defaultIsCatchAll) {
4465 llvm::zip(catchTypes, catchDestinations),
4468 p.printAttribute(std::get<0>(i));
4470 p.printSuccessor(std::get<1>(i));
4482 if (defaultIsCatchAll)
4483 p <<
" catch_all : ";
4486 p.printSuccessor(defaultDestination);
4496#define GET_OP_CLASSES
4497#include "clang/CIR/Dialect/IR/CIROps.cpp.inc"
static const MemRegion * getRegion(const CallEvent &Call, const MutexDescriptor &Descriptor, bool IsLock)
static void printEhDispatchDestinations(OpAsmPrinter &p, cir::EhDispatchOp op, mlir::ArrayAttr catchTypes, SuccessorRange catchDestinations, Block *defaultDestination, mlir::UnitAttr defaultIsCatchAll)
static mlir::LogicalResult checkReturnAndFunction(cir::ReturnOp op, cir::FuncOp function)
static bool isCirFunctionPointerType(mlir::Type ty)
static LogicalResult verifyMemberPtrCast(Operation *op, mlir::Value src, mlir::Type resultTy)
static mlir::ParseResult parseCallCommon(mlir::OpAsmParser &parser, mlir::OperationState &result, bool hasDestinationBlocks=false)
static bool isIntOrBoolCast(cir::CastOp op)
static ParseResult parseEhDispatchDestinations(OpAsmParser &parser, mlir::ArrayAttr &catchTypes, SmallVectorImpl< Block * > &catchDestinations, Block *&defaultDestination, mlir::UnitAttr &defaultIsCatchAll)
static void printConstant(OpAsmPrinter &p, Attribute value)
static mlir::ParseResult parseOmittedTerminatorRegion(mlir::OpAsmParser &parser, mlir::Region ®ion)
ParseResult parseInlineKindAttr(OpAsmParser &parser, cir::InlineKindAttr &inlineKindAttr)
void printInlineKindAttr(OpAsmPrinter &p, cir::InlineKindAttr inlineKindAttr)
static ParseResult parseSwitchFlatOpCases(OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues, SmallVectorImpl< Block * > &caseDestinations, SmallVectorImpl< llvm::SmallVector< OpAsmParser::UnresolvedOperand > > &caseOperands, SmallVectorImpl< llvm::SmallVector< Type > > &caseOperandTypes)
<cases> ::= [ (case (, case )* )?
void printGlobalAddressSpaceValue(mlir::AsmPrinter &printer, cir::GlobalOp op, mlir::ptr::MemorySpaceAttrInterface attr)
static void printCallCommon(mlir::Operation *op, mlir::FlatSymbolRefAttr calleeSym, mlir::Value indirectCallee, mlir::OpAsmPrinter &printer, bool isNothrow, cir::SideEffect sideEffect, ArrayAttr argAttrs, ArrayAttr resAttrs, mlir::Block *normalDest=nullptr, mlir::Block *unwindDest=nullptr)
static LogicalResult verifyCallCommInSymbolUses(mlir::Operation *op, SymbolTableCollection &symbolTable)
static LogicalResult ensureRegionTerm(OpAsmParser &parser, Region ®ion, SMLoc errLoc)
static ParseResult parseGlobalOpTypeAndInitialValue(OpAsmParser &parser, TypeAttr &typeAttr, Attribute &initialValueAttr, mlir::Region &ctorRegion, mlir::Region &dtorRegion)
void printIndirectBrOpSucessors(OpAsmPrinter &p, cir::IndirectBrOp op, Type flagType, SuccessorRange succs, OperandRangeRange succOperands, const TypeRangeRange &succOperandsTypes)
static OpFoldResult foldUnaryBitOp(mlir::Attribute inputAttr, llvm::function_ref< llvm::APInt(const llvm::APInt &)> func, bool poisonZero=false)
static llvm::StringRef getLinkageAttrNameString()
Returns the name used for the linkage attribute.
static RetTy parseOptionalCIRKeyword(AsmParser &parser, EnumTy defaultValue)
Parse an enum from the keyword, or default to the provided default value.
mlir::OptionalParseResult parseGlobalAddressSpaceValue(mlir::AsmParser &p, mlir::ptr::MemorySpaceAttrInterface &attr)
static void printSwitchFlatOpCases(OpAsmPrinter &p, cir::SwitchFlatOp op, Type flagType, mlir::ArrayAttr caseValues, SuccessorRange caseDestinations, OperandRangeRange caseOperands, const TypeRangeRange &caseOperandTypes)
static mlir::ParseResult parseTryCallDestinations(mlir::OpAsmParser &parser, mlir::OperationState &result)
static void printGlobalOpTypeAndInitialValue(OpAsmPrinter &p, cir::GlobalOp op, TypeAttr type, Attribute initAttr, mlir::Region &ctorRegion, mlir::Region &dtorRegion)
static ParseResult parseCIRKeyword(AsmParser &parser, RetTy &result)
Parse an enum from the keyword, return failure if the keyword is not found.
static Value tryFoldCastChain(cir::CastOp op)
static void printTryHandlerRegions(mlir::OpAsmPrinter &printer, cir::TryOp op, mlir::MutableArrayRef< mlir::Region > handlerRegions, mlir::ArrayAttr handlerTypes)
ParseResult parseIndirectBrOpSucessors(OpAsmParser &parser, Type &flagType, SmallVectorImpl< Block * > &succOperandBlocks, SmallVectorImpl< SmallVector< OpAsmParser::UnresolvedOperand > > &succOperands, SmallVectorImpl< SmallVector< Type > > &succOperandsTypes)
static bool omitRegionTerm(mlir::Region &r)
static LogicalResult verifyBinaryOverflowOp(mlir::Operation *op, bool noSignedWrap, bool noUnsignedWrap, bool saturated, bool hasSat)
static void printOmittedTerminatorRegion(mlir::OpAsmPrinter &printer, cir::ScopeOp &op, mlir::Region ®ion)
static ParseResult parseConstantValue(OpAsmParser &parser, mlir::Attribute &valueAttr)
static LogicalResult verifyArrayCtorDtor(Op op)
static LogicalResult checkConstantTypes(mlir::Operation *op, mlir::Type opType, mlir::Attribute attrType)
static mlir::ParseResult parseTryHandlerRegions(mlir::OpAsmParser &parser, llvm::SmallVectorImpl< std::unique_ptr< mlir::Region > > &handlerRegions, mlir::ArrayAttr &handlerTypes)
#define REGISTER_ENUM_TYPE(Ty)
static int parseOptionalKeywordAlternative(AsmParser &parser, ArrayRef< llvm::StringRef > keywords)
llvm::function_ref< void(mlir::OpBuilder &, mlir::Location)> BuilderCallbackRef
llvm::function_ref< void( mlir::OpBuilder &, mlir::Location, mlir::OperationState &)> BuilderOpStateCallbackRef
static std::optional< NonLoc > getIndex(ProgramStateRef State, const ElementRegion *ER, CharKind CK)
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 an optional score condition
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
__device__ __2f16 float c
void buildTerminatedBody(mlir::OpBuilder &builder, mlir::Location loc)
mlir::ptr::MemorySpaceAttrInterface normalizeDefaultAddressSpace(mlir::ptr::MemorySpaceAttrInterface addrSpace)
Normalize LangAddressSpace::Default to null (empty attribute).
const internal::VariadicAllOfMatcher< Attr > attr
const AstTypeMatcher< RecordType > recordType
StringRef getName(const HeaderType T)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
static bool memberFuncPtrCast()
static bool opCallCallConv()
static bool opScopeCleanupRegion()
static bool supportIFuncAttr()