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");
380 cir::AssumeBundleKindAttr kindAttr,
381 OperandRange bundleArgs,
382 TypeRange bundleArgTypes) {
383 cir::AssumeBundleKind
kind = kindAttr.getValue();
384 if (
kind == cir::AssumeBundleKind::None)
387 p <<
" " << cir::stringifyAssumeBundleKind(
kind);
388 if (bundleArgs.empty())
392 p.printOperands(bundleArgs);
394 llvm::interleaveComma(bundleArgTypes, p);
399 OpAsmParser &p, cir::AssumeBundleKindAttr &bundleKindAttr,
403 auto loc = p.getCurrentLocation();
404 if (failed(p.parseOptionalKeyword(&keyword))) {
405 bundleKindAttr = cir::AssumeBundleKindAttr::get(
406 p.getContext(), cir::AssumeBundleKind::None);
410 std::optional<cir::AssumeBundleKind> parsedKind =
411 cir::symbolizeAssumeBundleKind(keyword);
413 return p.emitError(loc,
"unknown assume bundle kind '") << keyword <<
"'";
415 bundleKindAttr = cir::AssumeBundleKindAttr::get(p.getContext(), *parsedKind);
417 if (p.parseOptionalLParen())
420 if (p.parseOperandList(bundleArgs) || p.parseColon() ||
421 p.parseTypeList(bundleArgTypes) || p.parseRParen())
427LogicalResult cir::AssumeOp::verify() {
428 cir::AssumeBundleKind
kind = getBundleKind();
429 size_t numArgs = getBundleArgs().size();
431 if (
kind == cir::AssumeBundleKind::None) {
433 return emitOpError(
"unexpected bundle operands for kind 'none'");
438 return emitOpError(
"expected bundle operands for kind '")
439 << cir::stringifyAssumeBundleKind(
kind) <<
"'";
442 case cir::AssumeBundleKind::Align:
443 if (numArgs != 2 && numArgs != 3)
444 return emitOpError(
"align bundle expects 2 or 3 operands");
446 case cir::AssumeBundleKind::SeparateStorage:
448 return emitOpError(
"separate_storage bundle expects 2 operands");
450 case cir::AssumeBundleKind::Dereferenceable:
452 return emitOpError(
"dereferenceable bundle expects 2 operands");
465cir::LocalInitOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
466 cir::GlobalOp global = getReferencedGlobal(symbolTable);
468 return emitOpError(
"'")
469 << getGlobalName() <<
"' does not reference a valid cir.global";
471 if (getTls() && !global.getTlsModel())
472 return emitOpError(
"access to global not marked thread local");
474 if (!global.getStaticLocalGuard().has_value())
475 return emitOpError(
"static_local attribute mismatch");
488void cir::ConditionOp::getSuccessorRegions(
494 if (
auto loopOp = dyn_cast<LoopOpInterface>(getOperation()->getParentOp())) {
495 regions.emplace_back(&loopOp.getBody());
496 regions.push_back(RegionSuccessor::parent());
501 auto await = cast<AwaitOp>(getOperation()->getParentOp());
502 regions.emplace_back(&await.getResume());
503 regions.emplace_back(&await.getSuspend());
507cir::ConditionOp::getMutableSuccessorOperands(RegionSuccessor point) {
509 return MutableOperandRange(getOperation(), 0, 0);
513cir::ResumeOp::getMutableSuccessorOperands(RegionSuccessor point) {
515 return MutableOperandRange(getOperation(), 0, 0);
518LogicalResult cir::ConditionOp::verify() {
519 if (!isa<LoopOpInterface, AwaitOp>(getOperation()->getParentOp()))
520 return emitOpError(
"condition must be within a conditional region");
529 mlir::Attribute attrType) {
530 if (isa<cir::ConstPtrAttr>(attrType)) {
531 if (!mlir::isa<cir::PointerType>(opType))
532 return op->emitOpError(
533 "pointer constant initializing a non-pointer type");
537 if (isa<cir::DataMemberAttr, cir::MethodAttr>(attrType)) {
543 if (isa<cir::ZeroAttr>(attrType)) {
544 if (isa<cir::RecordType, cir::ArrayType, cir::VectorType, cir::ComplexType>(
547 return op->emitOpError(
548 "zero expects struct, array, vector, or complex type");
551 if (mlir::isa<cir::UndefAttr>(attrType)) {
552 if (!mlir::isa<cir::VoidType>(opType))
554 return op->emitOpError(
"undef expects non-void type");
557 if (mlir::isa<cir::BoolAttr>(attrType)) {
558 if (!mlir::isa<cir::BoolType>(opType))
559 return op->emitOpError(
"result type (")
560 << opType <<
") must be '!cir.bool' for '" << attrType <<
"'";
564 if (mlir::isa<cir::IntAttr, cir::FPAttr>(attrType)) {
565 auto at = cast<TypedAttr>(attrType);
566 if (at.getType() != opType) {
567 return op->emitOpError(
"result type (")
568 << opType <<
") does not match value type (" << at.getType()
574 if (mlir::isa<cir::ConstArrayAttr, cir::ConstVectorAttr,
575 cir::ConstComplexAttr, cir::ConstRecordAttr,
576 cir::GlobalViewAttr, cir::PoisonAttr, cir::TypeInfoAttr,
577 cir::VTableAttr>(attrType))
580 assert(isa<TypedAttr>(attrType) &&
"What else could we be looking at here?");
581 return op->emitOpError(
"global with type ")
582 << cast<TypedAttr>(attrType).getType() <<
" not yet supported";
585LogicalResult cir::ConstantOp::verify() {
592OpFoldResult cir::ConstantOp::fold(FoldAdaptor ) {
600LogicalResult cir::CastOp::verify() {
601 mlir::Type resType =
getType();
602 mlir::Type srcType = getSrc().getType();
606 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
607 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
608 if (srcPtrTy && resPtrTy && (
getKind() != cir::CastKind::address_space))
609 if (srcPtrTy.getAddrSpace() != resPtrTy.getAddrSpace()) {
610 return emitOpError() <<
"result type address space does not match the "
611 "address space of the operand";
614 if (mlir::isa<cir::VectorType>(srcType) &&
615 mlir::isa<cir::VectorType>(resType)) {
618 srcType = mlir::dyn_cast<cir::VectorType>(srcType).getElementType();
619 resType = mlir::dyn_cast<cir::VectorType>(resType).getElementType();
623 case cir::CastKind::int_to_bool: {
624 if (!mlir::isa<cir::BoolType>(resType))
625 return emitOpError() <<
"requires !cir.bool type for result";
626 if (!mlir::isa<cir::IntType>(srcType))
627 return emitOpError() <<
"requires !cir.int type for source";
630 case cir::CastKind::ptr_to_bool: {
631 if (!mlir::isa<cir::BoolType>(resType))
632 return emitOpError() <<
"requires !cir.bool type for result";
633 if (!mlir::isa<cir::PointerType>(srcType))
634 return emitOpError() <<
"requires !cir.ptr type for source";
637 case cir::CastKind::integral: {
638 if (!mlir::isa<cir::IntType>(resType))
639 return emitOpError() <<
"requires !cir.int type for result";
640 if (!mlir::isa<cir::IntType>(srcType))
641 return emitOpError() <<
"requires !cir.int type for source";
644 case cir::CastKind::array_to_ptrdecay: {
645 const auto arrayPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
646 const auto flatPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
647 if (!arrayPtrTy || !flatPtrTy)
648 return emitOpError() <<
"requires !cir.ptr type for source and result";
653 case cir::CastKind::bitcast: {
655 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
656 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
658 if (srcPtrTy && resPtrTy) {
664 case cir::CastKind::floating: {
665 if (!mlir::isa<cir::FPTypeInterface>(srcType) ||
666 !mlir::isa<cir::FPTypeInterface>(resType))
667 return emitOpError() <<
"requires !cir.float type for source and result";
670 case cir::CastKind::float_to_int: {
671 if (!mlir::isa<cir::FPTypeInterface>(srcType))
672 return emitOpError() <<
"requires !cir.float type for source";
673 if (!mlir::dyn_cast<cir::IntType>(resType))
674 return emitOpError() <<
"requires !cir.int type for result";
677 case cir::CastKind::int_to_ptr: {
678 if (!mlir::dyn_cast<cir::IntType>(srcType))
679 return emitOpError() <<
"requires !cir.int type for source";
680 if (!mlir::dyn_cast<cir::PointerType>(resType))
681 return emitOpError() <<
"requires !cir.ptr type for result";
684 case cir::CastKind::ptr_to_int: {
685 if (!mlir::dyn_cast<cir::PointerType>(srcType))
686 return emitOpError() <<
"requires !cir.ptr type for source";
687 if (!mlir::dyn_cast<cir::IntType>(resType))
688 return emitOpError() <<
"requires !cir.int type for result";
691 case cir::CastKind::float_to_bool: {
692 if (!mlir::isa<cir::FPTypeInterface>(srcType))
693 return emitOpError() <<
"requires !cir.float type for source";
694 if (!mlir::isa<cir::BoolType>(resType))
695 return emitOpError() <<
"requires !cir.bool type for result";
698 case cir::CastKind::bool_to_int: {
699 if (!mlir::isa<cir::BoolType>(srcType))
700 return emitOpError() <<
"requires !cir.bool type for source";
701 if (!mlir::isa<cir::IntType>(resType))
702 return emitOpError() <<
"requires !cir.int type for result";
705 case cir::CastKind::int_to_float: {
706 if (!mlir::isa<cir::IntType>(srcType))
707 return emitOpError() <<
"requires !cir.int type for source";
708 if (!mlir::isa<cir::FPTypeInterface>(resType))
709 return emitOpError() <<
"requires !cir.float type for result";
712 case cir::CastKind::bool_to_float: {
713 if (!mlir::isa<cir::BoolType>(srcType))
714 return emitOpError() <<
"requires !cir.bool type for source";
715 if (!mlir::isa<cir::FPTypeInterface>(resType))
716 return emitOpError() <<
"requires !cir.float type for result";
719 case cir::CastKind::address_space: {
720 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
721 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
722 if (!srcPtrTy || !resPtrTy)
723 return emitOpError() <<
"requires !cir.ptr type for source and result";
724 if (srcPtrTy.getPointee() != resPtrTy.getPointee())
725 return emitOpError() <<
"requires two types differ in addrspace only";
728 case cir::CastKind::float_to_complex: {
729 if (!mlir::isa<cir::FPTypeInterface>(srcType))
730 return emitOpError() <<
"requires !cir.float type for source";
731 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
733 return emitOpError() <<
"requires !cir.complex type for result";
734 if (srcType != resComplexTy.getElementType())
735 return emitOpError() <<
"requires source type match result element type";
738 case cir::CastKind::int_to_complex: {
739 if (!mlir::isa<cir::IntType>(srcType))
740 return emitOpError() <<
"requires !cir.int type for source";
741 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
743 return emitOpError() <<
"requires !cir.complex type for result";
744 if (srcType != resComplexTy.getElementType())
745 return emitOpError() <<
"requires source type match result element type";
748 case cir::CastKind::float_complex_to_real: {
749 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
751 return emitOpError() <<
"requires !cir.complex type for source";
752 if (!mlir::isa<cir::FPTypeInterface>(resType))
753 return emitOpError() <<
"requires !cir.float type for result";
754 if (srcComplexTy.getElementType() != resType)
755 return emitOpError() <<
"requires source element type match result type";
758 case cir::CastKind::int_complex_to_real: {
759 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
761 return emitOpError() <<
"requires !cir.complex type for source";
762 if (!mlir::isa<cir::IntType>(resType))
763 return emitOpError() <<
"requires !cir.int type for result";
764 if (srcComplexTy.getElementType() != resType)
765 return emitOpError() <<
"requires source element type match result type";
768 case cir::CastKind::float_complex_to_bool: {
769 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
770 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
772 <<
"requires floating point !cir.complex type for source";
773 if (!mlir::isa<cir::BoolType>(resType))
774 return emitOpError() <<
"requires !cir.bool type for result";
777 case cir::CastKind::int_complex_to_bool: {
778 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
779 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
781 <<
"requires floating point !cir.complex type for source";
782 if (!mlir::isa<cir::BoolType>(resType))
783 return emitOpError() <<
"requires !cir.bool type for result";
786 case cir::CastKind::float_complex: {
787 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
788 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
790 <<
"requires floating point !cir.complex type for source";
791 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
792 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
794 <<
"requires floating point !cir.complex type for result";
797 case cir::CastKind::float_complex_to_int_complex: {
798 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
799 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
801 <<
"requires floating point !cir.complex type for source";
802 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
803 if (!resComplexTy || !resComplexTy.isIntegerComplex())
804 return emitOpError() <<
"requires integer !cir.complex type for result";
807 case cir::CastKind::int_complex: {
808 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
809 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
810 return emitOpError() <<
"requires integer !cir.complex type for source";
811 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
812 if (!resComplexTy || !resComplexTy.isIntegerComplex())
813 return emitOpError() <<
"requires integer !cir.complex type for result";
816 case cir::CastKind::int_complex_to_float_complex: {
817 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
818 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
819 return emitOpError() <<
"requires integer !cir.complex type for source";
820 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
821 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
823 <<
"requires floating point !cir.complex type for result";
826 case cir::CastKind::member_ptr_to_bool: {
827 if (!mlir::isa<cir::DataMemberType, cir::MethodType>(srcType))
829 <<
"requires !cir.data_member or !cir.method type for source";
830 if (!mlir::isa<cir::BoolType>(resType))
831 return emitOpError() <<
"requires !cir.bool type for result";
835 llvm_unreachable(
"Unknown CastOp kind?");
839 auto kind = op.getKind();
840 return kind == cir::CastKind::bool_to_int ||
841 kind == cir::CastKind::int_to_bool ||
kind == cir::CastKind::integral;
845 const auto ptrTy = mlir::dyn_cast<cir::PointerType>(ty);
846 return ptrTy && mlir::isa<cir::FuncType>(ptrTy.getPointee());
850 cir::CastOp head = op, tail = op;
856 op = head.getSrc().getDefiningOp<cir::CastOp>();
862 if (head.getKind() == cir::CastKind::bool_to_int &&
863 tail.getKind() == cir::CastKind::int_to_bool)
864 return head.getSrc();
869 if (head.getKind() == cir::CastKind::int_to_bool &&
870 tail.getKind() == cir::CastKind::int_to_bool)
871 return head.getResult();
879 if (tail.getKind() == cir::CastKind::bitcast) {
880 auto *inner = tail.getSrc().getDefiningOp();
882 auto innerCast = mlir::dyn_cast<cir::CastOp>(inner);
883 if (innerCast && innerCast.getKind() == cir::CastKind::bitcast &&
884 innerCast.getSrc().getType() == tail.getType() &&
885 innerCast.getType() == tail.getSrc().getType()) {
886 return innerCast.getSrc();
894OpFoldResult cir::CastOp::fold(FoldAdaptor adaptor) {
895 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getSrc())) {
897 return cir::PoisonAttr::get(getContext(),
getType());
902 case cir::CastKind::integral: {
904 auto foldOrder = getSrc().getDefiningOp()->fold(foldResults);
905 if (foldOrder.succeeded() && mlir::isa<mlir::Attribute>(foldResults[0]))
906 return mlir::cast<mlir::Attribute>(foldResults[0]);
909 case cir::CastKind::bitcast:
910 case cir::CastKind::address_space:
911 case cir::CastKind::float_complex:
912 case cir::CastKind::int_complex: {
926 if (
auto srcConst = getSrc().getDefiningOp<cir::ConstantOp>()) {
928 case cir::CastKind::integral: {
929 mlir::Type srcTy = getSrc().getType();
931 assert(mlir::isa<cir::VectorType>(srcTy) ==
932 mlir::isa<cir::VectorType>(
getType()));
933 if (mlir::isa<cir::VectorType>(srcTy))
936 auto srcIntTy = mlir::cast<cir::IntType>(srcTy);
937 auto dstIntTy = mlir::cast<cir::IntType>(
getType());
940 ? srcConst.getIntValue().sextOrTrunc(dstIntTy.getWidth())
941 : srcConst.getIntValue().zextOrTrunc(dstIntTy.getWidth());
942 return cir::IntAttr::get(dstIntTy, newVal);
955mlir::OperandRange cir::CallOp::getArgOperands() {
957 return getArgs().drop_front(1);
961mlir::MutableOperandRange cir::CallOp::getArgOperandsMutable() {
962 mlir::MutableOperandRange args = getArgsMutable();
964 return args.slice(1, args.size() - 1);
968mlir::Value cir::CallOp::getIndirectCall() {
969 assert(isIndirect());
970 return getOperand(0);
974Value cir::CallOp::getArgOperand(
unsigned i) {
977 return getOperand(i);
981unsigned cir::CallOp::getNumArgOperands() {
983 return this->getOperation()->getNumOperands() - 1;
984 return this->getOperation()->getNumOperands();
987static mlir::ParseResult
989 mlir::OperationState &result) {
990 mlir::Block *normalDestSuccessor;
991 if (parser.parseSuccessor(normalDestSuccessor))
992 return mlir::failure();
994 if (parser.parseComma())
995 return mlir::failure();
997 mlir::Block *unwindDestSuccessor;
998 if (parser.parseSuccessor(unwindDestSuccessor))
999 return mlir::failure();
1001 result.addSuccessors(normalDestSuccessor);
1002 result.addSuccessors(unwindDestSuccessor);
1003 return mlir::success();
1007 mlir::OperationState &result,
1008 bool hasDestinationBlocks =
false) {
1011 mlir::FlatSymbolRefAttr calleeAttr;
1015 .parseOptionalAttribute(calleeAttr, CIRDialect::getCalleeAttrName(),
1018 OpAsmParser::UnresolvedOperand indirectVal;
1020 if (parser.parseOperand(indirectVal).failed())
1022 ops.push_back(indirectVal);
1025 if (parser.parseLParen())
1026 return mlir::failure();
1028 opsLoc = parser.getCurrentLocation();
1029 if (parser.parseOperandList(ops))
1030 return mlir::failure();
1031 if (parser.parseRParen())
1032 return mlir::failure();
1034 if (hasDestinationBlocks &&
1036 return ::mlir::failure();
1039 if (parser.parseOptionalKeyword(
"musttail").succeeded())
1040 result.addAttribute(CIRDialect::getMustTailAttrName(),
1041 mlir::UnitAttr::get(parser.getContext()));
1043 if (parser.parseOptionalKeyword(
"nothrow").succeeded())
1044 result.addAttribute(CIRDialect::getNoThrowAttrName(),
1045 mlir::UnitAttr::get(parser.getContext()));
1047 if (parser.parseOptionalKeyword(
"side_effect").succeeded()) {
1048 if (parser.parseLParen().failed())
1050 cir::SideEffect sideEffect;
1053 if (parser.parseRParen().failed())
1055 auto attr = cir::SideEffectAttr::get(parser.getContext(), sideEffect);
1056 result.addAttribute(CIRDialect::getSideEffectAttrName(), attr);
1059 if (parser.parseOptionalAttrDict(result.attributes))
1060 return ::mlir::failure();
1062 if (parser.parseColon())
1063 return ::mlir::failure();
1069 if (call_interface_impl::parseFunctionSignature(parser, argTypes, argAttrs,
1070 resultTypes, resultAttrs))
1071 return mlir::failure();
1073 if (resultTypes.size() > 1 || resultAttrs.size() > 1)
1074 return parser.emitError(
1075 parser.getCurrentLocation(),
1076 "functions with multiple return types are not supported");
1078 result.addTypes(resultTypes);
1080 if (parser.resolveOperands(ops, argTypes, opsLoc, result.operands))
1081 return mlir::failure();
1083 if (!resultAttrs.empty() && resultAttrs[0])
1084 result.addAttribute(
1085 CIRDialect::getResAttrsAttrName(),
1086 mlir::ArrayAttr::get(parser.getContext(), {resultAttrs[0]}));
1091 bool argAttrsEmpty =
true;
1093 llvm::transform(argAttrs, std::back_inserter(convertedArgAttrs),
1094 [&](DictionaryAttr da) -> mlir::Attribute {
1096 argAttrsEmpty =
false;
1100 if (!argAttrsEmpty) {
1105 argAttrsRef = argAttrsRef.drop_front();
1107 result.addAttribute(CIRDialect::getArgAttrsAttrName(),
1108 mlir::ArrayAttr::get(parser.getContext(), argAttrsRef));
1111 return mlir::success();
1116 mlir::Value indirectCallee, mlir::OpAsmPrinter &printer,
1117 bool isNothrow, cir::SideEffect sideEffect, ArrayAttr argAttrs,
1118 ArrayAttr resAttrs, mlir::Block *normalDest =
nullptr,
1119 mlir::Block *unwindDest =
nullptr) {
1122 auto callLikeOp = mlir::cast<cir::CIRCallOpInterface>(op);
1123 auto ops = callLikeOp.getArgOperands();
1127 printer.printAttributeWithoutType(calleeSym);
1130 assert(indirectCallee);
1131 printer << indirectCallee;
1134 printer <<
"(" << ops <<
")";
1137 assert(unwindDest &&
"expected two successors");
1138 auto tryCall = cast<cir::TryCallOp>(op);
1139 printer <<
' ' << tryCall.getNormalDest();
1142 printer << tryCall.getUnwindDest();
1145 if (op->hasAttr(CIRDialect::getMustTailAttrName()))
1146 printer <<
" musttail";
1149 printer <<
" nothrow";
1151 if (sideEffect != cir::SideEffect::All) {
1152 printer <<
" side_effect(";
1153 printer << stringifySideEffect(sideEffect);
1158 CIRDialect::getCalleeAttrName(),
1159 CIRDialect::getMustTailAttrName(),
1160 CIRDialect::getNoThrowAttrName(),
1161 CIRDialect::getSideEffectAttrName(),
1162 CIRDialect::getOperandSegmentSizesAttrName(),
1163 llvm::StringRef(
"res_attrs"),
1164 llvm::StringRef(
"arg_attrs")};
1165 printer.printOptionalAttrDict(op->getAttrs(), elidedAttrs);
1167 if (calleeSym || !argAttrs) {
1168 call_interface_impl::printFunctionSignature(
1169 printer, op->getOperands().getTypes(), argAttrs,
1170 false, op->getResultTypes(), resAttrs);
1178 shimmedArgAttrs.push_back(mlir::DictionaryAttr::get(op->getContext(), {}));
1179 shimmedArgAttrs.append(argAttrs.begin(), argAttrs.end());
1180 call_interface_impl::printFunctionSignature(
1181 printer, op->getOperands().getTypes(),
1182 mlir::ArrayAttr::get(op->getContext(), shimmedArgAttrs),
1183 false, op->getResultTypes(), resAttrs);
1187mlir::ParseResult cir::CallOp::parse(mlir::OpAsmParser &parser,
1188 mlir::OperationState &result) {
1192void cir::CallOp::print(mlir::OpAsmPrinter &p) {
1193 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() :
nullptr;
1194 cir::SideEffect sideEffect = getSideEffect();
1195 printCallCommon(*
this, getCalleeAttr(), indirectCallee, p, getNothrow(),
1196 sideEffect, getArgAttrsAttr(), getResAttrsAttr());
1201 SymbolTableCollection &symbolTable) {
1203 op->getAttrOfType<FlatSymbolRefAttr>(CIRDialect::getCalleeAttrName());
1206 return mlir::success();
1209 auto fn = symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(op, fnAttr);
1211 return op->emitOpError() <<
"'" << fnAttr.getValue()
1212 <<
"' does not reference a valid function";
1214 auto callIf = dyn_cast<cir::CIRCallOpInterface>(op);
1215 assert(callIf &&
"expected CIR call interface to be always available");
1219 auto fnType = fn.getFunctionType();
1220 if (!fn.getNoProto()) {
1221 unsigned numCallOperands = callIf.getNumArgOperands();
1222 unsigned numFnOpOperands = fnType.getNumInputs();
1224 if (!fnType.isVarArg() && numCallOperands != numFnOpOperands)
1225 return op->emitOpError(
"incorrect number of operands for callee");
1226 if (fnType.isVarArg() && numCallOperands < numFnOpOperands)
1227 return op->emitOpError(
"too few operands for callee");
1229 for (
unsigned i = 0, e = numFnOpOperands; i != e; ++i)
1230 if (callIf.getArgOperand(i).getType() != fnType.getInput(i))
1231 return op->emitOpError(
"operand type mismatch: expected operand type ")
1232 << fnType.getInput(i) <<
", but provided "
1233 << op->getOperand(i).getType() <<
" for operand number " << i;
1239 if (fnType.hasVoidReturn() && op->getNumResults() != 0)
1240 return op->emitOpError(
"callee returns void but call has results");
1243 if (!fnType.hasVoidReturn() && op->getNumResults() != 1)
1244 return op->emitOpError(
"incorrect number of results for callee");
1247 if (!fnType.hasVoidReturn() &&
1248 op->getResultTypes().front() != fnType.getReturnType()) {
1249 return op->emitOpError(
"result type mismatch: expected ")
1250 << fnType.getReturnType() <<
", but provided "
1251 << op->getResult(0).getType();
1254 return mlir::success();
1258cir::CallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1266mlir::OperandRange cir::TryCallOp::getArgOperands() {
1268 return getArgs().drop_front(1);
1272mlir::MutableOperandRange cir::TryCallOp::getArgOperandsMutable() {
1273 mlir::MutableOperandRange args = getArgsMutable();
1275 return args.slice(1, args.size() - 1);
1279mlir::Value cir::TryCallOp::getIndirectCall() {
1280 assert(isIndirect());
1281 return getOperand(0);
1285Value cir::TryCallOp::getArgOperand(
unsigned i) {
1288 return getOperand(i);
1292unsigned cir::TryCallOp::getNumArgOperands() {
1294 return this->getOperation()->getNumOperands() - 1;
1295 return this->getOperation()->getNumOperands();
1299cir::TryCallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1303mlir::ParseResult cir::TryCallOp::parse(mlir::OpAsmParser &parser,
1304 mlir::OperationState &result) {
1308void cir::TryCallOp::print(::mlir::OpAsmPrinter &p) {
1309 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() :
nullptr;
1310 cir::SideEffect sideEffect = getSideEffect();
1311 printCallCommon(*
this, getCalleeAttr(), indirectCallee, p, getNothrow(),
1312 sideEffect, getArgAttrsAttr(), getResAttrsAttr(),
1313 getNormalDest(), getUnwindDest());
1321 cir::FuncOp function) {
1323 if (op.getNumOperands() > 1)
1324 return op.emitOpError() <<
"expects at most 1 return operand";
1327 auto expectedTy = function.getFunctionType().getReturnType();
1329 (op.getNumOperands() == 0 ? cir::VoidType::get(op.getContext())
1330 : op.getOperand(0).getType());
1331 if (actualTy != expectedTy)
1332 return op.emitOpError() <<
"returns " << actualTy
1333 <<
" but enclosing function returns " << expectedTy;
1335 return mlir::success();
1338mlir::LogicalResult cir::ReturnOp::verify() {
1341 auto *fnOp = getOperation()->getParentOp();
1342 while (!isa<cir::FuncOp>(fnOp))
1343 fnOp = fnOp->getParentOp();
1356ParseResult cir::IfOp::parse(OpAsmParser &parser, OperationState &result) {
1358 result.regions.reserve(2);
1359 Region *thenRegion = result.addRegion();
1360 Region *elseRegion = result.addRegion();
1362 mlir::Builder &builder = parser.getBuilder();
1363 OpAsmParser::UnresolvedOperand cond;
1364 Type boolType = cir::BoolType::get(builder.getContext());
1366 if (parser.parseOperand(cond) ||
1367 parser.resolveOperand(cond, boolType, result.operands))
1371 mlir::SMLoc parseThenLoc = parser.getCurrentLocation();
1372 if (parser.parseRegion(*thenRegion, {}, {}))
1379 if (!parser.parseOptionalKeyword(
"else")) {
1380 mlir::SMLoc parseElseLoc = parser.getCurrentLocation();
1381 if (parser.parseRegion(*elseRegion, {}, {}))
1388 if (parser.parseOptionalAttrDict(result.attributes))
1393void cir::IfOp::print(OpAsmPrinter &p) {
1394 p <<
" " << getCondition() <<
" ";
1395 mlir::Region &thenRegion = this->getThenRegion();
1396 p.printRegion(thenRegion,
1401 mlir::Region &elseRegion = this->getElseRegion();
1402 if (!elseRegion.empty()) {
1404 p.printRegion(elseRegion,
1409 p.printOptionalAttrDict(getOperation()->getAttrs());
1415 cir::YieldOp::create(builder, loc);
1423void cir::IfOp::getSuccessorRegions(mlir::RegionBranchPoint point,
1424 SmallVectorImpl<RegionSuccessor> ®ions) {
1426 if (!point.isParent()) {
1427 regions.push_back(RegionSuccessor::parent());
1432 Region *elseRegion = &this->getElseRegion();
1433 if (elseRegion->empty())
1434 elseRegion =
nullptr;
1437 regions.push_back(RegionSuccessor(&getThenRegion()));
1439 regions.push_back(RegionSuccessor(elseRegion));
1441 regions.push_back(RegionSuccessor::parent());
1444mlir::ValueRange cir::IfOp::getSuccessorInputs(RegionSuccessor successor) {
1445 return successor.isParent() ? ValueRange(getOperation()->getResults())
1449void cir::IfOp::build(OpBuilder &builder, OperationState &result,
Value cond,
1452 assert(thenBuilder &&
"the builder callback for 'then' must be present");
1453 result.addOperands(cond);
1455 OpBuilder::InsertionGuard guard(builder);
1456 Region *thenRegion = result.addRegion();
1457 builder.createBlock(thenRegion);
1458 thenBuilder(builder, result.location);
1460 Region *elseRegion = result.addRegion();
1461 if (!withElseRegion)
1464 builder.createBlock(elseRegion);
1465 elseBuilder(builder, result.location);
1477void cir::ScopeOp::getSuccessorRegions(
1478 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1480 if (!point.isParent()) {
1481 regions.push_back(RegionSuccessor::parent());
1486 regions.push_back(RegionSuccessor(&getScopeRegion()));
1489mlir::ValueRange cir::ScopeOp::getSuccessorInputs(RegionSuccessor successor) {
1490 return successor.isParent() ? ValueRange(getOperation()->getResults())
1494void cir::ScopeOp::build(
1495 OpBuilder &builder, OperationState &result,
1496 function_ref<
void(OpBuilder &, Type &, Location)> scopeBuilder) {
1497 assert(scopeBuilder &&
"the builder callback for 'then' must be present");
1499 OpBuilder::InsertionGuard guard(builder);
1500 Region *scopeRegion = result.addRegion();
1501 builder.createBlock(scopeRegion);
1505 scopeBuilder(builder, yieldTy, result.location);
1508 result.addTypes(TypeRange{yieldTy});
1511void cir::ScopeOp::build(
1512 OpBuilder &builder, OperationState &result,
1513 function_ref<
void(OpBuilder &, Location)> scopeBuilder) {
1514 assert(scopeBuilder &&
"the builder callback for 'then' must be present");
1515 OpBuilder::InsertionGuard guard(builder);
1516 Region *scopeRegion = result.addRegion();
1517 builder.createBlock(scopeRegion);
1519 scopeBuilder(builder, result.location);
1522LogicalResult cir::ScopeOp::verify() {
1524 return emitOpError() <<
"cir.scope must not be empty since it should "
1525 "include at least an implicit cir.yield ";
1528 mlir::Block &lastBlock =
getRegion().back();
1529 if (lastBlock.empty() || !lastBlock.mightHaveTerminator() ||
1530 !lastBlock.getTerminator()->hasTrait<OpTrait::IsTerminator>())
1531 return emitOpError() <<
"last block of cir.scope must be terminated";
1535LogicalResult cir::ScopeOp::fold(FoldAdaptor ,
1536 SmallVectorImpl<OpFoldResult> &results) {
1541 if (block.getOperations().size() != 1)
1544 auto yield = dyn_cast<cir::YieldOp>(block.front());
1549 if (getNumResults() != 1 || yield.getNumOperands() != 1)
1552 results.push_back(yield.getOperand(0));
1560void cir::CleanupScopeOp::getSuccessorRegions(
1561 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1562 if (!point.isParent()) {
1563 regions.push_back(RegionSuccessor::parent());
1568 regions.push_back(RegionSuccessor(&getBodyRegion()));
1569 regions.push_back(RegionSuccessor(&getCleanupRegion()));
1573cir::CleanupScopeOp::getSuccessorInputs(RegionSuccessor successor) {
1574 return ValueRange();
1577LogicalResult cir::CleanupScopeOp::canonicalize(CleanupScopeOp op,
1578 PatternRewriter &rewriter) {
1579 auto isRegionTrivial = [](Region ®ion) {
1580 assert(!region.empty() &&
"CleanupScopeOp regions must not be empty");
1581 if (!region.hasOneBlock())
1583 Block &block = llvm::getSingleElement(region);
1584 return llvm::hasSingleElement(block) &&
1585 isa<cir::YieldOp>(llvm::getSingleElement(block));
1588 Region &body = op.getBodyRegion();
1589 Region &
cleanup = op.getCleanupRegion();
1593 if (op.getCleanupKind() == CleanupKind::EH && isRegionTrivial(body)) {
1594 rewriter.eraseOp(op);
1600 if (!isRegionTrivial(
cleanup) || !body.hasOneBlock())
1603 Block &bodyBlock = body.front();
1604 if (!isa<cir::YieldOp>(bodyBlock.getTerminator()))
1607 Operation *yield = bodyBlock.getTerminator();
1608 rewriter.inlineBlockBefore(&bodyBlock, op);
1609 rewriter.eraseOp(yield);
1610 rewriter.eraseOp(op);
1614void cir::CleanupScopeOp::build(
1615 OpBuilder &builder, OperationState &result, CleanupKind cleanupKind,
1616 function_ref<
void(OpBuilder &, Location)> bodyBuilder,
1617 function_ref<
void(OpBuilder &, Location)> cleanupBuilder) {
1618 result.addAttribute(getCleanupKindAttrName(result.name),
1619 CleanupKindAttr::get(builder.getContext(), cleanupKind));
1621 OpBuilder::InsertionGuard guard(builder);
1624 Region *bodyRegion = result.addRegion();
1625 builder.createBlock(bodyRegion);
1627 bodyBuilder(builder, result.location);
1630 Region *cleanupRegion = result.addRegion();
1631 builder.createBlock(cleanupRegion);
1633 cleanupBuilder(builder, result.location);
1648LogicalResult cir::BrOp::canonicalize(BrOp op, PatternRewriter &rewriter) {
1649 Block *src = op->getBlock();
1650 Block *dst = op.getDest();
1657 if (src->getNumSuccessors() != 1 || dst->getSinglePredecessor() != src)
1662 if (isa<cir::LabelOp, cir::IndirectBrOp>(dst->front()))
1665 auto operands = op.getDestOperands();
1666 rewriter.eraseOp(op);
1667 rewriter.mergeBlocks(dst, src, operands);
1671mlir::SuccessorOperands cir::BrOp::getSuccessorOperands(
unsigned index) {
1672 assert(index == 0 &&
"invalid successor index");
1673 return mlir::SuccessorOperands(getDestOperandsMutable());
1684mlir::SuccessorOperands
1685cir::IndirectBrOp::getSuccessorOperands(
unsigned index) {
1686 assert(index < getNumSuccessors() &&
"invalid successor index");
1687 return mlir::SuccessorOperands(getSuccOperandsMutable()[index]);
1691 OpAsmParser &parser, Type &flagType,
1692 SmallVectorImpl<Block *> &succOperandBlocks,
1695 if (failed(parser.parseCommaSeparatedList(
1696 OpAsmParser::Delimiter::Square,
1698 Block *destination = nullptr;
1699 SmallVector<OpAsmParser::UnresolvedOperand> operands;
1700 SmallVector<Type> operandTypes;
1702 if (parser.parseSuccessor(destination).failed())
1705 if (succeeded(parser.parseOptionalLParen())) {
1706 if (failed(parser.parseOperandList(
1707 operands, OpAsmParser::Delimiter::None)) ||
1708 failed(parser.parseColonTypeList(operandTypes)) ||
1709 failed(parser.parseRParen()))
1712 succOperandBlocks.push_back(destination);
1713 succOperands.emplace_back(operands);
1714 succOperandsTypes.emplace_back(operandTypes);
1717 "successor blocks")))
1723 Type flagType, SuccessorRange succs,
1724 OperandRangeRange succOperands,
1725 const TypeRangeRange &succOperandsTypes) {
1728 llvm::zip(succs, succOperands),
1731 p.printSuccessorAndUseList(std::get<0>(i), std::get<1>(i));
1734 if (!succOperands.empty())
1743mlir::SuccessorOperands cir::BrCondOp::getSuccessorOperands(
unsigned index) {
1744 assert(index < getNumSuccessors() &&
"invalid successor index");
1745 return SuccessorOperands(index == 0 ? getDestOperandsTrueMutable()
1746 : getDestOperandsFalseMutable());
1750 if (IntegerAttr condAttr = dyn_cast_if_present<IntegerAttr>(operands.front()))
1751 return condAttr.getValue().isOne() ? getDestTrue() : getDestFalse();
1759void cir::CaseOp::getSuccessorRegions(
1760 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1761 if (!point.isParent()) {
1762 regions.push_back(RegionSuccessor::parent());
1765 regions.push_back(RegionSuccessor(&getCaseRegion()));
1768mlir::ValueRange cir::CaseOp::getSuccessorInputs(RegionSuccessor successor) {
1769 return successor.isParent() ? ValueRange(getOperation()->getResults())
1773void cir::CaseOp::build(OpBuilder &builder, OperationState &result,
1774 ArrayAttr value, CaseOpKind
kind,
1775 OpBuilder::InsertPoint &insertPoint) {
1776 OpBuilder::InsertionGuard guardSwitch(builder);
1777 result.addAttribute(
"value", value);
1778 result.getOrAddProperties<Properties>().
kind =
1779 cir::CaseOpKindAttr::get(builder.getContext(),
kind);
1780 Region *caseRegion = result.addRegion();
1781 builder.createBlock(caseRegion);
1783 insertPoint = builder.saveInsertionPoint();
1790void cir::SwitchOp::getSuccessorRegions(
1791 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ion) {
1792 if (!point.isParent()) {
1793 region.push_back(RegionSuccessor::parent());
1797 region.push_back(RegionSuccessor(&getBody()));
1800mlir::ValueRange cir::SwitchOp::getSuccessorInputs(RegionSuccessor successor) {
1801 return successor.isParent() ? ValueRange(getOperation()->getResults())
1805void cir::SwitchOp::build(OpBuilder &builder, OperationState &result,
1807 assert(switchBuilder &&
"the builder callback for regions must be present");
1808 OpBuilder::InsertionGuard guardSwitch(builder);
1809 Region *switchRegion = result.addRegion();
1810 builder.createBlock(switchRegion);
1811 result.addOperands({cond});
1812 switchBuilder(builder, result.location, result);
1816 walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
1818 if (isa<cir::SwitchOp>(op) && op != *
this)
1819 return WalkResult::skip();
1821 if (
auto caseOp = dyn_cast<cir::CaseOp>(op))
1822 cases.push_back(caseOp);
1824 return WalkResult::advance();
1829 collectCases(cases);
1831 if (getBody().empty())
1834 if (!isa<YieldOp>(getBody().front().back()))
1837 if (!llvm::all_of(getBody().front(),
1838 [](Operation &op) {
return isa<CaseOp, YieldOp>(op); }))
1841 return llvm::all_of(cases, [
this](CaseOp op) {
1842 return op->getParentOfType<SwitchOp>() == *
this;
1850void cir::SwitchFlatOp::build(OpBuilder &builder, OperationState &result,
1851 Value value, Block *defaultDestination,
1852 ValueRange defaultOperands,
1854 BlockRange caseDestinations,
1857 std::vector<mlir::Attribute> caseValuesAttrs;
1858 for (
const APInt &val : caseValues)
1859 caseValuesAttrs.push_back(cir::IntAttr::get(value.getType(), val));
1860 mlir::ArrayAttr attrs = ArrayAttr::get(builder.getContext(), caseValuesAttrs);
1862 build(builder, result, value, defaultOperands, caseOperands, attrs,
1863 defaultDestination, caseDestinations);
1869 OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues,
1870 SmallVectorImpl<Block *> &caseDestinations,
1874 if (failed(parser.parseLSquare()))
1876 if (succeeded(parser.parseOptionalRSquare()))
1880 auto parseCase = [&]() {
1882 if (failed(parser.parseInteger(value)))
1885 values.push_back(cir::IntAttr::get(flagType, value));
1890 if (parser.parseColon() || parser.parseSuccessor(destination))
1892 if (!parser.parseOptionalLParen()) {
1893 if (parser.parseOperandList(operands, OpAsmParser::Delimiter::None,
1895 parser.parseColonTypeList(operandTypes) || parser.parseRParen())
1898 caseDestinations.push_back(destination);
1899 caseOperands.emplace_back(operands);
1900 caseOperandTypes.emplace_back(operandTypes);
1903 if (failed(parser.parseCommaSeparatedList(parseCase)))
1906 caseValues = ArrayAttr::get(flagType.getContext(), values);
1908 return parser.parseRSquare();
1912 Type flagType, mlir::ArrayAttr caseValues,
1913 SuccessorRange caseDestinations,
1914 OperandRangeRange caseOperands,
1915 const TypeRangeRange &caseOperandTypes) {
1925 llvm::zip(caseValues, caseDestinations),
1928 mlir::Attribute a = std::get<0>(i);
1929 p << mlir::cast<cir::IntAttr>(a).getValue();
1931 p.printSuccessorAndUseList(std::get<1>(i), caseOperands[index++]);
1946 mlir::Attribute &valueAttr) {
1948 return parser.parseAttribute(valueAttr,
"value", attr);
1952 p.printAttribute(value);
1955mlir::LogicalResult cir::GlobalOp::verify() {
1958 if (getInitialValue().has_value()) {
1964 if ((getStaticLocalGuard().has_value()) &&
1965 (!getCtorRegion().empty() || !getDtorRegion().empty()))
1967 "Cannot have a static-local global-op with a constructor or "
1968 "destructor, they require in-function initialization via LocalInitOp");
1970 if (getDynTlsRefs()) {
1971 if (getStaticLocalGuard().has_value())
1973 "cannot have both static local and dynamic tls references");
1974 if (!getTlsModel() || getTlsModel() != TLS_Model::GeneralDynamic)
1975 return emitOpError(
"'dyn_tls_refs' only valid for dynamic tls");
1978 if (getAliasee().has_value()) {
1979 if (getInitialValue().has_value() || !getCtorRegion().empty() ||
1980 !getDtorRegion().empty())
1981 return emitOpError(
"global alias shall not have an initializer or "
1982 "constructor/destructor regions");
1991void cir::GlobalOp::build(
1992 OpBuilder &odsBuilder, OperationState &odsState, llvm::StringRef sym_name,
1993 mlir::Type sym_type,
bool isConstant,
1994 mlir::ptr::MemorySpaceAttrInterface addrSpace,
1995 cir::GlobalLinkageKind linkage,
1996 function_ref<
void(OpBuilder &, Location)> ctorBuilder,
1997 function_ref<
void(OpBuilder &, Location)> dtorBuilder) {
1998 odsState.addAttribute(getSymNameAttrName(odsState.name),
1999 odsBuilder.getStringAttr(sym_name));
2000 odsState.addAttribute(getSymTypeAttrName(odsState.name),
2001 mlir::TypeAttr::get(sym_type));
2002 auto &properties = odsState.getOrAddProperties<cir::GlobalOp::Properties>();
2003 properties.setConstant(isConstant);
2007 odsState.addAttribute(getAddrSpaceAttrName(odsState.name), addrSpace);
2009 cir::GlobalLinkageKindAttr linkageAttr =
2010 cir::GlobalLinkageKindAttr::get(odsBuilder.getContext(), linkage);
2011 odsState.addAttribute(getLinkageAttrName(odsState.name), linkageAttr);
2013 Region *ctorRegion = odsState.addRegion();
2015 odsBuilder.createBlock(ctorRegion);
2016 ctorBuilder(odsBuilder, odsState.location);
2019 Region *dtorRegion = odsState.addRegion();
2021 odsBuilder.createBlock(dtorRegion);
2022 dtorBuilder(odsBuilder, odsState.location);
2031void cir::GlobalOp::getSuccessorRegions(
2032 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
2034 if (!point.isParent()) {
2035 regions.push_back(RegionSuccessor::parent());
2040 Region *ctorRegion = &this->getCtorRegion();
2041 if (ctorRegion->empty())
2042 ctorRegion =
nullptr;
2045 Region *dtorRegion = &this->getDtorRegion();
2046 if (dtorRegion->empty())
2047 dtorRegion =
nullptr;
2051 regions.push_back(RegionSuccessor(ctorRegion));
2053 regions.push_back(RegionSuccessor(dtorRegion));
2056mlir::ValueRange cir::GlobalOp::getSuccessorInputs(RegionSuccessor successor) {
2057 return successor.isParent() ? ValueRange(getOperation()->getResults())
2062 TypeAttr type, Attribute initAttr,
2063 mlir::Region &ctorRegion,
2064 mlir::Region &dtorRegion) {
2065 auto printType = [&]() { p <<
": " << type; };
2068 if (op.isDeclaration() || op.getAliasee()) {
2074 if (!ctorRegion.empty()) {
2078 p.printRegion(ctorRegion,
2087 if (!dtorRegion.empty()) {
2089 p.printRegion(dtorRegion,
2097 Attribute &initialValueAttr,
2098 mlir::Region &ctorRegion,
2099 mlir::Region &dtorRegion) {
2101 if (parser.parseOptionalEqual().failed()) {
2104 if (parser.parseColonType(opTy))
2109 if (!parser.parseOptionalKeyword(
"ctor")) {
2110 if (parser.parseColonType(opTy))
2112 auto parseLoc = parser.getCurrentLocation();
2113 if (parser.parseRegion(ctorRegion, {}, {}))
2124 assert(mlir::isa<mlir::TypedAttr>(initialValueAttr) &&
2125 "Non-typed attrs shouldn't appear here.");
2126 auto typedAttr = mlir::cast<mlir::TypedAttr>(initialValueAttr);
2127 opTy = typedAttr.getType();
2132 if (!parser.parseOptionalKeyword(
"dtor")) {
2133 auto parseLoc = parser.getCurrentLocation();
2134 if (parser.parseRegion(dtorRegion, {}, {}))
2141 typeAttr = TypeAttr::get(opTy);
2150cir::GetGlobalOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2153 mlir::Operation *op =
2154 symbolTable.lookupNearestSymbolFrom(*
this, getNameAttr());
2155 if (op ==
nullptr || !(isa<GlobalOp>(op) || isa<FuncOp>(op)))
2156 return emitOpError(
"'")
2158 <<
"' does not reference a valid cir.global or cir.func";
2161 mlir::ptr::MemorySpaceAttrInterface symAddrSpaceAttr{};
2162 if (
auto g = dyn_cast<GlobalOp>(op)) {
2163 symTy = g.getSymType();
2164 symAddrSpaceAttr = g.getAddrSpaceAttr();
2167 if (getTls() && !g.getTlsModel())
2168 return emitOpError(
"access to global not marked thread local");
2173 bool getGlobalIsStaticLocal = getStaticLocal();
2174 bool globalIsStaticLocal = g.getStaticLocalGuard().has_value();
2175 if (getGlobalIsStaticLocal != globalIsStaticLocal &&
2176 !getOperation()->getParentOfType<cir::GlobalOp>())
2177 return emitOpError(
"static_local attribute mismatch");
2178 }
else if (
auto f = dyn_cast<FuncOp>(op)) {
2179 symTy = f.getFunctionType();
2181 llvm_unreachable(
"Unexpected operation for GetGlobalOp");
2184 auto resultType = dyn_cast<PointerType>(getAddr().
getType());
2185 if (!resultType || symTy != resultType.getPointee())
2186 return emitOpError(
"result type pointee type '")
2187 << resultType.getPointee() <<
"' does not match type " << symTy
2188 <<
" of the global @" <<
getName();
2190 if (symAddrSpaceAttr != resultType.getAddrSpace()) {
2191 return emitOpError()
2192 <<
"result type address space does not match the address "
2193 "space of the global @"
2205cir::VTableAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2211 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*
this, getNameAttr());
2213 return emitOpError(
"'")
2214 <<
name <<
"' does not reference a valid cir.global";
2215 std::optional<mlir::Attribute> init = op.getInitialValue();
2218 if (!isa<cir::VTableAttr>(*init))
2219 return emitOpError(
"Expected #cir.vtable in initializer for global '")
2229cir::VTTAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2238 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*
this, getNameAttr());
2240 return emitOpError(
"'")
2241 <<
name <<
"' does not reference a valid cir.global";
2242 std::optional<mlir::Attribute> init = op.getInitialValue();
2245 if (!isa<cir::ConstArrayAttr>(*init))
2247 "Expected constant array in initializer for global VTT '")
2252LogicalResult cir::VTTAddrPointOp::verify() {
2254 if (
getName() && getSymAddr())
2255 return emitOpError(
"should use either a symbol or value, but not both");
2261 mlir::Type resultType = getAddr().getType();
2262 mlir::Type resTy = cir::PointerType::get(
2263 cir::PointerType::get(cir::VoidType::get(getContext())));
2265 if (resultType != resTy)
2266 return emitOpError(
"result type must be ")
2267 << resTy <<
", but provided result type is " << resultType;
2279void cir::FuncOp::build(OpBuilder &builder, OperationState &result,
2280 StringRef name, FuncType type,
2281 GlobalLinkageKind linkage, CallingConv callingConv) {
2283 result.addAttribute(SymbolTable::getSymbolAttrName(),
2284 builder.getStringAttr(name));
2285 result.addAttribute(getFunctionTypeAttrName(result.name),
2286 TypeAttr::get(type));
2287 result.addAttribute(
2289 GlobalLinkageKindAttr::get(builder.getContext(), linkage));
2290 result.addAttribute(getCallingConvAttrName(result.name),
2291 CallingConvAttr::get(builder.getContext(), callingConv));
2299cir::AnnotationAttr::verify(function_ref<InFlightDiagnostic()> emitError,
2300 mlir::StringAttr name, mlir::ArrayAttr args) {
2303 for (mlir::Attribute arg : args) {
2304 if (!isa<mlir::StringAttr, mlir::IntegerAttr>(arg))
2305 return emitError() <<
"annotation args must be StringAttr or IntegerAttr,"
2311ParseResult cir::FuncOp::parse(OpAsmParser &parser, OperationState &state) {
2312 llvm::SMLoc loc = parser.getCurrentLocation();
2313 mlir::Builder &builder = parser.getBuilder();
2315 mlir::StringAttr builtinNameAttr = getBuiltinAttrName(state.name);
2316 mlir::StringAttr coroutineNameAttr = getCoroutineAttrName(state.name);
2317 mlir::StringAttr inlineKindNameAttr = getInlineKindAttrName(state.name);
2318 mlir::StringAttr lambdaNameAttr = getLambdaAttrName(state.name);
2319 mlir::StringAttr noProtoNameAttr = getNoProtoAttrName(state.name);
2320 mlir::StringAttr comdatNameAttr = getComdatAttrName(state.name);
2321 mlir::StringAttr visNameAttr = getSymVisibilityAttrName(state.name);
2322 mlir::StringAttr dsoLocalNameAttr = getDsoLocalAttrName(state.name);
2323 mlir::StringAttr specialMemberAttr = getCxxSpecialMemberAttrName(state.name);
2325 if (::mlir::succeeded(parser.parseOptionalKeyword(builtinNameAttr.strref())))
2326 state.addAttribute(builtinNameAttr, parser.getBuilder().getUnitAttr());
2327 if (::mlir::succeeded(
2328 parser.parseOptionalKeyword(coroutineNameAttr.strref())))
2329 state.addAttribute(coroutineNameAttr, parser.getBuilder().getUnitAttr());
2332 cir::InlineKindAttr inlineKindAttr;
2336 state.addAttribute(inlineKindNameAttr, inlineKindAttr);
2338 if (::mlir::succeeded(parser.parseOptionalKeyword(lambdaNameAttr.strref())))
2339 state.addAttribute(lambdaNameAttr, parser.getBuilder().getUnitAttr());
2340 if (parser.parseOptionalKeyword(noProtoNameAttr).succeeded())
2341 state.addAttribute(noProtoNameAttr, parser.getBuilder().getUnitAttr());
2343 if (parser.parseOptionalKeyword(comdatNameAttr).succeeded())
2344 state.addAttribute(comdatNameAttr, parser.getBuilder().getUnitAttr());
2348 GlobalLinkageKindAttr::get(
2349 parser.getContext(),
2351 parser, GlobalLinkageKind::ExternalLinkage)));
2353 ::llvm::StringRef visAttrStr;
2354 if (parser.parseOptionalKeyword(&visAttrStr, {
"private",
"public",
"nested"})
2356 state.addAttribute(visNameAttr,
2357 parser.getBuilder().getStringAttr(visAttrStr));
2360 state.getOrAddProperties<cir::FuncOp::Properties>().global_visibility =
2363 if (parser.parseOptionalKeyword(dsoLocalNameAttr).succeeded())
2364 state.addAttribute(dsoLocalNameAttr, parser.getBuilder().getUnitAttr());
2366 StringAttr nameAttr;
2367 if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
2373 bool isVariadic =
false;
2374 if (function_interface_impl::parseFunctionSignatureWithArguments(
2375 parser,
true, arguments, isVariadic, resultTypes,
2380 bool argAttrsEmpty =
true;
2381 for (OpAsmParser::Argument &arg : arguments) {
2382 argTypes.push_back(
arg.type);
2386 argAttrs.push_back(
arg.attrs);
2388 argAttrsEmpty =
false;
2392 if (resultTypes.size() > 1 || resultAttrs.size() > 1)
2393 return parser.emitError(
2394 loc,
"functions with multiple return types are not supported");
2396 mlir::Type returnType =
2397 (resultTypes.empty() ? cir::VoidType::get(builder.getContext())
2398 : resultTypes.front());
2400 cir::FuncType fnType = cir::FuncType::get(argTypes, returnType, isVariadic);
2404 state.addAttribute(getFunctionTypeAttrName(state.name),
2405 TypeAttr::get(fnType));
2407 if (!resultAttrs.empty() && resultAttrs[0])
2409 getResAttrsAttrName(state.name),
2410 mlir::ArrayAttr::get(parser.getContext(), {resultAttrs[0]}));
2413 state.addAttribute(getArgAttrsAttrName(state.name),
2414 mlir::ArrayAttr::get(parser.getContext(), argAttrs));
2416 bool hasAlias =
false;
2417 mlir::StringAttr aliaseeNameAttr = getAliaseeAttrName(state.name);
2418 if (parser.parseOptionalKeyword(
"alias").succeeded()) {
2419 if (parser.parseLParen().failed())
2421 mlir::StringAttr aliaseeAttr;
2422 if (parser.parseOptionalSymbolName(aliaseeAttr).failed())
2424 state.addAttribute(aliaseeNameAttr, FlatSymbolRefAttr::get(aliaseeAttr));
2425 if (parser.parseRParen().failed())
2430 mlir::StringAttr personalityNameAttr = getPersonalityAttrName(state.name);
2431 if (parser.parseOptionalKeyword(
"personality").succeeded()) {
2432 if (parser.parseLParen().failed())
2434 mlir::StringAttr personalityAttr;
2435 if (parser.parseOptionalSymbolName(personalityAttr).failed())
2437 state.addAttribute(personalityNameAttr,
2438 FlatSymbolRefAttr::get(personalityAttr));
2439 if (parser.parseRParen().failed())
2444 mlir::StringAttr callConvNameAttr = getCallingConvAttrName(state.name);
2445 cir::CallingConv callConv = cir::CallingConv::C;
2446 if (parser.parseOptionalKeyword(
"cc").succeeded()) {
2447 if (parser.parseLParen().failed())
2450 return parser.emitError(loc) <<
"unknown calling convention";
2451 if (parser.parseRParen().failed())
2454 state.addAttribute(callConvNameAttr,
2455 cir::CallingConvAttr::get(parser.getContext(), callConv));
2457 auto parseGlobalDtorCtor =
2458 [&](StringRef keyword,
2459 llvm::function_ref<void(std::optional<int> prio)> createAttr)
2460 -> mlir::LogicalResult {
2461 if (mlir::succeeded(parser.parseOptionalKeyword(keyword))) {
2462 std::optional<int> priority;
2463 if (mlir::succeeded(parser.parseOptionalLParen())) {
2464 auto parsedPriority = mlir::FieldParser<int>::parse(parser);
2465 if (mlir::failed(parsedPriority))
2466 return parser.emitError(parser.getCurrentLocation(),
2467 "failed to parse 'priority', of type 'int'");
2468 priority = parsedPriority.value_or(
int());
2470 if (parser.parseRParen())
2473 createAttr(priority);
2479 if (parser.parseOptionalKeyword(
"special_member").succeeded()) {
2480 if (parser.parseLess().failed())
2483 mlir::Attribute
attr;
2484 if (parser.parseAttribute(attr).failed())
2486 if (!mlir::isa<cir::CXXCtorAttr, cir::CXXDtorAttr, cir::CXXAssignAttr>(
2488 return parser.emitError(parser.getCurrentLocation(),
2489 "expected a C++ special member attribute");
2490 state.addAttribute(specialMemberAttr, attr);
2492 if (parser.parseGreater().failed())
2496 if (parseGlobalDtorCtor(
"global_ctor", [&](std::optional<int> priority) {
2497 mlir::IntegerAttr globalCtorPriorityAttr =
2498 builder.getI32IntegerAttr(priority.value_or(65535));
2499 state.addAttribute(getGlobalCtorPriorityAttrName(state.name),
2500 globalCtorPriorityAttr);
2504 if (parseGlobalDtorCtor(
"global_dtor", [&](std::optional<int> priority) {
2505 mlir::IntegerAttr globalDtorPriorityAttr =
2506 builder.getI32IntegerAttr(priority.value_or(65535));
2507 state.addAttribute(getGlobalDtorPriorityAttrName(state.name),
2508 globalDtorPriorityAttr);
2512 if (parser.parseOptionalKeyword(
"side_effect").succeeded()) {
2513 cir::SideEffect sideEffect;
2515 if (parser.parseLParen().failed() ||
2517 parser.parseRParen().failed())
2520 auto attr = cir::SideEffectAttr::get(parser.getContext(), sideEffect);
2521 state.addAttribute(CIRDialect::getSideEffectAttrName(), attr);
2525 mlir::StringAttr annotationsNameAttr = getAnnotationsAttrName(state.name);
2526 mlir::ArrayAttr annotationsAttr;
2527 if (parser.parseOptionalAttribute(annotationsAttr).has_value() &&
2529 state.addAttribute(annotationsNameAttr, annotationsAttr);
2532 NamedAttrList parsedAttrs;
2533 if (parser.parseOptionalAttrDictWithKeyword(parsedAttrs))
2536 for (StringRef disallowed : cir::FuncOp::getAttributeNames()) {
2537 if (parsedAttrs.get(disallowed))
2538 return parser.emitError(loc,
"attribute '")
2540 <<
"' should not be specified in the explicit attribute list";
2543 state.attributes.append(parsedAttrs);
2546 auto *body = state.addRegion();
2547 OptionalParseResult parseResult = parser.parseOptionalRegion(
2548 *body, arguments,
false);
2549 if (parseResult.has_value()) {
2551 return parser.emitError(loc,
"function alias shall not have a body");
2552 if (failed(*parseResult))
2556 return parser.emitError(loc,
"expected non-empty function body");
2565bool cir::FuncOp::isDeclaration() {
2568 std::optional<StringRef> aliasee = getAliasee();
2570 return getFunctionBody().empty();
2576bool cir::FuncOp::isCXXSpecialMemberFunction() {
2577 return getCxxSpecialMemberAttr() !=
nullptr;
2580bool cir::FuncOp::isCxxConstructor() {
2581 auto attr = getCxxSpecialMemberAttr();
2582 return attr && dyn_cast<CXXCtorAttr>(attr);
2585bool cir::FuncOp::isCxxDestructor() {
2586 auto attr = getCxxSpecialMemberAttr();
2587 return attr && dyn_cast<CXXDtorAttr>(attr);
2590bool cir::FuncOp::isCxxSpecialAssignment() {
2591 auto attr = getCxxSpecialMemberAttr();
2592 return attr && dyn_cast<CXXAssignAttr>(attr);
2595std::optional<CtorKind> cir::FuncOp::getCxxConstructorKind() {
2596 mlir::Attribute
attr = getCxxSpecialMemberAttr();
2598 if (
auto ctor = dyn_cast<CXXCtorAttr>(attr))
2599 return ctor.getCtorKind();
2601 return std::nullopt;
2604std::optional<AssignKind> cir::FuncOp::getCxxSpecialAssignKind() {
2605 mlir::Attribute
attr = getCxxSpecialMemberAttr();
2607 if (
auto assign = dyn_cast<CXXAssignAttr>(attr))
2608 return assign.getAssignKind();
2610 return std::nullopt;
2613bool cir::FuncOp::isCxxTrivialMemberFunction() {
2614 mlir::Attribute
attr = getCxxSpecialMemberAttr();
2616 if (
auto ctor = dyn_cast<CXXCtorAttr>(attr))
2617 return ctor.getIsTrivial();
2618 if (
auto dtor = dyn_cast<CXXDtorAttr>(attr))
2619 return dtor.getIsTrivial();
2620 if (
auto assign = dyn_cast<CXXAssignAttr>(attr))
2621 return assign.getIsTrivial();
2626mlir::Region *cir::FuncOp::getCallableRegion() {
2632void cir::FuncOp::print(OpAsmPrinter &p) {
2650 if (getLinkage() != GlobalLinkageKind::ExternalLinkage)
2651 p <<
' ' << stringifyGlobalLinkageKind(getLinkage());
2653 mlir::SymbolTable::Visibility vis = getVisibility();
2654 if (vis != mlir::SymbolTable::Visibility::Public)
2657 if (getGlobalVisibility() != cir::VisibilityKind::Default)
2658 p <<
' ' << stringifyVisibilityKind(getGlobalVisibility());
2664 p.printSymbolName(getSymName());
2665 cir::FuncType fnType = getFunctionType();
2666 function_interface_impl::printFunctionSignature(
2667 p, *
this, fnType.getInputs(), fnType.isVarArg(), fnType.getReturnTypes());
2669 if (std::optional<StringRef> aliaseeName = getAliasee()) {
2671 p.printSymbolName(*aliaseeName);
2675 if (getCallingConv() != cir::CallingConv::C) {
2677 p << stringifyCallingConv(getCallingConv());
2681 if (std::optional<StringRef> personalityName = getPersonality()) {
2682 p <<
" personality(";
2683 p.printSymbolName(*personalityName);
2687 if (
auto specialMemberAttr = getCxxSpecialMember()) {
2688 p <<
" special_member<";
2689 p.printAttribute(*specialMemberAttr);
2693 if (
auto globalCtorPriority = getGlobalCtorPriority()) {
2694 p <<
" global_ctor";
2695 if (globalCtorPriority.value() != 65535)
2696 p <<
"(" << globalCtorPriority.value() <<
")";
2699 if (
auto globalDtorPriority = getGlobalDtorPriority()) {
2700 p <<
" global_dtor";
2701 if (globalDtorPriority.value() != 65535)
2702 p <<
"(" << globalDtorPriority.value() <<
")";
2705 if (std::optional<cir::SideEffect> sideEffect = getSideEffect();
2706 sideEffect && *sideEffect != cir::SideEffect::All) {
2707 p <<
" side_effect(";
2708 p << stringifySideEffect(*sideEffect);
2712 if (mlir::ArrayAttr annotations = getAnnotationsAttr()) {
2714 p.printAttribute(annotations);
2717 function_interface_impl::printFunctionAttributes(
2718 p, *
this, cir::FuncOp::getAttributeNames());
2721 Region &body = getOperation()->getRegion(0);
2722 if (!body.empty()) {
2724 p.printRegion(body,
false,
2729mlir::LogicalResult cir::FuncOp::verify() {
2731 if (!isDeclaration() && getCoroutine()) {
2732 bool foundAwait =
false;
2733 int coroBodyCount = 0;
2734 this->walk([&](Operation *op) {
2735 if (
auto await = dyn_cast<AwaitOp>(op)) {
2737 }
else if (isa<CoroBodyOp>(op)) {
2739 if (coroBodyCount > 1) {
2740 return mlir::WalkResult::interrupt();
2743 return mlir::WalkResult::advance();
2746 return emitOpError()
2747 <<
"coroutine body must use at least one cir.await op";
2748 if (coroBodyCount != 1)
2749 return emitOpError()
2750 <<
"coroutine function must have exactly one cir.body op";
2753 llvm::SmallSet<llvm::StringRef, 16> labels;
2754 llvm::SmallSet<llvm::StringRef, 16> gotos;
2755 llvm::SmallSet<llvm::StringRef, 16> blockAddresses;
2756 bool invalidBlockAddress =
false;
2757 getOperation()->walk([&](mlir::Operation *op) {
2758 if (
auto lab = dyn_cast<cir::LabelOp>(op)) {
2759 labels.insert(lab.getLabel());
2760 }
else if (
auto goTo = dyn_cast<cir::GotoOp>(op)) {
2761 gotos.insert(goTo.getLabel());
2762 }
else if (
auto blkAdd = dyn_cast<cir::BlockAddressOp>(op)) {
2763 if (blkAdd.getBlockAddrInfoAttr().getFunc().getAttr() != getSymName()) {
2765 invalidBlockAddress =
true;
2766 return mlir::WalkResult::interrupt();
2768 blockAddresses.insert(blkAdd.getBlockAddrInfoAttr().getLabel());
2770 return mlir::WalkResult::advance();
2773 if (invalidBlockAddress)
2774 return emitOpError() <<
"blockaddress references a different function";
2776 llvm::SmallSet<llvm::StringRef, 16> mismatched;
2777 if (!labels.empty() || !gotos.empty()) {
2778 mismatched = llvm::set_difference(gotos, labels);
2780 if (!mismatched.empty())
2781 return emitOpError() <<
"goto/label mismatch";
2786 if (!labels.empty() || !blockAddresses.empty()) {
2787 mismatched = llvm::set_difference(blockAddresses, labels);
2789 if (!mismatched.empty())
2790 return emitOpError()
2791 <<
"expects an existing label target in the referenced function";
2803 bool noUnsignedWrap,
bool saturated,
2805 bool noWrap = noSignedWrap || noUnsignedWrap;
2806 if (!isa<cir::IntType>(op->getResultTypes()[0]) && noWrap)
2807 return op->emitError()
2808 <<
"only operations on integer values may have nsw/nuw flags";
2809 if (hasSat && saturated && !isa<cir::IntType>(op->getResultTypes()[0]))
2810 return op->emitError()
2811 <<
"only operations on integer values may have sat flag";
2812 if (hasSat && noWrap && saturated)
2813 return op->emitError()
2814 <<
"the nsw/nuw flags and the saturated flag are mutually exclusive";
2815 return mlir::success();
2818LogicalResult cir::AddOp::verify() {
2820 getNoUnsignedWrap(), getSaturated(),
2824LogicalResult cir::SubOp::verify() {
2826 getNoUnsignedWrap(), getSaturated(),
2830LogicalResult cir::MulOp::verify() {
2832 getNoUnsignedWrap(),
false,
2845void cir::TernaryOp::getSuccessorRegions(
2846 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
2848 if (!point.isParent()) {
2849 regions.push_back(RegionSuccessor::parent());
2855 regions.push_back(RegionSuccessor(&getTrueRegion()));
2856 regions.push_back(RegionSuccessor(&getFalseRegion()));
2859mlir::ValueRange cir::TernaryOp::getSuccessorInputs(RegionSuccessor successor) {
2860 return successor.isParent() ? ValueRange(getOperation()->getResults())
2864void cir::TernaryOp::build(
2865 OpBuilder &builder, OperationState &result,
Value cond,
2866 function_ref<
void(OpBuilder &, Location)> trueBuilder,
2867 function_ref<
void(OpBuilder &, Location)> falseBuilder) {
2868 result.addOperands(cond);
2869 OpBuilder::InsertionGuard guard(builder);
2870 Region *trueRegion = result.addRegion();
2871 builder.createBlock(trueRegion);
2872 trueBuilder(builder, result.location);
2873 Region *falseRegion = result.addRegion();
2874 builder.createBlock(falseRegion);
2875 falseBuilder(builder, result.location);
2880 if (trueRegion->back().mightHaveTerminator())
2881 yield = dyn_cast_or_null<cir::YieldOp>(trueRegion->back().getTerminator());
2882 if (!yield && falseRegion->back().mightHaveTerminator())
2883 yield = dyn_cast_or_null<cir::YieldOp>(falseRegion->back().getTerminator());
2885 assert((!yield || yield.getNumOperands() <= 1) &&
2886 "expected zero or one result type");
2887 if (yield && yield.getNumOperands() == 1)
2888 result.addTypes(TypeRange{yield.getOperandTypes().front()});
2895OpFoldResult cir::SelectOp::fold(FoldAdaptor adaptor) {
2896 mlir::Attribute
condition = adaptor.getCondition();
2898 bool conditionValue = mlir::cast<cir::BoolAttr>(
condition).getValue();
2899 return conditionValue ? getTrueValue() : getFalseValue();
2903 mlir::Attribute trueValue = adaptor.getTrueValue();
2904 mlir::Attribute falseValue = adaptor.getFalseValue();
2905 if (trueValue == falseValue)
2907 if (getTrueValue() == getFalseValue())
2908 return getTrueValue();
2913LogicalResult cir::SelectOp::verify() {
2915 auto condTy = dyn_cast<cir::VectorType>(getCondition().
getType());
2922 if (!isa<cir::VectorType>(getTrueValue().
getType()) ||
2923 !isa<cir::VectorType>(getFalseValue().
getType())) {
2924 return emitOpError()
2925 <<
"expected both true and false operands to be vector types "
2926 "when the condition is a vector boolean type";
2935LogicalResult cir::ShiftOp::verify() {
2936 mlir::Operation *op = getOperation();
2937 auto op0VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(0).getType());
2938 auto op1VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(1).getType());
2939 if (!op0VecTy ^ !op1VecTy)
2940 return emitOpError() <<
"input types cannot be one vector and one scalar";
2943 if (op0VecTy.getSize() != op1VecTy.getSize())
2944 return emitOpError() <<
"input vector types must have the same size";
2946 auto opResultTy = mlir::dyn_cast<cir::VectorType>(
getType());
2948 return emitOpError() <<
"the type of the result must be a vector "
2949 <<
"if it is vector shift";
2951 auto op0VecEleTy = mlir::cast<cir::IntType>(op0VecTy.getElementType());
2952 auto op1VecEleTy = mlir::cast<cir::IntType>(op1VecTy.getElementType());
2953 if (op0VecEleTy.getWidth() != op1VecEleTy.getWidth())
2954 return emitOpError()
2955 <<
"vector operands do not have the same elements sizes";
2957 auto resVecEleTy = mlir::cast<cir::IntType>(opResultTy.getElementType());
2958 if (op0VecEleTy.getWidth() != resVecEleTy.getWidth())
2959 return emitOpError() <<
"vector operands and result type do not have the "
2960 "same elements sizes";
2963 return mlir::success();
2970LogicalResult cir::LabelOp::verify() {
2971 mlir::Operation *op = getOperation();
2972 mlir::Block *blk = op->getBlock();
2973 if (&blk->front() != op)
2974 return emitError() <<
"must be the first operation in a block";
2976 return mlir::success();
2983OpFoldResult cir::IncOp::fold(FoldAdaptor adaptor) {
2984 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
2985 return adaptor.getInput();
2993OpFoldResult cir::DecOp::fold(FoldAdaptor adaptor) {
2994 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
2995 return adaptor.getInput();
3003OpFoldResult cir::MinusOp::fold(FoldAdaptor adaptor) {
3004 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3005 return adaptor.getInput();
3008 if (
auto srcConst = getInput().getDefiningOp<cir::ConstantOp>())
3009 if (mlir::isa<cir::BoolType>(srcConst.getType()))
3010 return srcConst.getResult();
3013 if (mlir::Attribute attr = adaptor.getInput()) {
3014 if (
auto intAttr = mlir::dyn_cast<cir::IntAttr>(attr)) {
3015 APInt val = intAttr.getValue();
3017 return cir::IntAttr::get(
getType(), val);
3019 if (
auto fpAttr = mlir::dyn_cast<cir::FPAttr>(attr)) {
3020 APFloat val = fpAttr.getValue();
3022 return cir::FPAttr::get(
getType(), val);
3033OpFoldResult cir::NotOp::fold(FoldAdaptor adaptor) {
3034 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3035 return adaptor.getInput();
3040 if (mlir::Attribute attr = adaptor.getInput()) {
3041 if (
auto intAttr = mlir::dyn_cast<cir::IntAttr>(attr)) {
3042 APInt val = intAttr.getValue();
3044 return cir::IntAttr::get(
getType(), val);
3046 if (
auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr))
3047 return cir::BoolAttr::get(getContext(), !boolAttr.getValue());
3058 mlir::Type resultTy) {
3061 mlir::Type inputMemberTy;
3062 mlir::Type resultMemberTy;
3063 if (mlir::isa<cir::DataMemberType>(src.getType())) {
3065 mlir::cast<cir::DataMemberType>(src.getType()).getMemberTy();
3066 resultMemberTy = mlir::cast<cir::DataMemberType>(resultTy).getMemberTy();
3069 if (inputMemberTy != resultMemberTy)
3070 return op->emitOpError()
3071 <<
"member types of the operand and the result do not match";
3073 return mlir::success();
3076LogicalResult cir::BaseDataMemberOp::verify() {
3080LogicalResult cir::DerivedDataMemberOp::verify() {
3088LogicalResult cir::BaseMethodOp::verify() {
3092LogicalResult cir::DerivedMethodOp::verify() {
3100void cir::AwaitOp::build(OpBuilder &builder, OperationState &result,
3104 result.addAttribute(getKindAttrName(result.name),
3105 cir::AwaitKindAttr::get(builder.getContext(),
kind));
3107 OpBuilder::InsertionGuard guard(builder);
3108 Region *readyRegion = result.addRegion();
3109 builder.createBlock(readyRegion);
3110 readyBuilder(builder, result.location);
3114 OpBuilder::InsertionGuard guard(builder);
3115 Region *suspendRegion = result.addRegion();
3116 builder.createBlock(suspendRegion);
3117 suspendBuilder(builder, result.location);
3121 OpBuilder::InsertionGuard guard(builder);
3122 Region *resumeRegion = result.addRegion();
3123 builder.createBlock(resumeRegion);
3124 resumeBuilder(builder, result.location);
3128void cir::AwaitOp::getSuccessorRegions(
3129 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
3132 if (!point.isParent()) {
3133 regions.push_back(RegionSuccessor::parent());
3140 regions.push_back(RegionSuccessor(&this->getReady()));
3141 regions.push_back(RegionSuccessor(&this->getSuspend()));
3142 regions.push_back(RegionSuccessor(&this->getResume()));
3145mlir::ValueRange cir::AwaitOp::getSuccessorInputs(RegionSuccessor successor) {
3146 if (successor.isParent())
3147 return getOperation()->getResults();
3148 if (successor == &getReady())
3149 return getReady().getArguments();
3150 if (successor == &getSuspend())
3151 return getSuspend().getArguments();
3152 if (successor == &getResume())
3153 return getResume().getArguments();
3154 llvm_unreachable(
"invalid region successor");
3157LogicalResult cir::AwaitOp::verify() {
3158 if (!isa<ConditionOp>(this->getReady().back().getTerminator()))
3159 return emitOpError(
"ready region must end with cir.condition");
3167void cir::CoroBodyOp::getSuccessorRegions(
3168 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
3169 if (!point.isParent()) {
3170 regions.push_back(RegionSuccessor::parent());
3174 regions.push_back(RegionSuccessor(&getBody()));
3178cir::CoroBodyOp::getSuccessorInputs(RegionSuccessor successor) {
3179 return ValueRange();
3182LogicalResult cir::CoroBodyOp::verify() {
3183 if (!getOperation()->getParentOfType<FuncOp>().getCoroutine())
3184 return emitOpError(
"enclosing function must be a coroutine");
3188void cir::CoroBodyOp::build(OpBuilder &builder, OperationState &result,
3190 assert(bodyBuilder &&
3191 "the builder callback for 'CoroBodyOp' must be present");
3192 OpBuilder::InsertionGuard guard(builder);
3194 Region *bodyRegion = result.addRegion();
3195 builder.createBlock(bodyRegion);
3196 bodyBuilder(builder, result.location);
3203LogicalResult cir::CopyOp::verify() {
3205 if (!
getType().getPointee().hasTrait<DataLayoutTypeInterface::Trait>())
3206 return emitError() <<
"missing data layout for pointee type";
3208 if (getSkipTailPadding() &&
3209 !mlir::isa<cir::RecordType>(
getType().getPointee()))
3211 <<
"skip_tail_padding is only valid for record pointee types";
3213 return mlir::success();
3220LogicalResult cir::GetRuntimeMemberOp::verify() {
3221 auto recordTy = mlir::cast<RecordType>(getAddr().
getType().getPointee());
3222 cir::DataMemberType memberPtrTy = getMember().getType();
3224 if (recordTy != memberPtrTy.getClassTy())
3225 return emitError() <<
"record type does not match the member pointer type";
3226 if (
getType().getPointee() != memberPtrTy.getMemberTy())
3227 return emitError() <<
"result type does not match the member pointer type";
3228 return mlir::success();
3235LogicalResult cir::GetMethodOp::verify() {
3236 cir::MethodType methodTy = getMethod().getType();
3239 cir::PointerType objectPtrTy = getObject().getType();
3240 mlir::Type objectTy = objectPtrTy.getPointee();
3242 if (methodTy.getClassTy() != objectTy)
3243 return emitError() <<
"method class type and object type do not match";
3246 auto calleeTy = mlir::cast<cir::FuncType>(getCallee().
getType().getPointee());
3247 cir::FuncType methodFuncTy = methodTy.getMemberFuncTy();
3254 if (methodFuncTy.getReturnType() != calleeTy.getReturnType())
3256 <<
"method return type and callee return type do not match";
3261 if (calleeArgsTy.empty())
3262 return emitError() <<
"callee parameter list lacks receiver object ptr";
3264 auto calleeThisArgPtrTy = mlir::dyn_cast<cir::PointerType>(calleeArgsTy[0]);
3265 if (!calleeThisArgPtrTy ||
3266 !mlir::isa<cir::VoidType>(calleeThisArgPtrTy.getPointee())) {
3268 <<
"the first parameter of callee must be a void pointer";
3271 if (calleeArgsTy.size() != methodFuncArgsTy.size())
3272 return emitError() <<
"callee and method parameter counts do not match";
3274 if (calleeArgsTy.size() > 1 &&
3275 calleeArgsTy.slice(1) != methodFuncArgsTy.slice(1))
3277 <<
"callee parameters and method parameters do not match";
3279 return mlir::success();
3286LogicalResult cir::GetMemberOp::verify() {
3287 const auto recordTy = dyn_cast<RecordType>(getAddrTy().getPointee());
3289 return emitError() <<
"expected pointer to a record type";
3291 if (recordTy.getMembers().size() <=
getIndex())
3292 return emitError() <<
"member index out of bounds";
3295 return emitError() <<
"member type mismatch";
3297 return mlir::success();
3304LogicalResult cir::ExtractMemberOp::verify() {
3305 auto recordTy = mlir::cast<cir::RecordType>(getRecord().
getType());
3306 if (recordTy.getKind() == cir::RecordType::Union)
3308 <<
"cir.extract_member currently does not support unions";
3309 if (recordTy.getMembers().size() <=
getIndex())
3310 return emitError() <<
"member index out of bounds";
3312 return emitError() <<
"member type mismatch";
3313 return mlir::success();
3320LogicalResult cir::InsertMemberOp::verify() {
3321 auto recordTy = mlir::cast<cir::RecordType>(getRecord().
getType());
3322 if (recordTy.getKind() == cir::RecordType::Union)
3323 return emitError() <<
"cir.insert_member currently does not support unions";
3324 if (recordTy.getMembers().size() <=
getIndex())
3325 return emitError() <<
"member index out of bounds";
3327 return emitError() <<
"member type mismatch";
3329 return mlir::success();
3336OpFoldResult cir::VecCreateOp::fold(FoldAdaptor adaptor) {
3337 if (llvm::any_of(getElements(), [](mlir::Value value) {
3338 return !value.getDefiningOp<cir::ConstantOp>();
3342 return cir::ConstVectorAttr::get(
3343 getType(), mlir::ArrayAttr::get(getContext(), adaptor.getElements()));
3346LogicalResult cir::VecCreateOp::verify() {
3350 const cir::VectorType vecTy =
getType();
3351 if (getElements().size() != vecTy.getSize()) {
3352 return emitOpError() <<
"operand count of " << getElements().size()
3353 <<
" doesn't match vector type " << vecTy
3354 <<
" element count of " << vecTy.getSize();
3357 const mlir::Type elementType = vecTy.getElementType();
3358 for (
const mlir::Value element : getElements()) {
3359 if (element.getType() != elementType) {
3360 return emitOpError() <<
"operand type " << element.getType()
3361 <<
" doesn't match vector element type "
3373OpFoldResult cir::VecExtractOp::fold(FoldAdaptor adaptor) {
3374 const auto vectorAttr =
3375 llvm::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec());
3379 const auto indexAttr =
3380 llvm::dyn_cast_if_present<cir::IntAttr>(adaptor.getIndex());
3384 const mlir::ArrayAttr elements = vectorAttr.getElts();
3385 const uint64_t index = indexAttr.getUInt();
3386 if (index >= elements.size())
3389 return elements[index];
3396OpFoldResult cir::VecCmpOp::fold(FoldAdaptor adaptor) {
3398 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getLhs());
3400 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getRhs());
3401 if (!lhsVecAttr || !rhsVecAttr)
3404 mlir::Type inputElemTy =
3405 mlir::cast<cir::VectorType>(lhsVecAttr.getType()).getElementType();
3406 if (!isAnyIntegerOrFloatingPointType(inputElemTy))
3409 cir::CmpOpKind opKind = adaptor.getKind();
3410 mlir::ArrayAttr lhsVecElhs = lhsVecAttr.getElts();
3411 mlir::ArrayAttr rhsVecElhs = rhsVecAttr.getElts();
3412 uint64_t vecSize = lhsVecElhs.size();
3415 bool isIntAttr = vecSize && mlir::isa<cir::IntAttr>(lhsVecElhs[0]);
3416 for (uint64_t i = 0; i < vecSize; i++) {
3417 mlir::Attribute lhsAttr = lhsVecElhs[i];
3418 mlir::Attribute rhsAttr = rhsVecElhs[i];
3421 case cir::CmpOpKind::lt: {
3423 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <
3424 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3426 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <
3427 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3431 case cir::CmpOpKind::le: {
3433 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <=
3434 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3436 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <=
3437 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3441 case cir::CmpOpKind::gt: {
3443 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >
3444 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3446 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >
3447 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3451 case cir::CmpOpKind::ge: {
3453 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >=
3454 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3456 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >=
3457 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3461 case cir::CmpOpKind::eq: {
3463 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() ==
3464 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3466 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() ==
3467 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3471 case cir::CmpOpKind::ne: {
3473 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() !=
3474 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3476 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() !=
3477 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3481 case cir::CmpOpKind::one: {
3482 llvm::APFloat::cmpResult cr =
3483 mlir::cast<cir::FPAttr>(lhsAttr).getValue().compare(
3484 mlir::cast<cir::FPAttr>(rhsAttr).getValue());
3486 cr != llvm::APFloat::cmpUnordered && cr != llvm::APFloat::cmpEqual;
3489 case cir::CmpOpKind::uno: {
3490 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue().compare(
3491 mlir::cast<cir::FPAttr>(rhsAttr).getValue()) ==
3492 llvm::APFloat::cmpUnordered;
3497 elements[i] = cir::IntAttr::get(
getType().getElementType(), cmpResult);
3500 return cir::ConstVectorAttr::get(
3501 getType(), mlir::ArrayAttr::get(getContext(), elements));
3508OpFoldResult cir::VecShuffleOp::fold(FoldAdaptor adaptor) {
3510 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec1());
3512 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec2());
3513 if (!vec1Attr || !vec2Attr)
3516 mlir::Type vec1ElemTy =
3517 mlir::cast<cir::VectorType>(vec1Attr.getType()).getElementType();
3519 mlir::ArrayAttr vec1Elts = vec1Attr.getElts();
3520 mlir::ArrayAttr vec2Elts = vec2Attr.getElts();
3521 mlir::ArrayAttr indicesElts = adaptor.getIndices();
3524 elements.reserve(indicesElts.size());
3526 uint64_t vec1Size = vec1Elts.size();
3527 for (
const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
3528 if (idxAttr.getSInt() == -1) {
3529 elements.push_back(cir::UndefAttr::get(vec1ElemTy));
3533 uint64_t idxValue = idxAttr.getUInt();
3534 elements.push_back(idxValue < vec1Size ? vec1Elts[idxValue]
3535 : vec2Elts[idxValue - vec1Size]);
3538 return cir::ConstVectorAttr::get(
3539 getType(), mlir::ArrayAttr::get(getContext(), elements));
3542LogicalResult cir::VecShuffleOp::verify() {
3545 if (getIndices().size() != getResult().
getType().getSize()) {
3546 return emitOpError() <<
": the number of elements in " << getIndices()
3547 <<
" and " << getResult().getType() <<
" don't match";
3552 if (getVec1().
getType().getElementType() !=
3553 getResult().
getType().getElementType()) {
3554 return emitOpError() <<
": element types of " << getVec1().getType()
3555 <<
" and " << getResult().getType() <<
" don't match";
3558 const uint64_t maxValidIndex =
3559 getVec1().getType().getSize() + getVec2().getType().getSize() - 1;
3561 getIndices().getAsRange<cir::IntAttr>(), [&](cir::IntAttr idxAttr) {
3562 return idxAttr.getSInt() != -1 && idxAttr.getUInt() > maxValidIndex;
3564 return emitOpError() <<
": index for __builtin_shufflevector must be "
3565 "less than the total number of vector elements";
3574OpFoldResult cir::VecShuffleDynamicOp::fold(FoldAdaptor adaptor) {
3575 mlir::Attribute vec = adaptor.getVec();
3576 mlir::Attribute indices = adaptor.getIndices();
3577 if (mlir::isa_and_nonnull<cir::ConstVectorAttr>(vec) &&
3578 mlir::isa_and_nonnull<cir::ConstVectorAttr>(indices)) {
3579 auto vecAttr = mlir::cast<cir::ConstVectorAttr>(vec);
3580 auto indicesAttr = mlir::cast<cir::ConstVectorAttr>(indices);
3582 mlir::ArrayAttr vecElts = vecAttr.getElts();
3583 mlir::ArrayAttr indicesElts = indicesAttr.getElts();
3585 const uint64_t numElements = vecElts.size();
3588 elements.reserve(numElements);
3590 const uint64_t maskBits = llvm::NextPowerOf2(numElements - 1) - 1;
3591 for (
const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
3592 uint64_t idxValue = idxAttr.getUInt();
3593 uint64_t newIdx = idxValue & maskBits;
3594 elements.push_back(vecElts[newIdx]);
3597 return cir::ConstVectorAttr::get(
3598 getType(), mlir::ArrayAttr::get(getContext(), elements));
3604LogicalResult cir::VecShuffleDynamicOp::verify() {
3606 if (getVec().
getType().getSize() !=
3607 mlir::cast<cir::VectorType>(getIndices().
getType()).getSize()) {
3608 return emitOpError() <<
": the number of elements in " << getVec().getType()
3609 <<
" and " << getIndices().getType() <<
" don't match";
3618LogicalResult cir::VecTernaryOp::verify() {
3623 if (getCond().
getType().getSize() != getLhs().
getType().getSize()) {
3624 return emitOpError() <<
": the number of elements in "
3625 << getCond().getType() <<
" and " << getLhs().getType()
3631OpFoldResult cir::VecTernaryOp::fold(FoldAdaptor adaptor) {
3632 mlir::Attribute cond = adaptor.getCond();
3633 mlir::Attribute lhs = adaptor.getLhs();
3634 mlir::Attribute rhs = adaptor.getRhs();
3636 if (!mlir::isa_and_nonnull<cir::ConstVectorAttr>(cond) ||
3637 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(lhs) ||
3638 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(rhs))
3640 auto condVec = mlir::cast<cir::ConstVectorAttr>(cond);
3641 auto lhsVec = mlir::cast<cir::ConstVectorAttr>(lhs);
3642 auto rhsVec = mlir::cast<cir::ConstVectorAttr>(rhs);
3644 mlir::ArrayAttr condElts = condVec.getElts();
3647 elements.reserve(condElts.size());
3649 for (
const auto &[idx, condAttr] :
3650 llvm::enumerate(condElts.getAsRange<cir::IntAttr>())) {
3651 if (condAttr.getSInt()) {
3652 elements.push_back(lhsVec.getElts()[idx]);
3654 elements.push_back(rhsVec.getElts()[idx]);
3658 cir::VectorType vecTy = getLhs().getType();
3659 return cir::ConstVectorAttr::get(
3660 vecTy, mlir::ArrayAttr::get(getContext(), elements));
3667LogicalResult cir::ComplexCreateOp::verify() {
3670 <<
"operand type of cir.complex.create does not match its result type";
3677OpFoldResult cir::ComplexCreateOp::fold(FoldAdaptor adaptor) {
3678 mlir::Attribute real = adaptor.getReal();
3679 mlir::Attribute imag = adaptor.getImag();
3685 auto realAttr = mlir::cast<mlir::TypedAttr>(real);
3686 auto imagAttr = mlir::cast<mlir::TypedAttr>(imag);
3687 return cir::ConstComplexAttr::get(realAttr, imagAttr);
3694LogicalResult cir::ComplexRealOp::verify() {
3695 mlir::Type operandTy = getOperand().getType();
3696 if (
auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
3697 operandTy = complexOperandTy.getElementType();
3700 emitOpError() <<
": result type does not match operand type";
3707OpFoldResult cir::ComplexRealOp::fold(FoldAdaptor adaptor) {
3708 if (!mlir::isa<cir::ComplexType>(getOperand().
getType()))
3711 if (
auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
3712 return complexCreateOp.getOperand(0);
3715 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
3716 return complex ? complex.getReal() :
nullptr;
3723LogicalResult cir::ComplexImagOp::verify() {
3724 mlir::Type operandTy = getOperand().getType();
3725 if (
auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
3726 operandTy = complexOperandTy.getElementType();
3729 emitOpError() <<
": result type does not match operand type";
3736OpFoldResult cir::ComplexImagOp::fold(FoldAdaptor adaptor) {
3737 if (!mlir::isa<cir::ComplexType>(getOperand().
getType()))
3740 if (
auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
3741 return complexCreateOp.getOperand(1);
3744 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
3745 return complex ? complex.getImag() :
nullptr;
3752LogicalResult cir::ComplexRealPtrOp::verify() {
3753 mlir::Type resultPointeeTy =
getType().getPointee();
3754 cir::PointerType operandPtrTy = getOperand().getType();
3755 auto operandPointeeTy =
3756 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
3758 if (resultPointeeTy != operandPointeeTy.getElementType()) {
3759 return emitOpError() <<
": result type does not match operand type";
3769LogicalResult cir::ComplexImagPtrOp::verify() {
3770 mlir::Type resultPointeeTy =
getType().getPointee();
3771 cir::PointerType operandPtrTy = getOperand().getType();
3772 auto operandPointeeTy =
3773 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
3775 if (resultPointeeTy != operandPointeeTy.getElementType()) {
3776 return emitOpError()
3777 <<
"cir.complex.imag_ptr result type does not match operand type";
3788 llvm::function_ref<llvm::APInt(
const llvm::APInt &)> func,
3789 bool poisonZero =
false) {
3790 if (mlir::isa_and_present<cir::PoisonAttr>(inputAttr)) {
3795 auto input = mlir::dyn_cast_if_present<IntAttr>(inputAttr);
3799 llvm::APInt inputValue = input.getValue();
3800 if (poisonZero && inputValue.isZero())
3801 return cir::PoisonAttr::get(input.getType());
3803 llvm::APInt resultValue = func(inputValue);
3804 return IntAttr::get(input.getType(), resultValue);
3807OpFoldResult BitClrsbOp::fold(FoldAdaptor adaptor) {
3808 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3809 unsigned resultValue =
3810 inputValue.getBitWidth() - inputValue.getSignificantBits();
3811 return llvm::APInt(inputValue.getBitWidth(), resultValue);
3815OpFoldResult BitClzOp::fold(FoldAdaptor adaptor) {
3818 [](
const llvm::APInt &inputValue) {
3819 unsigned resultValue = inputValue.countLeadingZeros();
3820 return llvm::APInt(inputValue.getBitWidth(), resultValue);
3825OpFoldResult BitCtzOp::fold(FoldAdaptor adaptor) {
3828 [](
const llvm::APInt &inputValue) {
3829 return llvm::APInt(inputValue.getBitWidth(),
3830 inputValue.countTrailingZeros());
3835OpFoldResult BitFfsOp::fold(FoldAdaptor adaptor) {
3836 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3837 unsigned trailingZeros = inputValue.countTrailingZeros();
3839 trailingZeros == inputValue.getBitWidth() ? 0 : trailingZeros + 1;
3840 return llvm::APInt(inputValue.getBitWidth(), result);
3844OpFoldResult BitParityOp::fold(FoldAdaptor adaptor) {
3845 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3846 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount() % 2);
3850OpFoldResult BitPopcountOp::fold(FoldAdaptor adaptor) {
3851 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3852 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount());
3856OpFoldResult BitReverseOp::fold(FoldAdaptor adaptor) {
3857 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3858 return inputValue.reverseBits();
3862OpFoldResult ByteSwapOp::fold(FoldAdaptor adaptor) {
3863 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3864 return inputValue.byteSwap();
3868OpFoldResult RotateOp::fold(FoldAdaptor adaptor) {
3869 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()) ||
3870 mlir::isa_and_present<cir::PoisonAttr>(adaptor.getAmount())) {
3872 return cir::PoisonAttr::get(
getType());
3875 auto input = mlir::dyn_cast_if_present<IntAttr>(adaptor.getInput());
3876 auto amount = mlir::dyn_cast_if_present<IntAttr>(adaptor.getAmount());
3877 if (!input && !amount)
3886 llvm::APInt inputValue;
3888 inputValue = input.getValue();
3889 if (inputValue.isZero() || inputValue.isAllOnes()) {
3895 uint64_t amountValue;
3897 amountValue = amount.getValue().urem(getInput().
getType().getWidth());
3898 if (amountValue == 0) {
3904 if (!input || !amount)
3907 assert(inputValue.getBitWidth() == getInput().
getType().getWidth() &&
3908 "input value must have the same bit width as the input type");
3910 llvm::APInt resultValue;
3912 resultValue = inputValue.rotl(amountValue);
3914 resultValue = inputValue.rotr(amountValue);
3916 return IntAttr::get(input.getContext(), input.getType(), resultValue);
3923void cir::InlineAsmOp::print(OpAsmPrinter &p) {
3924 p <<
'(' << getAsmFlavor() <<
", ";
3929 auto *nameIt = names.begin();
3930 auto *attrIt = getOperandAttrs().begin();
3932 for (mlir::OperandRange ops : getAsmOperands()) {
3933 p << *nameIt <<
" = ";
3936 llvm::interleaveComma(llvm::make_range(ops.begin(), ops.end()), p,
3938 p.printOperand(value);
3939 p <<
" : " << value.getType();
3940 if (mlir::isa<mlir::UnitAttr>(*attrIt))
3941 p <<
" (maybe_memory)";
3950 p.printString(getAsmString());
3952 p.printString(getConstraints());
3956 if (getSideEffects())
3957 p <<
" side_effects";
3959 std::array elidedAttrs{
3960 llvm::StringRef(
"asm_flavor"), llvm::StringRef(
"asm_string"),
3961 llvm::StringRef(
"constraints"), llvm::StringRef(
"operand_attrs"),
3962 llvm::StringRef(
"operands_segments"), llvm::StringRef(
"side_effects")};
3963 p.printOptionalAttrDict(getOperation()->getAttrs(), elidedAttrs);
3965 if (
auto v = getRes())
3966 p <<
" -> " << v.getType();
3969void cir::InlineAsmOp::build(OpBuilder &odsBuilder, OperationState &odsState,
3971 StringRef asmString, StringRef constraints,
3972 bool sideEffects, cir::AsmFlavor asmFlavor,
3976 for (
auto operandRange : asmOperands) {
3977 segments.push_back(operandRange.size());
3978 odsState.addOperands(operandRange);
3981 odsState.addAttribute(
3982 "operands_segments",
3983 DenseI32ArrayAttr::get(odsBuilder.getContext(), segments));
3984 odsState.addAttribute(
"asm_string", odsBuilder.getStringAttr(asmString));
3985 odsState.addAttribute(
"constraints", odsBuilder.getStringAttr(constraints));
3986 odsState.addAttribute(
"asm_flavor",
3987 AsmFlavorAttr::get(odsBuilder.getContext(), asmFlavor));
3990 odsState.addAttribute(
"side_effects", odsBuilder.getUnitAttr());
3992 odsState.addAttribute(
"operand_attrs", odsBuilder.getArrayAttr(operandAttrs));
3995ParseResult cir::InlineAsmOp::parse(OpAsmParser &parser,
3996 OperationState &result) {
3999 std::string asmString, constraints;
4001 MLIRContext *ctxt = parser.getBuilder().getContext();
4003 auto error = [&](
const Twine &msg) -> LogicalResult {
4004 return parser.emitError(parser.getCurrentLocation(), msg);
4007 auto expected = [&](
const std::string &
c) {
4008 return error(
"expected '" +
c +
"'");
4011 if (parser.parseLParen().failed())
4012 return expected(
"(");
4014 auto flavor = FieldParser<AsmFlavor, AsmFlavor>::parse(parser);
4016 return error(
"Unknown AsmFlavor");
4018 if (parser.parseComma().failed())
4019 return expected(
",");
4021 auto parseValue = [&](
Value &v) {
4022 OpAsmParser::UnresolvedOperand op;
4024 if (parser.parseOperand(op) || parser.parseColon())
4025 return error(
"can't parse operand");
4028 if (parser.parseType(typ).failed())
4029 return error(
"can't parse operand type");
4031 if (parser.resolveOperand(op, typ, tmp))
4032 return error(
"can't resolve operand");
4034 return mlir::success();
4037 auto parseOperands = [&](llvm::StringRef
name) {
4038 if (parser.parseKeyword(name).failed())
4039 return error(
"expected " + name +
" operands here");
4040 if (parser.parseEqual().failed())
4041 return expected(
"=");
4042 if (parser.parseLSquare().failed())
4043 return expected(
"[");
4046 if (parser.parseOptionalRSquare().succeeded()) {
4047 operandsGroupSizes.push_back(size);
4048 if (parser.parseComma())
4049 return expected(
",");
4050 return mlir::success();
4053 auto parseOperand = [&]() {
4055 if (parseValue(val).succeeded()) {
4056 result.operands.push_back(val);
4059 if (parser.parseOptionalLParen().failed()) {
4060 operandAttrs.push_back(mlir::DictionaryAttr::get(ctxt));
4061 return mlir::success();
4064 if (parser.parseKeyword(
"maybe_memory").succeeded()) {
4065 operandAttrs.push_back(mlir::UnitAttr::get(ctxt));
4066 if (parser.parseRParen())
4067 return expected(
")");
4068 return mlir::success();
4070 return expected(
"maybe_memory");
4073 return mlir::failure();
4076 if (parser.parseCommaSeparatedList(parseOperand).failed())
4077 return mlir::failure();
4079 if (parser.parseRSquare().failed() || parser.parseComma().failed())
4080 return expected(
"]");
4081 operandsGroupSizes.push_back(size);
4082 return mlir::success();
4085 if (parseOperands(
"out").failed() || parseOperands(
"in").failed() ||
4086 parseOperands(
"in_out").failed())
4087 return error(
"failed to parse operands");
4089 if (parser.parseLBrace())
4090 return expected(
"{");
4091 if (parser.parseString(&asmString))
4092 return error(
"asm string parsing failed");
4093 if (parser.parseString(&constraints))
4094 return error(
"constraints string parsing failed");
4095 if (parser.parseRBrace())
4096 return expected(
"}");
4097 if (parser.parseRParen())
4098 return expected(
")");
4100 if (parser.parseOptionalKeyword(
"side_effects").succeeded())
4101 result.attributes.set(
"side_effects", UnitAttr::get(ctxt));
4103 if (parser.parseOptionalAttrDict(result.attributes).failed())
4104 return mlir::failure();
4106 if (parser.parseOptionalArrow().succeeded() &&
4107 parser.parseType(resType).failed())
4108 return mlir::failure();
4110 result.attributes.set(
"asm_flavor", AsmFlavorAttr::get(ctxt, *flavor));
4111 result.attributes.set(
"asm_string", StringAttr::get(ctxt, asmString));
4112 result.attributes.set(
"constraints", StringAttr::get(ctxt, constraints));
4113 result.attributes.set(
"operand_attrs", ArrayAttr::get(ctxt, operandAttrs));
4114 result.getOrAddProperties<InlineAsmOp::Properties>().operands_segments =
4115 parser.getBuilder().getDenseI32ArrayAttr(operandsGroupSizes);
4117 result.addTypes(TypeRange{resType});
4119 return mlir::success();
4126template <
typename ThrowOpTy>
4129 return mlir::success();
4131 if (op.getNumOperands() != 0) {
4132 if (op.getTypeInfo())
4133 return mlir::success();
4134 return op.emitOpError() <<
"'type_info' symbol attribute missing";
4137 return mlir::failure();
4142mlir::LogicalResult cir::TryThrowOp::verify() {
4150LogicalResult cir::AtomicFetchOp::verify() {
4151 if (getBinop() != cir::AtomicFetchKind::Add &&
4152 getBinop() != cir::AtomicFetchKind::Sub &&
4153 getBinop() != cir::AtomicFetchKind::Max &&
4154 getBinop() != cir::AtomicFetchKind::Min &&
4155 !mlir::isa<cir::IntType>(getVal().
getType()))
4156 return emitError(
"only atomic add, sub, max, and min operation could "
4157 "operate on floating-point values");
4165LogicalResult cir::TypeInfoAttr::verify(
4166 ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError,
4167 ::mlir::Type type, ::mlir::ArrayAttr typeInfoData) {
4169 if (cir::ConstRecordAttr::verify(emitError, type, typeInfoData).failed())
4179void cir::TryOp::getSuccessorRegions(
4180 mlir::RegionBranchPoint point,
4183 if (!point.isParent()) {
4184 regions.push_back(RegionSuccessor::parent());
4188 regions.push_back(mlir::RegionSuccessor(&getTryRegion()));
4192 for (mlir::Region &handlerRegion : this->getHandlerRegions())
4193 regions.push_back(mlir::RegionSuccessor(&handlerRegion));
4196mlir::ValueRange cir::TryOp::getSuccessorInputs(RegionSuccessor successor) {
4197 return successor.isParent() ? ValueRange(getOperation()->getResults())
4201LogicalResult cir::TryOp::verify() {
4202 mlir::ArrayAttr handlerTypes = getHandlerTypes();
4203 if (!handlerTypes) {
4204 if (!getHandlerRegions().empty())
4206 "handler regions must be empty when no handler types are present");
4210 mlir::MutableArrayRef<mlir::Region> handlerRegions = getHandlerRegions();
4214 if (handlerRegions.size() != handlerTypes.size())
4216 "number of handler regions and handler types must match");
4218 for (
const auto &[typeAttr, handlerRegion] :
4219 llvm::zip(handlerTypes, handlerRegions)) {
4221 mlir::Block &entryBlock = handlerRegion.front();
4222 if (entryBlock.getNumArguments() != 1 ||
4223 !mlir::isa<cir::EhTokenType>(entryBlock.getArgument(0).getType()))
4225 "handler region must have a single '!cir.eh_token' argument");
4228 if (mlir::isa<cir::UnwindAttr>(typeAttr))
4234 if (entryBlock.empty())
4235 return emitOpError(
"catch handler region must not be empty");
4236 mlir::Operation *firstOp = &entryBlock.front();
4237 if (mlir::isa_and_present<cir::ConstructCatchParamOp>(firstOp))
4238 firstOp = firstOp->getNextNode();
4239 if (!firstOp || !mlir::isa<cir::BeginCatchOp>(firstOp))
4241 "catch handler region must start with 'cir.begin_catch'");
4249 mlir::MutableArrayRef<mlir::Region> handlerRegions,
4250 mlir::ArrayAttr handlerTypes) {
4254 for (
const auto [typeIdx, typeAttr] : llvm::enumerate(handlerTypes)) {
4258 if (mlir::isa<cir::CatchAllAttr>(typeAttr)) {
4259 printer <<
"catch all ";
4260 }
else if (mlir::isa<cir::UnwindAttr>(typeAttr)) {
4261 printer <<
"unwind ";
4263 printer <<
"catch [type ";
4264 printer.printAttribute(typeAttr);
4269 mlir::Region ®ion = handlerRegions[typeIdx];
4270 if (!region.empty() && region.front().getNumArguments() > 0) {
4272 printer.printRegionArgument(region.front().getArgument(0));
4276 printer.printRegion(region,
4283 mlir::OpAsmParser &parser,
4285 mlir::ArrayAttr &handlerTypes) {
4287 auto parseCheckedCatcherRegion = [&]() -> mlir::ParseResult {
4288 handlerRegions.emplace_back(
new mlir::Region);
4290 mlir::Region &currRegion = *handlerRegions.back();
4294 if (parser.parseLParen())
4296 mlir::OpAsmParser::Argument arg;
4297 if (parser.parseArgument(arg,
true))
4299 regionArgs.push_back(arg);
4300 if (parser.parseRParen())
4303 mlir::SMLoc regionLoc = parser.getCurrentLocation();
4304 if (parser.parseRegion(currRegion, regionArgs)) {
4305 handlerRegions.clear();
4309 if (currRegion.empty())
4310 return parser.emitError(regionLoc,
"handler region shall not be empty");
4312 if (!(currRegion.back().mightHaveTerminator() &&
4313 currRegion.back().getTerminator()))
4314 return parser.emitError(
4315 regionLoc,
"blocks are expected to be explicitly terminated");
4320 bool hasCatchAll =
false;
4322 while (parser.parseOptionalKeyword(
"catch").succeeded()) {
4323 bool hasLSquare = parser.parseOptionalLSquare().succeeded();
4325 llvm::StringRef attrStr;
4326 if (parser.parseOptionalKeyword(&attrStr, {
"all",
"type"}).failed())
4327 return parser.emitError(parser.getCurrentLocation(),
4328 "expected 'all' or 'type' keyword");
4330 bool isCatchAll = attrStr ==
"all";
4333 return parser.emitError(parser.getCurrentLocation(),
4334 "can't have more than one catch all");
4338 mlir::Attribute exceptionRTTIAttr;
4339 if (!isCatchAll && parser.parseAttribute(exceptionRTTIAttr).failed())
4340 return parser.emitError(parser.getCurrentLocation(),
4341 "expected valid RTTI info attribute");
4343 catcherAttrs.push_back(isCatchAll
4344 ? cir::CatchAllAttr::get(parser.getContext())
4345 : exceptionRTTIAttr);
4347 if (hasLSquare && isCatchAll)
4348 return parser.emitError(parser.getCurrentLocation(),
4349 "catch all dosen't need RTTI info attribute");
4351 if (hasLSquare && parser.parseRSquare().failed())
4352 return parser.emitError(parser.getCurrentLocation(),
4353 "expected `]` after RTTI info attribute");
4355 if (parseCheckedCatcherRegion().failed())
4356 return mlir::failure();
4359 if (parser.parseOptionalKeyword(
"unwind").succeeded()) {
4361 return parser.emitError(parser.getCurrentLocation(),
4362 "unwind can't be used with catch all");
4364 catcherAttrs.push_back(cir::UnwindAttr::get(parser.getContext()));
4365 if (parseCheckedCatcherRegion().failed())
4366 return mlir::failure();
4369 handlerTypes = parser.getBuilder().getArrayAttr(catcherAttrs);
4370 return mlir::success();
4378cir::EhTypeIdOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
4379 Operation *op = symbolTable.lookupNearestSymbolFrom(*
this, getTypeSymAttr());
4380 if (!isa_and_nonnull<GlobalOp>(op))
4381 return emitOpError(
"'")
4382 << getTypeSym() <<
"' does not reference a valid cir.global";
4390LogicalResult cir::ConstructCatchParamOp::verifySymbolUses(
4391 SymbolTableCollection &symbolTable) {
4392 auto copyFnAttr = getCopyFnAttr();
4396 symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(*
this, getCopyFnAttr());
4398 return emitOpError(
"'")
4399 << *getCopyFn() <<
"' does not reference a valid cir.func";
4401 if (!fn->hasAttr(cir::CIRDialect::getCatchCopyThunkAttrName()))
4402 return emitOpError(
"catch-init copy_fn must be tagged with the ")
4403 << cir::CIRDialect::getCatchCopyThunkAttrName() <<
" attribute";
4405 cir::FuncType fnType = fn.getFunctionType();
4406 if (fnType.getNumInputs() != 2 || !fnType.hasVoidReturn())
4407 return emitOpError(
"catch-init copy_fn must take two pointer arguments and "
4410 if (fnType.getInput(0) != getParamAddr().
getType())
4411 return emitOpError(
"first argument of catch-init copy_fn must match the "
4412 "type of 'param_addr'");
4414 if (fnType.getInput(1) != getParamAddr().
getType())
4416 "second argument of catch-init copy_fn must be a pointer "
4417 "to the catch type");
4428 SmallVectorImpl<Block *> &catchDestinations,
4429 Block *&defaultDestination,
4430 mlir::UnitAttr &defaultIsCatchAll) {
4432 if (parser.parseLSquare())
4436 bool hasCatchAll =
false;
4437 bool hasUnwind =
false;
4440 auto parseHandler = [&]() -> ParseResult {
4442 if (succeeded(parser.parseOptionalKeyword(
"catch_all"))) {
4444 return parser.emitError(parser.getCurrentLocation(),
4445 "duplicate 'catch_all' handler");
4447 return parser.emitError(parser.getCurrentLocation(),
4448 "cannot have both 'catch_all' and 'unwind'");
4451 if (parser.parseColon().failed())
4454 if (parser.parseSuccessor(defaultDestination).failed())
4460 if (succeeded(parser.parseOptionalKeyword(
"unwind"))) {
4462 return parser.emitError(parser.getCurrentLocation(),
4463 "duplicate 'unwind' handler");
4465 return parser.emitError(parser.getCurrentLocation(),
4466 "cannot have both 'catch_all' and 'unwind'");
4469 if (parser.parseColon().failed())
4472 if (parser.parseSuccessor(defaultDestination).failed())
4480 if (parser.parseKeyword(
"catch").failed())
4483 if (parser.parseLParen().failed())
4486 mlir::Attribute catchTypeAttr;
4487 if (parser.parseAttribute(catchTypeAttr).failed())
4489 handlerTypes.push_back(catchTypeAttr);
4491 if (parser.parseRParen().failed())
4494 if (parser.parseColon().failed())
4498 if (parser.parseSuccessor(dest).failed())
4500 catchDestinations.push_back(dest);
4504 if (parser.parseCommaSeparatedList(parseHandler).failed())
4507 if (parser.parseRSquare().failed())
4511 if (!hasCatchAll && !hasUnwind)
4512 return parser.emitError(parser.getCurrentLocation(),
4513 "must have either 'catch_all' or 'unwind' handler");
4516 if (!handlerTypes.empty())
4517 catchTypes = parser.getBuilder().getArrayAttr(handlerTypes);
4520 defaultIsCatchAll = parser.getBuilder().getUnitAttr();
4526 mlir::ArrayAttr catchTypes,
4527 SuccessorRange catchDestinations,
4528 Block *defaultDestination,
4529 mlir::UnitAttr defaultIsCatchAll) {
4537 llvm::zip(catchTypes, catchDestinations),
4540 p.printAttribute(std::get<0>(i));
4542 p.printSuccessor(std::get<1>(i));
4554 if (defaultIsCatchAll)
4555 p <<
" catch_all : ";
4558 p.printSuccessor(defaultDestination);
4568#define GET_OP_CLASSES
4569#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 parseAssumeBundle(OpAsmParser &p, cir::AssumeBundleKindAttr &bundleKindAttr, llvm::SmallVector< mlir::OpAsmParser::UnresolvedOperand, 4 > &bundleArgs, llvm::SmallVector< mlir::Type, 1 > &bundleArgTypes)
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)
static void printAssumeBundle(OpAsmPrinter &p, cir::AssumeOp op, cir::AssumeBundleKindAttr kindAttr, OperandRange bundleArgs, TypeRange bundleArgTypes)
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 mlir::LogicalResult verifyThrowOpImpl(ThrowOpTy 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()