19#include "mlir/IR/Attributes.h"
20#include "mlir/IR/BuiltinOps.h"
21#include "mlir/IR/BuiltinTypes.h"
22#include "mlir/IR/DialectImplementation.h"
23#include "mlir/IR/PatternMatch.h"
24#include "mlir/IR/Value.h"
25#include "mlir/Interfaces/ControlFlowInterfaces.h"
26#include "mlir/Interfaces/FunctionImplementation.h"
27#include "mlir/Support/LLVM.h"
29#include "clang/CIR/Dialect/IR/CIROpsDialect.cpp.inc"
30#include "clang/CIR/Dialect/IR/CIROpsEnums.cpp.inc"
32#include "llvm/ADT/SetOperations.h"
33#include "llvm/ADT/SmallSet.h"
34#include "llvm/ADT/TypeSwitch.h"
35#include "llvm/Support/LogicalResult.h"
44struct CIROpAsmDialectInterface :
public OpAsmDialectInterface {
45 using OpAsmDialectInterface::OpAsmDialectInterface;
47 AliasResult getAlias(Type type, raw_ostream &os)
const final {
48 if (
auto recordType = dyn_cast<cir::RecordType>(type)) {
51 os <<
"rec_anon_" <<
recordType.getKindAsStr();
53 os <<
"rec_" << nameAttr.getValue();
54 return AliasResult::OverridableAlias;
56 if (
auto intType = dyn_cast<cir::IntType>(type)) {
59 unsigned width = intType.getWidth();
60 if (width < 8 || !llvm::isPowerOf2_32(width))
61 return AliasResult::NoAlias;
62 os << intType.getAlias();
63 return AliasResult::OverridableAlias;
65 if (
auto voidType = dyn_cast<cir::VoidType>(type)) {
66 os << voidType.getAlias();
67 return AliasResult::OverridableAlias;
70 return AliasResult::NoAlias;
73 AliasResult getAlias(Attribute attr, raw_ostream &os)
const final {
74 if (
auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr)) {
75 os << (boolAttr.getValue() ?
"true" :
"false");
76 return AliasResult::FinalAlias;
78 if (
auto bitfield = mlir::dyn_cast<cir::BitfieldInfoAttr>(attr)) {
79 os <<
"bfi_" << bitfield.getName().str();
80 return AliasResult::FinalAlias;
82 if (
auto dynCastInfoAttr = mlir::dyn_cast<cir::DynamicCastInfoAttr>(attr)) {
83 os << dynCastInfoAttr.getAlias();
84 return AliasResult::FinalAlias;
86 if (
auto cmpThreeWayInfoAttr =
87 mlir::dyn_cast<cir::CmpThreeWayInfoAttr>(attr)) {
88 os << cmpThreeWayInfoAttr.getAlias();
89 return AliasResult::FinalAlias;
91 return AliasResult::NoAlias;
96void cir::CIRDialect::initialize() {
101#include "clang/CIR/Dialect/IR/CIROps.cpp.inc"
103 addInterfaces<CIROpAsmDialectInterface>();
106Operation *cir::CIRDialect::materializeConstant(mlir::OpBuilder &builder,
107 mlir::Attribute value,
109 mlir::Location loc) {
110 return cir::ConstantOp::create(builder, loc, type,
111 mlir::cast<mlir::TypedAttr>(value));
115 return attrName == CIRDialect::getOpenCLVersionAttrName() ||
116 attrName == CIRDialect::getOpenCLCXXVersionAttrName();
120 NamedAttribute attr) {
121 StringRef attrName = attr.getName().getValue();
122 if (isa<ModuleOp>(op))
125 return op->emitError() << attrName
126 <<
" attribute must be attached to a module";
130 cir::OpenCLVersionAttr cxxVersion) {
131 return (openCLVersion.getMajor() == 2 && openCLVersion.getMinor() == 0 &&
132 cxxVersion.getMajor() == 1 && cxxVersion.getMinor() == 0) ||
133 (openCLVersion.getMajor() == 3 && openCLVersion.getMinor() == 0 &&
134 cxxVersion.getMajor() == 2021 && cxxVersion.getMinor() == 0);
138 cir::OpenCLVersionAttr cxxVersion) {
139 Attribute openCLAttr =
140 module->getAttr(CIRDialect::getOpenCLVersionAttrName());
142 return module.emitError()
143 << "module attribute '" << CIRDialect::getOpenCLCXXVersionAttrName()
144 << "' requires the companion attribute '"
145 << CIRDialect::getOpenCLVersionAttrName() << "'";
147 auto openCLVersion = dyn_cast<cir::OpenCLVersionAttr>(openCLAttr);
152 return module.emitError("incompatible OpenCL and C++ for OpenCL versions");
158 NamedAttribute attr) {
162 StringRef attrName = attr.getName().getValue();
163 auto version = dyn_cast<cir::OpenCLVersionAttr>(attr.getValue());
165 return op->emitError() <<
"expected " << attrName
166 <<
" to be #cir.cl.version";
169 if (attrName == CIRDialect::getOpenCLCXXVersionAttrName())
175LogicalResult cir::CIRDialect::verifyRegionArgAttribute(
176 Operation *op,
unsigned ,
unsigned ,
177 NamedAttribute attr) {
184LogicalResult cir::CIRDialect::verifyRegionResultAttribute(
185 Operation *op,
unsigned ,
unsigned ,
186 NamedAttribute attr) {
198 cir::OffloadKind expected) {
199 auto attr =
module->getAttrOfType<cir::OffloadKindAttr>(
200 cir::CIRDialect::getOffloadKindAttrName());
202 return module.emitOpError()
203 << "expects '" << cir::CIRDialect::getOffloadKindAttrName()
204 << "' offload kind attribute";
205 if (attr.getValue() != expected)
206 return module.emitOpError()
207 << "expects '" << cir::CIRDialect::getOffloadKindAttrName()
208 << "' value '" << cir::stringifyOffloadKind(expected) << "'";
217 auto container = mlir::dyn_cast<mlir::ModuleOp>(op);
219 return op->emitOpError()
220 <<
"expects '" << cir::CIRDialect::getOffloadContainerAttrName()
221 <<
"' attribute to be attached to '"
222 << mlir::ModuleOp::getOperationName() <<
"'";
224 mlir::Block &body = *container.getBody();
226 return container.emitOpError()
227 <<
"expects host module as the first nested op";
229 auto host = mlir::dyn_cast<mlir::ModuleOp>(body.front());
231 return container.emitOpError()
232 <<
"expects host module as the first nested op";
237 if (std::next(body.begin()) == body.end())
238 return container.emitOpError() <<
"expects at least one device module";
240 for (
auto &op : llvm::drop_begin(body)) {
241 auto module = mlir::dyn_cast<mlir::ModuleOp>(op);
243 return container.emitOpError()
244 <<
"expects only nested builtin.module ops";
252cir::CIRDialect::verifyOperationAttribute(mlir::Operation *op,
253 mlir::NamedAttribute attr) {
254 llvm::StringRef attrName =
attr.getName().getValue();
258 if (attrName == getOffloadContainerAttrName()) {
259 if (!mlir::isa<mlir::UnitAttr>(
attr.getValue()))
260 return op->emitOpError() <<
"expects '" << getOffloadContainerAttrName()
261 <<
"' to be a unit attribute";
268 if (attrName == getOffloadKindAttrName() && !mlir::isa<mlir::ModuleOp>(op))
269 return op->emitOpError() <<
"expects '" << getOffloadKindAttrName()
270 <<
"' attribute to be attached to '"
271 << mlir::ModuleOp::getOperationName() <<
"'";
275 if (attrName == getCUDADeviceBinaryAttrName()) {
276 auto bytes = mlir::dyn_cast<mlir::StringAttr>(
attr.getValue());
279 if (!arrayTy || arrayTy.getSize() !=
bytes.size())
280 return op->emitOpError()
281 <<
"expects '" << getCUDADeviceBinaryAttrName()
282 <<
"' to be a string typed as an array of its length";
283 return cir::ConstArrayAttr::verify([&] {
return op->emitOpError(); },
300 for (
auto en : llvm::enumerate(keywords)) {
301 if (succeeded(parser.parseOptionalKeyword(en.value())))
308template <
typename Ty>
struct EnumTraits {};
310#define REGISTER_ENUM_TYPE(Ty) \
311 template <> struct EnumTraits<cir::Ty> { \
312 static llvm::StringRef stringify(cir::Ty value) { \
313 return stringify##Ty(value); \
315 static unsigned getMaxEnumVal() { return cir::getMaxEnumValFor##Ty(); } \
326template <
typename EnumTy,
typename RetTy = EnumTy>
329 for (
unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
330 names.push_back(EnumTraits<EnumTy>::stringify(
static_cast<EnumTy
>(i)));
334 return static_cast<RetTy
>(defaultValue);
335 return static_cast<RetTy
>(index);
339template <
typename EnumTy,
typename RetTy = EnumTy>
342 for (
unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
343 names.push_back(EnumTraits<EnumTy>::stringify(
static_cast<EnumTy
>(i)));
348 result =
static_cast<RetTy
>(index);
356 Location eLoc = parser.getEncodedSourceLoc(parser.getCurrentLocation());
357 OpBuilder builder(parser.getBuilder().getContext());
362 builder.createBlock(®ion);
364 Block &block = region.back();
366 if (!block.empty() && block.back().hasTrait<OpTrait::IsTerminator>())
370 if (!region.hasOneBlock())
371 return parser.emitError(errLoc,
372 "multi-block region must not omit terminator");
375 builder.setInsertionPointToEnd(&block);
376 cir::YieldOp::create(builder, eLoc);
382 const auto singleNonEmptyBlock = r.hasOneBlock() && !r.back().empty();
383 const auto yieldsNothing = [&r]() {
384 auto y = dyn_cast<cir::YieldOp>(r.back().getTerminator());
385 return y && y.getArgs().empty();
387 return singleNonEmptyBlock && yieldsNothing();
392template <
typename ExpectedProducerOp>
394 StringRef operandName) {
395 Operation *producer = operand.getDefiningOp();
396 if (!producer || !isa<ExpectedProducerOp>(producer))
397 return op->emitOpError()
398 <<
"operand '" << operandName <<
"' must be produced by '"
399 << ExpectedProducerOp::getOperationName() <<
"'";
408 cir::InlineKindAttr &inlineKindAttr) {
410 static constexpr llvm::StringRef keywords[] = {
"no_inline",
"always_inline",
414 llvm::StringRef keyword;
415 if (parser.parseOptionalKeyword(&keyword, keywords).failed()) {
421 auto inlineKindResult = ::cir::symbolizeEnum<::cir::InlineKind>(keyword);
422 if (!inlineKindResult) {
423 return parser.emitError(parser.getCurrentLocation(),
"expected one of [")
425 <<
"] for inlineKind, got: " << keyword;
429 ::cir::InlineKindAttr::get(parser.getContext(), *inlineKindResult);
434 if (inlineKindAttr) {
435 p <<
" " << stringifyInlineKind(inlineKindAttr.getValue());
444 mlir::Region ®ion) {
445 auto regionLoc = parser.getCurrentLocation();
446 if (parser.parseRegion(region))
455 mlir::Region ®ion) {
456 printer.printRegion(region,
461mlir::OptionalParseResult
463 mlir::ptr::MemorySpaceAttrInterface &attr);
466 mlir::ptr::MemorySpaceAttrInterface attr);
472void cir::AllocaOp::build(mlir::OpBuilder &odsBuilder,
473 mlir::OperationState &odsState, mlir::Type addr,
474 llvm::StringRef name, mlir::IntegerAttr alignment) {
475 odsState.addAttribute(getNameAttrName(odsState.name),
476 odsBuilder.getStringAttr(name));
478 odsState.addAttribute(getAlignmentAttrName(odsState.name), alignment);
480 odsState.addTypes(addr);
484 mlir::Value ptr = addr;
485 while (cir::CastOp castOp = ptr.getDefiningOp<cir::CastOp>()) {
486 if (!castOp.isAllocaPreservingCast())
488 ptr = castOp.getSrc();
490 return ptr.getDefiningOp<cir::AllocaOp>();
498 auto ptrTy = mlir::cast<cir::PointerType>(op.getAddr().getType());
499 mlir::Type pointeeTy = ptrTy.getPointee();
501 mlir::Block &body = op.getBody().front();
502 if (body.getNumArguments() != 1)
503 return op.emitOpError(
"body must have exactly one block argument");
505 auto expectedEltPtrTy =
506 mlir::dyn_cast<cir::PointerType>(body.getArgument(0).getType());
507 if (!expectedEltPtrTy)
508 return op.emitOpError(
"block argument must be a !cir.ptr type");
510 if (op.getNumElements()) {
511 auto recTy = mlir::dyn_cast<cir::RecordType>(pointeeTy);
513 return op.emitOpError(
514 "when 'num_elements' is present, 'addr' must be a pointer to a "
515 "!cir.struct or !cir.union type");
517 if (expectedEltPtrTy != ptrTy)
518 return op.emitOpError(
"when 'num_elements' is present, 'addr' type must "
519 "match the block argument type");
521 auto arrayTy = mlir::dyn_cast<cir::ArrayType>(pointeeTy);
523 return op.emitOpError(
524 "when 'num_elements' is absent, 'addr' must be a pointer to a "
527 mlir::Type innerEltTy = arrayTy.getElementType();
528 while (
auto nested = mlir::dyn_cast<cir::ArrayType>(innerEltTy))
529 innerEltTy = nested.getElementType();
531 auto recTy = mlir::dyn_cast<cir::RecordType>(innerEltTy);
533 return op.emitOpError(
"the block argument type must be a pointer to a "
534 "!cir.struct or !cir.union type");
536 if (expectedEltPtrTy.getPointee() != innerEltTy)
537 return op.emitOpError(
538 "block argument pointee type must match the innermost array "
545LogicalResult cir::ArrayCtor::verify() {
549 mlir::Region &partialDtor = getPartialDtor();
550 if (!partialDtor.empty()) {
551 mlir::Block &dtorBlock = partialDtor.front();
552 if (dtorBlock.getNumArguments() != 1)
553 return emitOpError(
"partial_dtor must have exactly one block argument");
555 auto bodyArgTy = getBody().front().getArgument(0).getType();
556 if (dtorBlock.getArgument(0).getType() != bodyArgTy)
557 return emitOpError(
"partial_dtor block argument type must match "
558 "the body block argument type");
568LogicalResult cir::DeleteArrayOp::verify() {
569 if (getDtorMayThrow() && !getElementDtorAttr())
571 "'dtor_may_throw' requires an 'element_dtor' to be present");
580 cir::AssumeBundleKindAttr kindAttr,
581 OperandRange bundleArgs,
582 TypeRange bundleArgTypes) {
583 cir::AssumeBundleKind
kind = kindAttr.getValue();
584 if (
kind == cir::AssumeBundleKind::None)
587 p <<
" " << cir::stringifyAssumeBundleKind(
kind);
588 if (bundleArgs.empty())
592 p.printOperands(bundleArgs);
594 llvm::interleaveComma(bundleArgTypes, p);
599 OpAsmParser &p, cir::AssumeBundleKindAttr &bundleKindAttr,
603 auto loc = p.getCurrentLocation();
604 if (failed(p.parseOptionalKeyword(&keyword))) {
605 bundleKindAttr = cir::AssumeBundleKindAttr::get(
606 p.getContext(), cir::AssumeBundleKind::None);
610 std::optional<cir::AssumeBundleKind> parsedKind =
611 cir::symbolizeAssumeBundleKind(keyword);
613 return p.emitError(loc,
"unknown assume bundle kind '") << keyword <<
"'";
615 bundleKindAttr = cir::AssumeBundleKindAttr::get(p.getContext(), *parsedKind);
617 if (p.parseOptionalLParen())
620 if (p.parseOperandList(bundleArgs) || p.parseColon() ||
621 p.parseTypeList(bundleArgTypes) || p.parseRParen())
627LogicalResult cir::AssumeOp::verify() {
628 cir::AssumeBundleKind
kind = getBundleKind();
629 size_t numArgs = getBundleArgs().size();
631 if (
kind == cir::AssumeBundleKind::None) {
633 return emitOpError(
"unexpected bundle operands for kind 'none'");
638 return emitOpError(
"expected bundle operands for kind '")
639 << cir::stringifyAssumeBundleKind(
kind) <<
"'";
642 case cir::AssumeBundleKind::Align:
643 if (numArgs != 2 && numArgs != 3)
644 return emitOpError(
"align bundle expects 2 or 3 operands");
646 case cir::AssumeBundleKind::SeparateStorage:
648 return emitOpError(
"separate_storage bundle expects 2 operands");
650 case cir::AssumeBundleKind::Dereferenceable:
652 return emitOpError(
"dereferenceable bundle expects 2 operands");
665cir::LocalInitOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
666 cir::GlobalOp global = getReferencedGlobal(symbolTable);
668 return emitOpError(
"'")
669 << getGlobalName() <<
"' does not reference a valid cir.global";
671 if (getTls() && !global.getTlsModel())
672 return emitOpError(
"access to global not marked thread local");
674 if (!global.getStaticLocalGuard().has_value())
675 return emitOpError(
"static_local attribute mismatch");
688void cir::ConditionOp::getSuccessorRegions(
695 if (
auto loopOp = dyn_cast<LoopOpInterface>(getOperation()->getParentOp())) {
696 regions.emplace_back(&loopOp.getBody());
697 if (mlir::Region *cleanup = loopOp.maybeGetCleanup())
698 regions.emplace_back(cleanup);
700 regions.emplace_back(getOperation());
705 auto await = cast<AwaitOp>(getOperation()->getParentOp());
706 regions.emplace_back(&await.getResume());
707 regions.emplace_back(&await.getSuspend());
711cir::ConditionOp::getMutableSuccessorOperands(RegionSuccessor point) {
713 return MutableOperandRange(getOperation(), 0, 0);
717cir::ResumeOp::getMutableSuccessorOperands(RegionSuccessor point) {
719 return MutableOperandRange(getOperation(), 0, 0);
722LogicalResult cir::ConditionOp::verify() {
723 if (!isa<LoopOpInterface, AwaitOp>(getOperation()->getParentOp()))
724 return emitOpError(
"condition must be within a conditional region");
732template <
typename LoopOpTy>
734 std::optional<cir::CleanupKind> cleanupKind = op.getCleanupKind();
738 if (cleanupKind.has_value() == op.getCleanup().empty())
739 return op.emitOpError(
"cleanup kind must be present if and only if the "
740 "cleanup region is non-empty");
745 if (cleanupKind == cir::CleanupKind::EH)
746 return op.emitOpError(
"loop cleanup kind must be 'normal' or 'all', "
761 mlir::Attribute attrType) {
762 if (isa<cir::ConstPtrAttr>(attrType)) {
763 if (!mlir::isa<cir::PointerType>(opType))
764 return op->emitOpError(
765 "pointer constant initializing a non-pointer type");
769 if (isa<cir::DataMemberAttr, cir::DataMemberOffsetAttr, cir::MethodAttr>(
776 if (isa<cir::ZeroAttr>(attrType)) {
777 if (isa<
cir::RecordType, cir::ArrayType, cir::MatrixType, cir::VectorType,
778 cir::ComplexType>(opType))
780 return op->emitOpError(
781 "zero expects struct, array, vector, or complex type");
784 if (mlir::isa<cir::UndefAttr>(attrType)) {
785 if (!mlir::isa<cir::VoidType>(opType))
787 return op->emitOpError(
"undef expects non-void type");
790 if (mlir::isa<cir::BoolAttr>(attrType)) {
791 if (!mlir::isa<cir::BoolType>(opType))
792 return op->emitOpError(
"result type (")
793 << opType <<
") must be '!cir.bool' for '" << attrType <<
"'";
797 if (mlir::isa<cir::IntAttr, cir::FPAttr>(attrType)) {
798 auto at = cast<TypedAttr>(attrType);
799 if (at.getType() != opType) {
800 return op->emitOpError(
"result type (")
801 << opType <<
") does not match value type (" << at.getType()
807 if (mlir::isa<cir::BlockAddrDiffAttr, cir::BlockAddrInfoAttr,
808 cir::ConstArrayAttr, cir::ConstVectorAttr,
809 cir::ConstComplexAttr, cir::ConstRecordAttr,
810 cir::GlobalOffsetAttr, cir::GlobalViewAttr, cir::PoisonAttr,
811 cir::TypeInfoAttr, cir::VTableAttr>(attrType))
814 assert(isa<TypedAttr>(attrType) &&
"What else could we be looking at here?");
815 return op->emitOpError(
"global with type ")
816 << cast<TypedAttr>(attrType).getType() <<
" not yet supported";
819LogicalResult cir::ConstantOp::verify() {
826OpFoldResult cir::ConstantOp::fold(FoldAdaptor ) {
836 case cir::CastKind::floating:
837 case cir::CastKind::int_to_float:
838 case cir::CastKind::float_to_int:
839 case cir::CastKind::float_to_bool:
840 case cir::CastKind::bool_to_float:
841 case cir::CastKind::float_to_complex:
842 case cir::CastKind::float_complex_to_real:
843 case cir::CastKind::float_complex_to_bool:
844 case cir::CastKind::float_complex:
845 case cir::CastKind::float_complex_to_int_complex:
846 case cir::CastKind::int_complex_to_float_complex:
853LogicalResult cir::CastOp::verify() {
854 mlir::Type resType =
getType();
855 mlir::Type srcType = getSrc().getType();
860 <<
"'fenv' is only valid for floating-point cast kinds";
864 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
865 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
866 if (srcPtrTy && resPtrTy && (
kind != cir::CastKind::address_space))
867 if (srcPtrTy.getAddrSpace() != resPtrTy.getAddrSpace()) {
868 return emitOpError() <<
"result type address space does not match the "
869 "address space of the operand";
872 auto srcVTy = mlir::dyn_cast<cir::VectorType>(srcType);
873 auto resVTy = mlir::dyn_cast<cir::VectorType>(resType);
874 if (srcVTy && resVTy) {
875 if ((
kind == cir::CastKind::int_to_float ||
876 kind == cir::CastKind::float_to_int) &&
877 srcVTy.getSize() != resVTy.getSize()) {
879 <<
"vector float-to-int and int-to-float casts require "
880 "source and destination vectors to have the same number of "
885 srcType = srcVTy.getElementType();
886 resType = resVTy.getElementType();
890 case cir::CastKind::int_to_bool: {
891 if (!mlir::isa<cir::BoolType>(resType))
892 return emitOpError() <<
"requires !cir.bool type for result";
893 if (!mlir::isa<cir::IntType>(srcType))
894 return emitOpError() <<
"requires !cir.int type for source";
897 case cir::CastKind::ptr_to_bool: {
898 if (!mlir::isa<cir::BoolType>(resType))
899 return emitOpError() <<
"requires !cir.bool type for result";
900 if (!mlir::isa<cir::PointerType>(srcType))
901 return emitOpError() <<
"requires !cir.ptr type for source";
904 case cir::CastKind::integral: {
905 if (!mlir::isa<cir::IntType>(resType))
906 return emitOpError() <<
"requires !cir.int type for result";
907 if (!mlir::isa<cir::IntType>(srcType))
908 return emitOpError() <<
"requires !cir.int type for source";
911 case cir::CastKind::array_to_ptrdecay: {
912 const auto arrayPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
913 const auto flatPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
914 if (!arrayPtrTy || !flatPtrTy)
915 return emitOpError() <<
"requires !cir.ptr type for source and result";
920 case cir::CastKind::bitcast: {
922 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
923 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
925 if (srcPtrTy && resPtrTy) {
931 case cir::CastKind::floating: {
932 if (!mlir::isa<cir::FPTypeInterface>(srcType) ||
933 !mlir::isa<cir::FPTypeInterface>(resType))
934 return emitOpError() <<
"requires !cir.float type for source and result";
937 case cir::CastKind::float_to_int: {
938 if (!mlir::isa<cir::FPTypeInterface>(srcType))
939 return emitOpError() <<
"requires !cir.float type for source";
940 if (!mlir::dyn_cast<cir::IntType>(resType))
941 return emitOpError() <<
"requires !cir.int type for result";
944 case cir::CastKind::int_to_ptr: {
945 if (!mlir::dyn_cast<cir::IntType>(srcType))
946 return emitOpError() <<
"requires !cir.int type for source";
947 if (!mlir::dyn_cast<cir::PointerType>(resType))
948 return emitOpError() <<
"requires !cir.ptr type for result";
951 case cir::CastKind::ptr_to_int: {
952 if (!mlir::dyn_cast<cir::PointerType>(srcType))
953 return emitOpError() <<
"requires !cir.ptr type for source";
954 if (!mlir::dyn_cast<cir::IntType>(resType))
955 return emitOpError() <<
"requires !cir.int type for result";
958 case cir::CastKind::float_to_bool: {
959 if (!mlir::isa<cir::FPTypeInterface>(srcType))
960 return emitOpError() <<
"requires !cir.float type for source";
961 if (!mlir::isa<cir::BoolType>(resType))
962 return emitOpError() <<
"requires !cir.bool type for result";
965 case cir::CastKind::bool_to_int: {
966 if (!mlir::isa<cir::BoolType>(srcType))
967 return emitOpError() <<
"requires !cir.bool type for source";
968 if (!mlir::isa<cir::IntType>(resType))
969 return emitOpError() <<
"requires !cir.int type for result";
972 case cir::CastKind::int_to_float: {
973 if (!mlir::isa<cir::IntType>(srcType))
974 return emitOpError() <<
"requires !cir.int type for source";
975 if (!mlir::isa<cir::FPTypeInterface>(resType))
976 return emitOpError() <<
"requires !cir.float type for result";
979 case cir::CastKind::bool_to_float: {
980 if (!mlir::isa<cir::BoolType>(srcType))
981 return emitOpError() <<
"requires !cir.bool type for source";
982 if (!mlir::isa<cir::FPTypeInterface>(resType))
983 return emitOpError() <<
"requires !cir.float type for result";
986 case cir::CastKind::address_space: {
987 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
988 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
989 if (!srcPtrTy || !resPtrTy)
990 return emitOpError() <<
"requires !cir.ptr type for source and result";
991 if (srcPtrTy.getPointee() != resPtrTy.getPointee())
992 return emitOpError() <<
"requires two types differ in addrspace only";
995 case cir::CastKind::float_to_complex: {
996 if (!mlir::isa<cir::FPTypeInterface>(srcType))
997 return emitOpError() <<
"requires !cir.float type for source";
998 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
1000 return emitOpError() <<
"requires !cir.complex type for result";
1001 if (srcType != resComplexTy.getElementType())
1002 return emitOpError() <<
"requires source type match result element type";
1005 case cir::CastKind::int_to_complex: {
1006 if (!mlir::isa<cir::IntType>(srcType))
1007 return emitOpError() <<
"requires !cir.int type for source";
1008 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
1010 return emitOpError() <<
"requires !cir.complex type for result";
1011 if (srcType != resComplexTy.getElementType())
1012 return emitOpError() <<
"requires source type match result element type";
1015 case cir::CastKind::float_complex_to_real: {
1016 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1018 return emitOpError() <<
"requires !cir.complex type for source";
1019 if (!mlir::isa<cir::FPTypeInterface>(resType))
1020 return emitOpError() <<
"requires !cir.float type for result";
1021 if (srcComplexTy.getElementType() != resType)
1022 return emitOpError() <<
"requires source element type match result type";
1025 case cir::CastKind::int_complex_to_real: {
1026 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1028 return emitOpError() <<
"requires !cir.complex type for source";
1029 if (!mlir::isa<cir::IntType>(resType))
1030 return emitOpError() <<
"requires !cir.int type for result";
1031 if (srcComplexTy.getElementType() != resType)
1032 return emitOpError() <<
"requires source element type match result type";
1035 case cir::CastKind::float_complex_to_bool: {
1036 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1037 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
1038 return emitOpError()
1039 <<
"requires floating point !cir.complex type for source";
1040 if (!mlir::isa<cir::BoolType>(resType))
1041 return emitOpError() <<
"requires !cir.bool type for result";
1044 case cir::CastKind::int_complex_to_bool: {
1045 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1046 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
1047 return emitOpError()
1048 <<
"requires floating point !cir.complex type for source";
1049 if (!mlir::isa<cir::BoolType>(resType))
1050 return emitOpError() <<
"requires !cir.bool type for result";
1053 case cir::CastKind::float_complex: {
1054 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1055 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
1056 return emitOpError()
1057 <<
"requires floating point !cir.complex type for source";
1058 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
1059 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
1060 return emitOpError()
1061 <<
"requires floating point !cir.complex type for result";
1064 case cir::CastKind::float_complex_to_int_complex: {
1065 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1066 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
1067 return emitOpError()
1068 <<
"requires floating point !cir.complex type for source";
1069 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
1070 if (!resComplexTy || !resComplexTy.isIntegerComplex())
1071 return emitOpError() <<
"requires integer !cir.complex type for result";
1074 case cir::CastKind::int_complex: {
1075 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1076 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
1077 return emitOpError() <<
"requires integer !cir.complex type for source";
1078 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
1079 if (!resComplexTy || !resComplexTy.isIntegerComplex())
1080 return emitOpError() <<
"requires integer !cir.complex type for result";
1083 case cir::CastKind::int_complex_to_float_complex: {
1084 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1085 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
1086 return emitOpError() <<
"requires integer !cir.complex type for source";
1087 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
1088 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
1089 return emitOpError()
1090 <<
"requires floating point !cir.complex type for result";
1093 case cir::CastKind::member_ptr_to_bool: {
1094 if (!mlir::isa<cir::DataMemberType, cir::MethodType>(srcType))
1095 return emitOpError()
1096 <<
"requires !cir.data_member or !cir.method type for source";
1097 if (!mlir::isa<cir::BoolType>(resType))
1098 return emitOpError() <<
"requires !cir.bool type for result";
1102 llvm_unreachable(
"Unknown CastOp kind?");
1106 auto kind = op.getKind();
1107 return kind == cir::CastKind::bool_to_int ||
1108 kind == cir::CastKind::int_to_bool ||
kind == cir::CastKind::integral;
1112 const auto ptrTy = mlir::dyn_cast<cir::PointerType>(ty);
1113 return ptrTy && mlir::isa<cir::FuncType>(ptrTy.getPointee());
1117 cir::CastOp head = op, tail = op;
1123 op = head.getSrc().getDefiningOp<cir::CastOp>();
1129 if (head.getKind() == cir::CastKind::bool_to_int &&
1130 tail.getKind() == cir::CastKind::int_to_bool)
1131 return head.getSrc();
1136 if (head.getKind() == cir::CastKind::int_to_bool &&
1137 tail.getKind() == cir::CastKind::int_to_bool)
1138 return head.getResult();
1146 if (tail.getKind() == cir::CastKind::bitcast) {
1147 auto *inner = tail.getSrc().getDefiningOp();
1149 auto innerCast = mlir::dyn_cast<cir::CastOp>(inner);
1150 if (innerCast && innerCast.getKind() == cir::CastKind::bitcast &&
1151 innerCast.getSrc().getType() == tail.getType() &&
1152 innerCast.getType() == tail.getSrc().getType()) {
1153 return innerCast.getSrc();
1161OpFoldResult cir::CastOp::fold(FoldAdaptor adaptor) {
1162 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getSrc())) {
1164 return cir::PoisonAttr::get(getContext(),
getType());
1168 if (mlir::isa_and_present<cir::UndefAttr>(adaptor.getSrc()))
1169 return cir::UndefAttr::get(
getType());
1173 case cir::CastKind::integral: {
1175 auto foldOrder = getSrc().getDefiningOp()->fold(foldResults);
1176 if (foldOrder.succeeded() && mlir::isa<mlir::Attribute>(foldResults[0]))
1177 return mlir::cast<mlir::Attribute>(foldResults[0]);
1180 case cir::CastKind::bitcast:
1181 case cir::CastKind::address_space:
1182 case cir::CastKind::float_complex:
1183 case cir::CastKind::int_complex: {
1197 if (
auto srcConst = getSrc().getDefiningOp<cir::ConstantOp>()) {
1199 case cir::CastKind::integral: {
1200 mlir::Type srcTy = getSrc().getType();
1202 assert(mlir::isa<cir::VectorType>(srcTy) ==
1203 mlir::isa<cir::VectorType>(
getType()));
1204 if (mlir::isa<cir::VectorType>(srcTy))
1207 auto srcIntTy = mlir::cast<cir::IntType>(srcTy);
1208 auto dstIntTy = mlir::cast<cir::IntType>(
getType());
1209 auto constIntAttr = srcConst.getValueAttr<cir::IntAttr>();
1213 APInt srcValue = constIntAttr.getValue();
1214 APInt newVal = srcIntTy.isSigned()
1215 ? srcValue.sextOrTrunc(dstIntTy.getWidth())
1216 : srcValue.zextOrTrunc(dstIntTy.getWidth());
1217 return cir::IntAttr::get(dstIntTy, newVal);
1230LogicalResult cir::BuiltinIntCastOp::verify() {
1231 mlir::Type srcType = getSrc().getType();
1232 mlir::Type resType =
getType();
1234 auto srcCirInt = mlir::dyn_cast<cir::IntType>(srcType);
1235 auto resCirInt = mlir::dyn_cast<cir::IntType>(resType);
1239 if (
static_cast<bool>(srcCirInt) ==
static_cast<bool>(resCirInt))
1240 return emitOpError()
1241 <<
"requires exactly one '!cir.int' operand or result; the other "
1242 "must be a builtin integer or 'index' type";
1244 mlir::Type
builtinType = srcCirInt ? resType : srcType;
1245 if (!mlir::isa<mlir::IntegerType, mlir::IndexType>(builtinType))
1246 return emitOpError() <<
"requires a builtin integer or 'index' type on the "
1251 if (
auto builtinInt = mlir::dyn_cast<mlir::IntegerType>(builtinType)) {
1252 cir::IntType cirInt = srcCirInt ? srcCirInt : resCirInt;
1253 if (cirInt.getWidth() != builtinInt.getWidth())
1254 return emitOpError()
1255 <<
"requires the CIR and builtin integer types to have the same "
1256 "width; use 'cir.cast' for width conversions";
1262OpFoldResult cir::BuiltinIntCastOp::fold(FoldAdaptor adaptor) {
1265 if (
auto inner = getSrc().getDefiningOp<cir::BuiltinIntCastOp>())
1266 if (inner.getSrc().getType() ==
getType())
1267 return inner.getSrc();
1275mlir::OperandRange cir::CallOp::getArgOperands() {
1277 return getArgs().drop_front(1);
1281mlir::MutableOperandRange cir::CallOp::getArgOperandsMutable() {
1282 mlir::MutableOperandRange args = getArgsMutable();
1284 return args.slice(1, args.size() - 1);
1288mlir::Value cir::CallOp::getIndirectCall() {
1289 assert(isIndirect());
1290 return getOperand(0);
1294Value cir::CallOp::getArgOperand(
unsigned i) {
1297 return getOperand(i);
1301unsigned cir::CallOp::getNumArgOperands() {
1303 return this->getOperation()->getNumOperands() - 1;
1304 return this->getOperation()->getNumOperands();
1307static mlir::ParseResult
1309 mlir::OperationState &result) {
1310 mlir::Block *normalDestSuccessor;
1311 if (parser.parseSuccessor(normalDestSuccessor))
1312 return mlir::failure();
1314 if (parser.parseComma())
1315 return mlir::failure();
1317 mlir::Block *unwindDestSuccessor;
1318 if (parser.parseSuccessor(unwindDestSuccessor))
1319 return mlir::failure();
1321 result.addSuccessors(normalDestSuccessor);
1322 result.addSuccessors(unwindDestSuccessor);
1323 return mlir::success();
1331 const mlir::NamedAttrList &attrs) {
1332 if (mlir::Attribute effects =
1333 attrs.get(CIRDialect::getMemoryEffectsAttrName()))
1334 if (!mlir::isa<cir::MemoryEffectsAttr>(effects))
1335 return parser.emitError(loc,
"attribute '")
1336 << CIRDialect::getMemoryEffectsAttrName()
1337 <<
"' must be a #cir.memory_effects attribute";
1339 for (llvm::StringRef name :
1340 {CIRDialect::getNoUnwindAttrName(), CIRDialect::getWillReturnAttrName()})
1341 if (mlir::Attribute flag = attrs.get(name))
1342 if (!mlir::isa<mlir::UnitAttr>(flag))
1343 return parser.emitError(loc,
"attribute '")
1344 << name <<
"' must be a unit attribute";
1346 return mlir::success();
1350 mlir::OperationState &result,
1351 bool hasDestinationBlocks =
false) {
1354 mlir::FlatSymbolRefAttr calleeAttr;
1358 .parseOptionalAttribute(calleeAttr, CIRDialect::getCalleeAttrName(),
1361 OpAsmParser::UnresolvedOperand indirectVal;
1363 if (parser.parseOperand(indirectVal).failed())
1365 ops.push_back(indirectVal);
1368 if (parser.parseLParen())
1369 return mlir::failure();
1371 opsLoc = parser.getCurrentLocation();
1372 if (parser.parseOperandList(ops))
1373 return mlir::failure();
1374 if (parser.parseRParen())
1375 return mlir::failure();
1377 if (hasDestinationBlocks &&
1379 return ::mlir::failure();
1382 if (parser.parseOptionalKeyword(
"musttail").succeeded())
1383 result.addAttribute(CIRDialect::getMustTailAttrName(),
1384 mlir::UnitAttr::get(parser.getContext()));
1386 if (parser.parseOptionalKeyword(
"nothrow").succeeded())
1387 result.addAttribute(CIRDialect::getNoThrowAttrName(),
1388 mlir::UnitAttr::get(parser.getContext()));
1390 if (parser.parseOptionalKeyword(
"nounwind").succeeded())
1391 result.addAttribute(CIRDialect::getNoUnwindAttrName(),
1392 mlir::UnitAttr::get(parser.getContext()));
1394 if (parser.parseOptionalKeyword(
"willreturn").succeeded())
1395 result.addAttribute(CIRDialect::getWillReturnAttrName(),
1396 mlir::UnitAttr::get(parser.getContext()));
1398 llvm::SMLoc attrsLoc = parser.getCurrentLocation();
1399 if (parser.parseOptionalAttrDict(result.attributes))
1400 return ::mlir::failure();
1403 return ::mlir::failure();
1405 if (parser.parseColon())
1406 return ::mlir::failure();
1412 if (call_interface_impl::parseFunctionSignature(parser, argTypes, argAttrs,
1413 resultTypes, resultAttrs))
1414 return mlir::failure();
1416 if (resultTypes.size() > 1 || resultAttrs.size() > 1)
1417 return parser.emitError(
1418 parser.getCurrentLocation(),
1419 "functions with multiple return types are not supported");
1421 result.addTypes(resultTypes);
1423 if (parser.resolveOperands(ops, argTypes, opsLoc, result.operands))
1424 return mlir::failure();
1426 if (!resultAttrs.empty() && resultAttrs[0])
1427 result.addAttribute(
1428 CIRDialect::getResAttrsAttrName(),
1429 mlir::ArrayAttr::get(parser.getContext(), {resultAttrs[0]}));
1434 bool argAttrsEmpty =
true;
1436 llvm::transform(argAttrs, std::back_inserter(convertedArgAttrs),
1437 [&](DictionaryAttr da) -> mlir::Attribute {
1439 argAttrsEmpty =
false;
1443 if (!argAttrsEmpty) {
1448 argAttrsRef = argAttrsRef.drop_front();
1450 result.addAttribute(CIRDialect::getArgAttrsAttrName(),
1451 mlir::ArrayAttr::get(parser.getContext(), argAttrsRef));
1454 return mlir::success();
1458 mlir::FlatSymbolRefAttr calleeSym,
1459 mlir::Value indirectCallee,
1460 mlir::OpAsmPrinter &printer,
bool isNothrow,
1461 ArrayAttr argAttrs, ArrayAttr resAttrs,
1462 mlir::Block *normalDest =
nullptr,
1463 mlir::Block *unwindDest =
nullptr) {
1466 auto callLikeOp = mlir::cast<cir::CIRCallOpInterface>(op);
1467 auto ops = callLikeOp.getArgOperands();
1471 printer.printAttributeWithoutType(calleeSym);
1474 assert(indirectCallee);
1475 printer << indirectCallee;
1478 printer <<
"(" << ops <<
")";
1481 assert(unwindDest &&
"expected two successors");
1482 auto tryCall = cast<cir::TryCallOp>(op);
1483 printer <<
' ' << tryCall.getNormalDest();
1486 printer << tryCall.getUnwindDest();
1489 if (op->hasAttr(CIRDialect::getMustTailAttrName()))
1490 printer <<
" musttail";
1493 printer <<
" nothrow";
1495 if (op->hasAttr(CIRDialect::getNoUnwindAttrName()))
1496 printer <<
" nounwind";
1498 if (op->hasAttr(CIRDialect::getWillReturnAttrName()))
1499 printer <<
" willreturn";
1501 llvm::StringRef elidedAttrs[] = {
1502 CIRDialect::getCalleeAttrName(),
1503 CIRDialect::getMustTailAttrName(),
1504 CIRDialect::getNoThrowAttrName(),
1505 CIRDialect::getNoUnwindAttrName(),
1506 CIRDialect::getWillReturnAttrName(),
1507 CIRDialect::getOperandSegmentSizesAttrName(),
1514 for (mlir::NamedAttribute attr : op->getDiscardableAttrs())
1515 if (!llvm::is_contained(elidedAttrs, attr.getName()))
1516 attrs.push_back(attr);
1517 op->getName().walkInherentAttrs(op, [&](llvm::StringRef name,
1518 mlir::Attribute &attr) {
1519 if (!llvm::is_contained(elidedAttrs, name))
1520 attrs.emplace_back(mlir::StringAttr::get(op->getContext(), name), attr);
1522 llvm::sort(attrs, [](mlir::NamedAttribute lhs, mlir::NamedAttribute rhs) {
1523 return lhs.getName().strref() < rhs.getName().strref();
1525 printer.printOptionalAttrDict(attrs);
1527 if (calleeSym || !argAttrs) {
1528 call_interface_impl::printFunctionSignature(
1529 printer, op->getOperands().getTypes(), argAttrs,
1530 false, op->getResultTypes(), resAttrs);
1538 shimmedArgAttrs.push_back(mlir::DictionaryAttr::get(op->getContext(), {}));
1539 shimmedArgAttrs.append(argAttrs.begin(), argAttrs.end());
1540 call_interface_impl::printFunctionSignature(
1541 printer, op->getOperands().getTypes(),
1542 mlir::ArrayAttr::get(op->getContext(), shimmedArgAttrs),
1543 false, op->getResultTypes(), resAttrs);
1547mlir::ParseResult cir::CallOp::parse(mlir::OpAsmParser &parser,
1548 mlir::OperationState &result) {
1552void cir::CallOp::print(mlir::OpAsmPrinter &p) {
1553 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() :
nullptr;
1554 printCallCommon(*
this, getCalleeAttr(), indirectCallee, p, getNothrow(),
1555 getArgAttrsAttr(), getResAttrsAttr());
1560 SymbolTableCollection &symbolTable) {
1562 op->getAttrOfType<FlatSymbolRefAttr>(CIRDialect::getCalleeAttrName());
1565 return mlir::success();
1568 auto fn = symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(op, fnAttr);
1570 return op->emitOpError() <<
"'" << fnAttr.getValue()
1571 <<
"' does not reference a valid function";
1573 auto callIf = dyn_cast<cir::CIRCallOpInterface>(op);
1574 assert(callIf &&
"expected CIR call interface to be always available");
1578 auto fnType = fn.getFunctionType();
1579 if (!fn.getNoProto()) {
1580 unsigned numCallOperands = callIf.getNumArgOperands();
1581 unsigned numFnOpOperands = fnType.getNumInputs();
1583 if (!fnType.isVarArg() && numCallOperands != numFnOpOperands)
1584 return op->emitOpError(
"incorrect number of operands for callee");
1585 if (fnType.isVarArg() && numCallOperands < numFnOpOperands)
1586 return op->emitOpError(
"too few operands for callee");
1588 for (
unsigned i = 0, e = numFnOpOperands; i != e; ++i)
1589 if (callIf.getArgOperand(i).getType() != fnType.getInput(i))
1590 return op->emitOpError(
"operand type mismatch: expected operand type ")
1591 << fnType.getInput(i) <<
", but provided "
1592 << op->getOperand(i).getType() <<
" for operand number " << i;
1598 if (fnType.hasVoidReturn() && op->getNumResults() != 0)
1599 return op->emitOpError(
"callee returns void but call has results");
1602 if (!fnType.hasVoidReturn() && op->getNumResults() != 1)
1603 return op->emitOpError(
"incorrect number of results for callee");
1606 if (!fnType.hasVoidReturn() &&
1607 op->getResultTypes().front() != fnType.getReturnType()) {
1608 return op->emitOpError(
"result type mismatch: expected ")
1609 << fnType.getReturnType() <<
", but provided "
1610 << op->getResult(0).getType();
1613 return mlir::success();
1617cir::CallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1625mlir::OperandRange cir::TryCallOp::getArgOperands() {
1627 return getArgs().drop_front(1);
1631mlir::MutableOperandRange cir::TryCallOp::getArgOperandsMutable() {
1632 mlir::MutableOperandRange args = getArgsMutable();
1634 return args.slice(1, args.size() - 1);
1638mlir::Value cir::TryCallOp::getIndirectCall() {
1639 assert(isIndirect());
1640 return getOperand(0);
1644Value cir::TryCallOp::getArgOperand(
unsigned i) {
1647 return getOperand(i);
1651unsigned cir::TryCallOp::getNumArgOperands() {
1653 return this->getOperation()->getNumOperands() - 1;
1654 return this->getOperation()->getNumOperands();
1658cir::TryCallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1662mlir::ParseResult cir::TryCallOp::parse(mlir::OpAsmParser &parser,
1663 mlir::OperationState &result) {
1667void cir::TryCallOp::print(::mlir::OpAsmPrinter &p) {
1668 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() :
nullptr;
1669 printCallCommon(*
this, getCalleeAttr(), indirectCallee, p, getNothrow(),
1670 getArgAttrsAttr(), getResAttrsAttr(), getNormalDest(),
1679 cir::FuncOp function) {
1681 if (op.getNumOperands() > 1)
1682 return op.emitOpError() <<
"expects at most 1 return operand";
1685 auto expectedTy = function.getFunctionType().getReturnType();
1687 (op.getNumOperands() == 0 ? cir::VoidType::get(op.getContext())
1688 : op.getOperand(0).getType());
1689 if (actualTy != expectedTy)
1690 return op.emitOpError() <<
"returns " << actualTy
1691 <<
" but enclosing function returns " << expectedTy;
1693 return mlir::success();
1696mlir::LogicalResult cir::ReturnOp::verify() {
1699 auto *fnOp = getOperation()->getParentOp();
1700 while (!isa<cir::FuncOp>(fnOp))
1701 fnOp = fnOp->getParentOp();
1714ParseResult cir::IfOp::parse(OpAsmParser &parser, OperationState &result) {
1716 result.regions.reserve(2);
1717 Region *thenRegion = result.addRegion();
1718 Region *elseRegion = result.addRegion();
1720 mlir::Builder &builder = parser.getBuilder();
1721 OpAsmParser::UnresolvedOperand cond;
1722 Type boolType = cir::BoolType::get(builder.getContext());
1724 if (parser.parseOperand(cond) ||
1725 parser.resolveOperand(cond, boolType, result.operands))
1729 mlir::SMLoc parseThenLoc = parser.getCurrentLocation();
1730 if (parser.parseRegion(*thenRegion, {}, {}))
1737 if (!parser.parseOptionalKeyword(
"else")) {
1738 mlir::SMLoc parseElseLoc = parser.getCurrentLocation();
1739 if (parser.parseRegion(*elseRegion, {}, {}))
1746 if (parser.parseOptionalAttrDict(result.attributes))
1751void cir::IfOp::print(OpAsmPrinter &p) {
1752 p <<
" " << getCondition() <<
" ";
1753 mlir::Region &thenRegion = this->getThenRegion();
1754 p.printRegion(thenRegion,
1759 mlir::Region &elseRegion = this->getElseRegion();
1760 if (!elseRegion.empty()) {
1762 p.printRegion(elseRegion,
1767 p.printOptionalAttrDict(
1768 getOperation()->getDiscardableAttrDictionary().getValue());
1774 cir::YieldOp::create(builder, loc);
1782void cir::IfOp::getSuccessorRegions(mlir::RegionBranchPoint point,
1783 SmallVectorImpl<RegionSuccessor> ®ions) {
1785 if (!point.isParent()) {
1786 regions.emplace_back(getOperation());
1791 Region *elseRegion = &this->getElseRegion();
1792 if (elseRegion->empty())
1793 elseRegion =
nullptr;
1796 regions.push_back(RegionSuccessor(&getThenRegion()));
1798 regions.push_back(RegionSuccessor(elseRegion));
1800 regions.emplace_back(getOperation());
1803void cir::IfOp::build(OpBuilder &builder, OperationState &result,
Value cond,
1806 assert(thenBuilder &&
"the builder callback for 'then' must be present");
1807 result.addOperands(cond);
1809 OpBuilder::InsertionGuard guard(builder);
1810 Region *thenRegion = result.addRegion();
1811 builder.createBlock(thenRegion);
1812 thenBuilder(builder, result.location);
1814 Region *elseRegion = result.addRegion();
1815 if (!withElseRegion)
1818 builder.createBlock(elseRegion);
1819 elseBuilder(builder, result.location);
1831void cir::ScopeOp::getSuccessorRegions(
1832 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1834 if (!point.isParent()) {
1835 regions.emplace_back(getOperation());
1840 regions.push_back(RegionSuccessor(&getScopeRegion()));
1843void cir::ScopeOp::build(
1844 OpBuilder &builder, OperationState &result,
1845 function_ref<
void(OpBuilder &, Type &, Location)> scopeBuilder) {
1846 assert(scopeBuilder &&
"the builder callback for 'then' must be present");
1848 OpBuilder::InsertionGuard guard(builder);
1849 Region *scopeRegion = result.addRegion();
1850 builder.createBlock(scopeRegion);
1854 scopeBuilder(builder, yieldTy, result.location);
1857 result.addTypes(TypeRange{yieldTy});
1860void cir::ScopeOp::build(
1861 OpBuilder &builder, OperationState &result,
1862 function_ref<
void(OpBuilder &, Location)> scopeBuilder) {
1863 assert(scopeBuilder &&
"the builder callback for 'then' must be present");
1864 OpBuilder::InsertionGuard guard(builder);
1865 Region *scopeRegion = result.addRegion();
1866 builder.createBlock(scopeRegion);
1868 scopeBuilder(builder, result.location);
1871LogicalResult cir::ScopeOp::verify() {
1873 return emitOpError() <<
"cir.scope must not be empty since it should "
1874 "include at least an implicit cir.yield ";
1877 mlir::Block &lastBlock =
getRegion().back();
1878 if (lastBlock.empty() || !lastBlock.mightHaveTerminator() ||
1879 !lastBlock.getTerminator()->hasTrait<OpTrait::IsTerminator>())
1880 return emitOpError() <<
"last block of cir.scope must be terminated";
1884LogicalResult cir::ScopeOp::fold(FoldAdaptor ,
1885 SmallVectorImpl<OpFoldResult> &results) {
1890 if (block.getOperations().size() != 1)
1893 auto yield = dyn_cast<cir::YieldOp>(block.front());
1898 if (getNumResults() != 1 || yield.getNumOperands() != 1)
1901 results.push_back(yield.getOperand(0));
1910 for (mlir::Block &block : cleanupRegion) {
1911 for (mlir::Operation &op : block) {
1912 if (isa<cir::YieldOp, cir::LifetimeEndOp, cir::StackRestoreOp>(op))
1915 auto loadOp = dyn_cast<cir::LoadOp>(op);
1916 if (loadOp && loadOp.getResult().hasOneUse() &&
1917 isa<cir::StackRestoreOp>(*loadOp.getResult().getUsers().begin()))
1925LogicalResult cir::CleanupScopeOp::verify() {
1929 cir::CallOp mustTailCall;
1930 getBodyRegion().walk([&](cir::CallOp callOp) {
1931 if (!callOp.getMusttail())
1932 return WalkResult::advance();
1933 mustTailCall = callOp;
1934 return WalkResult::interrupt();
1942 InFlightDiagnostic diag =
1943 emitOpError(
"cleanup is not redundant before a return, so it cannot be "
1944 "skipped by a musttail call");
1945 diag.attachNote(mustTailCall.getLoc()) <<
"musttail call is here";
1949void cir::CleanupScopeOp::getSuccessorRegions(
1950 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1951 if (!point.isParent()) {
1952 regions.emplace_back(getOperation());
1957 regions.push_back(RegionSuccessor(&getBodyRegion()));
1958 regions.push_back(RegionSuccessor(&getCleanupRegion()));
1961LogicalResult cir::CleanupScopeOp::canonicalize(CleanupScopeOp op,
1962 PatternRewriter &rewriter) {
1963 auto isRegionTrivial = [](Region ®ion) {
1964 assert(!region.empty() &&
"CleanupScopeOp regions must not be empty");
1965 if (!region.hasOneBlock())
1967 Block &block = llvm::getSingleElement(region);
1968 return llvm::hasSingleElement(block) &&
1969 isa<cir::YieldOp>(llvm::getSingleElement(block));
1972 Region &body = op.getBodyRegion();
1973 Region &
cleanup = op.getCleanupRegion();
1977 if (op.getCleanupKind() == CleanupKind::EH && isRegionTrivial(body)) {
1978 rewriter.eraseOp(op);
1984 if (!isRegionTrivial(cleanup) || !body.hasOneBlock())
1987 Block &bodyBlock = body.front();
1988 if (!isa<cir::YieldOp>(bodyBlock.getTerminator()))
1991 Operation *yield = bodyBlock.getTerminator();
1992 rewriter.inlineBlockBefore(&bodyBlock, op);
1993 rewriter.eraseOp(yield);
1994 rewriter.eraseOp(op);
1998void cir::CleanupScopeOp::build(
1999 OpBuilder &builder, OperationState &result, CleanupKind cleanupKind,
2000 function_ref<
void(OpBuilder &, Location)> bodyBuilder,
2001 function_ref<
void(OpBuilder &, Location)> cleanupBuilder) {
2002 result.addAttribute(getCleanupKindAttrName(result.name),
2003 CleanupKindAttr::get(builder.getContext(), cleanupKind));
2005 OpBuilder::InsertionGuard guard(builder);
2008 Region *bodyRegion = result.addRegion();
2009 builder.createBlock(bodyRegion);
2011 bodyBuilder(builder, result.location);
2014 Region *cleanupRegion = result.addRegion();
2015 builder.createBlock(cleanupRegion);
2017 cleanupBuilder(builder, result.location);
2032LogicalResult cir::BrOp::canonicalize(BrOp op, PatternRewriter &rewriter) {
2033 Block *src = op->getBlock();
2034 Block *dst = op.getDest();
2041 if (src->getNumSuccessors() != 1 || dst->getSinglePredecessor() != src)
2046 if (isa<cir::LabelOp, cir::IndirectBrOp>(dst->front()))
2049 auto operands = op.getDestOperands();
2050 rewriter.eraseOp(op);
2051 rewriter.mergeBlocks(dst, src, operands);
2055mlir::SuccessorOperands cir::BrOp::getSuccessorOperands(
unsigned index) {
2056 assert(index == 0 &&
"invalid successor index");
2057 return mlir::SuccessorOperands(getDestOperandsMutable());
2068mlir::SuccessorOperands
2069cir::IndirectBrOp::getSuccessorOperands(
unsigned index) {
2070 assert(index < getNumSuccessors() &&
"invalid successor index");
2071 return mlir::SuccessorOperands(getSuccOperandsMutable()[index]);
2075 OpAsmParser &parser, Type &flagType,
2076 SmallVectorImpl<Block *> &succOperandBlocks,
2079 if (failed(parser.parseCommaSeparatedList(
2080 OpAsmParser::Delimiter::Square,
2082 Block *destination = nullptr;
2083 SmallVector<OpAsmParser::UnresolvedOperand> operands;
2084 SmallVector<Type> operandTypes;
2086 if (parser.parseSuccessor(destination).failed())
2089 if (succeeded(parser.parseOptionalLParen())) {
2090 if (failed(parser.parseOperandList(
2091 operands, OpAsmParser::Delimiter::None)) ||
2092 failed(parser.parseColonTypeList(operandTypes)) ||
2093 failed(parser.parseRParen()))
2096 succOperandBlocks.push_back(destination);
2097 succOperands.emplace_back(operands);
2098 succOperandsTypes.emplace_back(operandTypes);
2101 "successor blocks")))
2107 Type flagType, SuccessorRange succs,
2108 OperandRangeRange succOperands,
2109 const TypeRangeRange &succOperandsTypes) {
2112 llvm::zip(succs, succOperands),
2115 p.printSuccessorAndUseList(std::get<0>(i), std::get<1>(i));
2118 if (!succOperands.empty())
2127mlir::SuccessorOperands cir::BrCondOp::getSuccessorOperands(
unsigned index) {
2128 assert(index < getNumSuccessors() &&
"invalid successor index");
2129 return SuccessorOperands(index == 0 ? getDestOperandsTrueMutable()
2130 : getDestOperandsFalseMutable());
2134 if (IntegerAttr condAttr = dyn_cast_if_present<IntegerAttr>(operands.front()))
2135 return condAttr.getValue().isOne() ? getDestTrue() : getDestFalse();
2143void cir::CaseOp::getSuccessorRegions(
2144 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
2145 if (!point.isParent()) {
2146 regions.emplace_back(getOperation());
2149 regions.push_back(RegionSuccessor(&getCaseRegion()));
2152void cir::CaseOp::build(OpBuilder &builder, OperationState &result,
2153 ArrayAttr value, CaseOpKind
kind,
2154 OpBuilder::InsertPoint &insertPoint) {
2155 OpBuilder::InsertionGuard guardSwitch(builder);
2156 result.addAttribute(
"value", value);
2157 result.getOrAddProperties<Properties>().
kind =
2158 cir::CaseOpKindAttr::get(builder.getContext(),
kind);
2159 Region *caseRegion = result.addRegion();
2160 builder.createBlock(caseRegion);
2162 insertPoint = builder.saveInsertionPoint();
2169void cir::SwitchOp::getSuccessorRegions(
2170 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ion) {
2171 if (!point.isParent()) {
2172 region.emplace_back(getOperation());
2176 region.push_back(RegionSuccessor(&getBody()));
2179void cir::SwitchOp::build(OpBuilder &builder, OperationState &result,
2181 assert(switchBuilder &&
"the builder callback for regions must be present");
2182 OpBuilder::InsertionGuard guardSwitch(builder);
2183 Region *switchRegion = result.addRegion();
2184 builder.createBlock(switchRegion);
2185 result.addOperands({cond});
2186 switchBuilder(builder, result.location, result);
2190 walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
2192 if (isa<cir::SwitchOp>(op) && op != *
this)
2193 return WalkResult::skip();
2195 if (
auto caseOp = dyn_cast<cir::CaseOp>(op))
2196 cases.push_back(caseOp);
2198 return WalkResult::advance();
2203 collectCases(cases);
2205 if (getBody().empty())
2208 if (!isa<YieldOp>(getBody().front().back()))
2211 if (!llvm::all_of(getBody().front(),
2212 [](Operation &op) {
return isa<CaseOp, YieldOp>(op); }))
2215 return llvm::all_of(cases, [
this](CaseOp op) {
2216 return op->getParentOfType<SwitchOp>() == *
this;
2224void cir::SwitchFlatOp::build(OpBuilder &builder, OperationState &result,
2225 Value value, Block *defaultDestination,
2226 ValueRange defaultOperands,
2228 BlockRange caseDestinations,
2231 std::vector<mlir::Attribute> caseValuesAttrs;
2232 for (
const APInt &val : caseValues)
2233 caseValuesAttrs.push_back(cir::IntAttr::get(value.getType(), val));
2234 mlir::ArrayAttr attrs = ArrayAttr::get(builder.getContext(), caseValuesAttrs);
2236 build(builder, result, value, defaultOperands, caseOperands, attrs,
2237 defaultDestination, caseDestinations);
2243 OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues,
2244 SmallVectorImpl<Block *> &caseDestinations,
2248 if (failed(parser.parseLSquare()))
2250 if (succeeded(parser.parseOptionalRSquare()))
2254 auto parseCase = [&]() {
2256 if (failed(parser.parseInteger(value)))
2259 values.push_back(cir::IntAttr::get(flagType, value));
2264 if (parser.parseColon() || parser.parseSuccessor(destination))
2266 if (!parser.parseOptionalLParen()) {
2267 if (parser.parseOperandList(operands, OpAsmParser::Delimiter::None,
2269 parser.parseColonTypeList(operandTypes) || parser.parseRParen())
2272 caseDestinations.push_back(destination);
2273 caseOperands.emplace_back(operands);
2274 caseOperandTypes.emplace_back(operandTypes);
2277 if (failed(parser.parseCommaSeparatedList(parseCase)))
2280 caseValues = ArrayAttr::get(flagType.getContext(), values);
2282 return parser.parseRSquare();
2286 Type flagType, mlir::ArrayAttr caseValues,
2287 SuccessorRange caseDestinations,
2288 OperandRangeRange caseOperands,
2289 const TypeRangeRange &caseOperandTypes) {
2299 llvm::zip(caseValues, caseDestinations),
2302 mlir::Attribute a = std::get<0>(i);
2303 p << mlir::cast<cir::IntAttr>(a).getValue();
2305 p.printSuccessorAndUseList(std::get<1>(i), caseOperands[index++]);
2320 mlir::Attribute &valueAttr) {
2322 return parser.parseAttribute(valueAttr,
"value", attr);
2326 p.printAttribute(value);
2329mlir::LogicalResult cir::GlobalOp::verify() {
2332 if (mlir::isa<cir::FuncType>(getSymType()))
2333 return emitOpError(
"global type cannot be a function type");
2337 if (getInitialValue().has_value()) {
2343 if ((getStaticLocalGuard().has_value()) &&
2344 (!getCtorRegion().empty() || !getDtorRegion().empty()))
2346 "Cannot have a static-local global-op with a constructor or "
2347 "destructor, they require in-function initialization via LocalInitOp");
2353 if (getStaticLocalGuard().has_value() != getStaticLocalInfo().has_value())
2354 return emitOpError(
"'static_local_guard' and 'static_local_info' must be "
2355 "present together");
2358 if (getStaticLocalGuard().has_value())
2359 return emitOpError(
"cannot have both static local and tls references");
2361 return emitOpError(
"'tls_refs' only valid for tls");
2364 if (getAliasee().has_value()) {
2365 if (getInitialValue().has_value() || !getCtorRegion().empty() ||
2366 !getDtorRegion().empty())
2367 return emitOpError(
"global alias shall not have an initializer or "
2368 "constructor/destructor regions");
2377void cir::GlobalOp::build(
2378 OpBuilder &odsBuilder, OperationState &odsState, llvm::StringRef sym_name,
2379 mlir::Type sym_type,
bool isConstant,
2380 mlir::ptr::MemorySpaceAttrInterface addrSpace,
2381 cir::GlobalLinkageKind linkage,
2382 function_ref<
void(OpBuilder &, Location)> ctorBuilder,
2383 function_ref<
void(OpBuilder &, Location)> dtorBuilder) {
2384 odsState.addAttribute(getSymNameAttrName(odsState.name),
2385 odsBuilder.getStringAttr(sym_name));
2386 odsState.addAttribute(getSymTypeAttrName(odsState.name),
2387 mlir::TypeAttr::get(sym_type));
2388 auto &properties = odsState.getOrAddProperties<cir::GlobalOp::Properties>();
2389 properties.setConstant(isConstant);
2393 odsState.addAttribute(getAddrSpaceAttrName(odsState.name), addrSpace);
2395 cir::GlobalLinkageKindAttr linkageAttr =
2396 cir::GlobalLinkageKindAttr::get(odsBuilder.getContext(), linkage);
2397 odsState.addAttribute(getLinkageAttrName(odsState.name), linkageAttr);
2399 Region *ctorRegion = odsState.addRegion();
2401 odsBuilder.createBlock(ctorRegion);
2402 ctorBuilder(odsBuilder, odsState.location);
2405 Region *dtorRegion = odsState.addRegion();
2407 odsBuilder.createBlock(dtorRegion);
2408 dtorBuilder(odsBuilder, odsState.location);
2417void cir::GlobalOp::getSuccessorRegions(
2418 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
2420 if (!point.isParent()) {
2421 regions.emplace_back(getOperation());
2426 Region *ctorRegion = &this->getCtorRegion();
2427 if (ctorRegion->empty())
2428 ctorRegion =
nullptr;
2431 Region *dtorRegion = &this->getDtorRegion();
2432 if (dtorRegion->empty())
2433 dtorRegion =
nullptr;
2437 regions.push_back(RegionSuccessor(ctorRegion));
2439 regions.push_back(RegionSuccessor(dtorRegion));
2443 TypeAttr type, Attribute initAttr,
2444 mlir::Region &ctorRegion,
2445 mlir::Region &dtorRegion) {
2446 auto printType = [&]() { p <<
": " << type; };
2449 if (op.isDeclaration() || op.getAliasee()) {
2455 if (!ctorRegion.empty()) {
2459 p.printRegion(ctorRegion,
2468 if (!dtorRegion.empty()) {
2470 p.printRegion(dtorRegion,
2478 Attribute &initialValueAttr,
2479 mlir::Region &ctorRegion,
2480 mlir::Region &dtorRegion) {
2482 if (parser.parseOptionalEqual().failed()) {
2485 if (parser.parseColonType(opTy))
2490 if (!parser.parseOptionalKeyword(
"ctor")) {
2491 if (parser.parseColonType(opTy))
2493 auto parseLoc = parser.getCurrentLocation();
2494 if (parser.parseRegion(ctorRegion, {}, {}))
2505 assert(mlir::isa<mlir::TypedAttr>(initialValueAttr) &&
2506 "Non-typed attrs shouldn't appear here.");
2507 opTy = mlir::cast<mlir::TypedAttr>(initialValueAttr).getType();
2512 if (!parser.parseOptionalKeyword(
"dtor")) {
2513 auto parseLoc = parser.getCurrentLocation();
2514 if (parser.parseRegion(dtorRegion, {}, {}))
2521 typeAttr = TypeAttr::get(opTy);
2530cir::GetGlobalOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2533 mlir::Operation *op =
2534 symbolTable.lookupNearestSymbolFrom(*
this, getNameAttr());
2535 if (op ==
nullptr || !(isa<GlobalOp>(op) || isa<FuncOp>(op)))
2536 return emitOpError(
"'")
2538 <<
"' does not reference a valid cir.global or cir.func";
2541 mlir::ptr::MemorySpaceAttrInterface symAddrSpaceAttr{};
2542 if (
auto g = dyn_cast<GlobalOp>(op)) {
2543 symTy = g.getSymType();
2544 symAddrSpaceAttr = g.getAddrSpaceAttr();
2547 if (getTls() && !g.getTlsModel())
2548 return emitOpError(
"access to global not marked thread local");
2553 bool getGlobalIsStaticLocal = getStaticLocal();
2554 bool globalIsStaticLocal = g.getStaticLocalGuard().has_value();
2555 if (getGlobalIsStaticLocal != globalIsStaticLocal &&
2556 !getOperation()->getParentOfType<cir::GlobalOp>())
2557 return emitOpError(
"static_local attribute mismatch");
2558 }
else if (
auto f = dyn_cast<FuncOp>(op)) {
2559 symTy = f.getFunctionType();
2561 llvm_unreachable(
"Unexpected operation for GetGlobalOp");
2564 auto resultType = dyn_cast<PointerType>(getAddr().
getType());
2565 if (!resultType || symTy != resultType.getPointee())
2566 return emitOpError(
"result type pointee type '")
2567 << resultType.getPointee() <<
"' does not match type " << symTy
2568 <<
" of the global @" <<
getName();
2570 if (symAddrSpaceAttr != resultType.getAddrSpace()) {
2571 return emitOpError()
2572 <<
"result type address space does not match the address "
2573 "space of the global @"
2585cir::VTableAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2591 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*
this, getNameAttr());
2593 return emitOpError(
"'")
2594 <<
name <<
"' does not reference a valid cir.global";
2595 std::optional<mlir::Attribute> init = op.getInitialValue();
2598 if (!isa<cir::VTableAttr>(*init))
2599 return emitOpError(
"Expected #cir.vtable in initializer for global '")
2609cir::VTTAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2618 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*
this, getNameAttr());
2620 return emitOpError(
"'")
2621 <<
name <<
"' does not reference a valid cir.global";
2622 std::optional<mlir::Attribute> init = op.getInitialValue();
2625 if (!isa<cir::ConstArrayAttr>(*init))
2627 "Expected constant array in initializer for global VTT '")
2632LogicalResult cir::VTTAddrPointOp::verify() {
2634 if (
getName() && getSymAddr())
2635 return emitOpError(
"should use either a symbol or value, but not both");
2641 mlir::Type resultType = getAddr().getType();
2642 mlir::Type resTy = cir::PointerType::get(
2643 cir::PointerType::get(cir::VoidType::get(getContext())));
2645 if (resultType != resTy)
2646 return emitOpError(
"result type must be ")
2647 << resTy <<
", but provided result type is " << resultType;
2659void cir::FuncOp::build(OpBuilder &builder, OperationState &result,
2660 StringRef name, FuncType type,
2661 GlobalLinkageKind linkage, CallingConv callingConv) {
2663 result.addAttribute(getSymNameAttrName(result.name),
2664 builder.getStringAttr(name));
2665 result.addAttribute(getFunctionTypeAttrName(result.name),
2666 TypeAttr::get(type));
2667 result.addAttribute(
2669 GlobalLinkageKindAttr::get(builder.getContext(), linkage));
2670 result.addAttribute(getCallingConvAttrName(result.name),
2671 CallingConvAttr::get(builder.getContext(), callingConv));
2679cir::AnnotationAttr::verify(function_ref<InFlightDiagnostic()> emitError,
2680 mlir::StringAttr name, mlir::ArrayAttr args) {
2683 for (mlir::Attribute arg : args) {
2684 if (!isa<mlir::StringAttr, mlir::IntegerAttr>(arg))
2685 return emitError() <<
"annotation args must be StringAttr or IntegerAttr,"
2691ParseResult cir::FuncOp::parse(OpAsmParser &parser, OperationState &state) {
2692 llvm::SMLoc loc = parser.getCurrentLocation();
2693 mlir::Builder &builder = parser.getBuilder();
2695 mlir::StringAttr builtinNameAttr = getBuiltinAttrName(state.name);
2696 mlir::StringAttr coroutineNameAttr = getCoroutineAttrName(state.name);
2697 mlir::StringAttr inlineKindNameAttr = getInlineKindAttrName(state.name);
2698 mlir::StringAttr lambdaNameAttr = getLambdaAttrName(state.name);
2699 mlir::StringAttr noProtoNameAttr = getNoProtoAttrName(state.name);
2700 mlir::StringAttr comdatNameAttr = getComdatAttrName(state.name);
2701 mlir::StringAttr alignmentNameAttr = getAlignmentAttrName(state.name);
2702 mlir::StringAttr preferredAlignmentNameAttr =
2703 getPreferredAlignmentAttrName(state.name);
2704 mlir::StringAttr visNameAttr = getSymVisibilityAttrName(state.name);
2705 mlir::StringAttr dsoLocalNameAttr = getDsoLocalAttrName(state.name);
2706 mlir::StringAttr funcInfoNameAttr = getFuncInfoAttrName(state.name);
2708 if (::mlir::succeeded(parser.parseOptionalKeyword(builtinNameAttr.strref())))
2709 state.addAttribute(builtinNameAttr, parser.getBuilder().getUnitAttr());
2710 if (::mlir::succeeded(
2711 parser.parseOptionalKeyword(coroutineNameAttr.strref())))
2712 state.addAttribute(coroutineNameAttr, parser.getBuilder().getUnitAttr());
2715 cir::InlineKindAttr inlineKindAttr;
2719 state.addAttribute(inlineKindNameAttr, inlineKindAttr);
2721 if (::mlir::succeeded(parser.parseOptionalKeyword(lambdaNameAttr.strref())))
2722 state.addAttribute(lambdaNameAttr, parser.getBuilder().getUnitAttr());
2723 if (parser.parseOptionalKeyword(noProtoNameAttr).succeeded())
2724 state.addAttribute(noProtoNameAttr, parser.getBuilder().getUnitAttr());
2726 if (parser.parseOptionalKeyword(comdatNameAttr).succeeded()) {
2727 std::string comdatKey;
2728 if (mlir::succeeded(parser.parseOptionalLParen())) {
2729 if (parser.parseString(&comdatKey).failed())
2731 if (parser.parseRParen().failed())
2734 state.addAttribute(comdatNameAttr,
2735 parser.getBuilder().getStringAttr(comdatKey));
2738 auto parseAlignmentBody = [&](int64_t &value) {
2739 if (parser.parseLParen().failed() || parser.parseInteger(value).failed() ||
2740 parser.parseRParen().failed())
2744 return static_cast<LogicalResult
>(parser.emitError(
2745 loc,
"function alignment must be a positive integer"));
2750 if (parser.parseOptionalKeyword(alignmentNameAttr).succeeded()) {
2752 if (parseAlignmentBody(value).failed())
2754 state.addAttribute(alignmentNameAttr, builder.getI64IntegerAttr(value));
2757 if (parser.parseOptionalKeyword(preferredAlignmentNameAttr).succeeded()) {
2759 if (parseAlignmentBody(value).failed())
2761 state.addAttribute(preferredAlignmentNameAttr,
2762 builder.getI64IntegerAttr(value));
2767 GlobalLinkageKindAttr::get(
2768 parser.getContext(),
2770 parser, GlobalLinkageKind::ExternalLinkage)));
2772 ::llvm::StringRef visAttrStr;
2773 if (parser.parseOptionalKeyword(&visAttrStr, {
"private",
"public",
"nested"})
2775 state.addAttribute(visNameAttr,
2776 parser.getBuilder().getStringAttr(visAttrStr));
2779 state.getOrAddProperties<cir::FuncOp::Properties>().global_visibility =
2782 if (parser.parseOptionalKeyword(dsoLocalNameAttr).succeeded())
2783 state.addAttribute(dsoLocalNameAttr, parser.getBuilder().getUnitAttr());
2785 StringAttr nameAttr;
2786 if (parser.parseSymbolName(nameAttr, getSymNameAttrName(state.name),
2792 bool isVariadic =
false;
2793 if (function_interface_impl::parseFunctionSignatureWithArguments(
2794 parser,
true, arguments, isVariadic, resultTypes,
2799 bool argAttrsEmpty =
true;
2800 for (OpAsmParser::Argument &arg : arguments) {
2801 argTypes.push_back(
arg.type);
2805 argAttrs.push_back(
arg.attrs);
2807 argAttrsEmpty =
false;
2811 if (resultTypes.size() > 1 || resultAttrs.size() > 1)
2812 return parser.emitError(
2813 loc,
"functions with multiple return types are not supported");
2815 mlir::Type returnType =
2816 (resultTypes.empty() ? cir::VoidType::get(builder.getContext())
2817 : resultTypes.front());
2819 cir::FuncType fnType =
2820 cir::FuncType::getChecked([&]() {
return parser.emitError(loc); },
2821 argTypes, returnType, isVariadic);
2825 state.addAttribute(getFunctionTypeAttrName(state.name),
2826 TypeAttr::get(fnType));
2828 if (!resultAttrs.empty() && resultAttrs[0])
2830 getResAttrsAttrName(state.name),
2831 mlir::ArrayAttr::get(parser.getContext(), {resultAttrs[0]}));
2834 state.addAttribute(getArgAttrsAttrName(state.name),
2835 mlir::ArrayAttr::get(parser.getContext(), argAttrs));
2837 bool hasAlias =
false;
2838 mlir::StringAttr aliaseeNameAttr = getAliaseeAttrName(state.name);
2839 if (parser.parseOptionalKeyword(
"alias").succeeded()) {
2840 if (parser.parseLParen().failed())
2842 mlir::StringAttr aliaseeAttr;
2843 if (parser.parseOptionalSymbolName(aliaseeAttr).failed())
2845 state.addAttribute(aliaseeNameAttr, FlatSymbolRefAttr::get(aliaseeAttr));
2846 if (parser.parseRParen().failed())
2851 mlir::StringAttr personalityNameAttr = getPersonalityAttrName(state.name);
2852 if (parser.parseOptionalKeyword(
"personality").succeeded()) {
2853 if (parser.parseLParen().failed())
2855 mlir::StringAttr personalityAttr;
2856 if (parser.parseOptionalSymbolName(personalityAttr).failed())
2858 state.addAttribute(personalityNameAttr,
2859 FlatSymbolRefAttr::get(personalityAttr));
2860 if (parser.parseRParen().failed())
2865 mlir::StringAttr callConvNameAttr = getCallingConvAttrName(state.name);
2866 cir::CallingConv callConv = cir::CallingConv::C;
2867 if (parser.parseOptionalKeyword(
"cc").succeeded()) {
2868 if (parser.parseLParen().failed())
2871 return parser.emitError(loc) <<
"unknown calling convention";
2872 if (parser.parseRParen().failed())
2875 state.addAttribute(callConvNameAttr,
2876 cir::CallingConvAttr::get(parser.getContext(), callConv));
2878 auto parseGlobalDtorCtor =
2879 [&](StringRef keyword,
2880 llvm::function_ref<void(std::optional<int> prio)> createAttr)
2881 -> mlir::LogicalResult {
2882 if (mlir::succeeded(parser.parseOptionalKeyword(keyword))) {
2883 std::optional<int> priority;
2884 if (mlir::succeeded(parser.parseOptionalLParen())) {
2885 auto parsedPriority = mlir::FieldParser<int>::parse(parser);
2886 if (mlir::failed(parsedPriority))
2887 return parser.emitError(parser.getCurrentLocation(),
2888 "failed to parse 'priority', of type 'int'");
2889 priority = parsedPriority.value_or(
int());
2891 if (parser.parseRParen())
2894 createAttr(priority);
2900 if (parser.parseOptionalKeyword(
"func_info").succeeded()) {
2901 if (parser.parseLess().failed())
2904 llvm::SMLoc attrLoc = parser.getCurrentLocation();
2905 mlir::Attribute
attr;
2906 if (parser.parseAttribute(attr).failed())
2908 if (!mlir::isa<cir::CXXCtorAttr, cir::CXXDtorAttr, cir::CXXAssignAttr,
2909 cir::FuncIdentityAttr>(attr))
2910 return parser.emitError(attrLoc,
2911 "expected a function info attribute, got ")
2913 state.addAttribute(funcInfoNameAttr, attr);
2915 if (parser.parseGreater().failed())
2919 if (parseGlobalDtorCtor(
"global_ctor", [&](std::optional<int> priority) {
2920 mlir::IntegerAttr globalCtorPriorityAttr =
2921 builder.getI32IntegerAttr(priority.value_or(65535));
2922 state.addAttribute(getGlobalCtorPriorityAttrName(state.name),
2923 globalCtorPriorityAttr);
2927 if (parseGlobalDtorCtor(
"global_dtor", [&](std::optional<int> priority) {
2928 mlir::IntegerAttr globalDtorPriorityAttr =
2929 builder.getI32IntegerAttr(priority.value_or(65535));
2930 state.addAttribute(getGlobalDtorPriorityAttrName(state.name),
2931 globalDtorPriorityAttr);
2936 mlir::StringAttr annotationsNameAttr = getAnnotationsAttrName(state.name);
2937 mlir::ArrayAttr annotationsAttr;
2938 if (parser.parseOptionalAttribute(annotationsAttr).has_value() &&
2940 state.addAttribute(annotationsNameAttr, annotationsAttr);
2943 NamedAttrList parsedAttrs;
2944 llvm::SMLoc attrsLoc = parser.getCurrentLocation();
2945 if (parser.parseOptionalAttrDictWithKeyword(parsedAttrs))
2951 for (StringRef disallowed : cir::FuncOp::getAttributeNames()) {
2952 if (disallowed == CIRDialect::getMemoryEffectsAttrName())
2954 if (parsedAttrs.get(disallowed))
2955 return parser.emitError(loc,
"attribute '")
2957 <<
"' should not be specified in the explicit attribute list";
2963 state.attributes.append(parsedAttrs);
2966 auto *body = state.addRegion();
2967 OptionalParseResult parseResult = parser.parseOptionalRegion(
2968 *body, arguments,
false);
2969 if (parseResult.has_value()) {
2971 return parser.emitError(loc,
"function alias shall not have a body");
2972 if (failed(*parseResult))
2976 return parser.emitError(loc,
"expected non-empty function body");
2985bool cir::FuncOp::isDeclaration() {
2988 std::optional<StringRef> aliasee = getAliasee();
2990 return getFunctionBody().empty();
2996bool cir::FuncOp::isCXXSpecialMemberFunction() {
2999 mlir::Attribute
attr = getFuncInfoAttr();
3000 return attr && mlir::isa<CXXCtorAttr, CXXDtorAttr, CXXAssignAttr>(attr);
3003bool cir::FuncOp::isCxxConstructor() {
3004 auto attr = getFuncInfoAttr();
3005 return attr && dyn_cast<CXXCtorAttr>(attr);
3008bool cir::FuncOp::isCxxDestructor() {
3009 auto attr = getFuncInfoAttr();
3010 return attr && dyn_cast<CXXDtorAttr>(attr);
3013bool cir::FuncOp::isCxxSpecialAssignment() {
3014 auto attr = getFuncInfoAttr();
3015 return attr && dyn_cast<CXXAssignAttr>(attr);
3018std::optional<CtorKind> cir::FuncOp::getCxxConstructorKind() {
3019 mlir::Attribute
attr = getFuncInfoAttr();
3021 if (
auto ctor = dyn_cast<CXXCtorAttr>(attr))
3022 return ctor.getCtorKind();
3024 return std::nullopt;
3027std::optional<AssignKind> cir::FuncOp::getCxxSpecialAssignKind() {
3028 mlir::Attribute
attr = getFuncInfoAttr();
3030 if (
auto assign = dyn_cast<CXXAssignAttr>(attr))
3031 return assign.getAssignKind();
3033 return std::nullopt;
3036bool cir::FuncOp::isCxxTrivialMemberFunction() {
3037 mlir::Attribute
attr = getFuncInfoAttr();
3039 if (
auto ctor = dyn_cast<CXXCtorAttr>(attr))
3040 return ctor.getIsTrivial();
3041 if (
auto dtor = dyn_cast<CXXDtorAttr>(attr))
3042 return dtor.getIsTrivial();
3043 if (
auto assign = dyn_cast<CXXAssignAttr>(attr))
3044 return assign.getIsTrivial();
3049mlir::Region *cir::FuncOp::getCallableRegion() {
3055void cir::FuncOp::print(OpAsmPrinter &p) {
3070 if (std::optional<StringRef> comdatKey = getComdat()) {
3072 if (!comdatKey->empty())
3073 p <<
"(\"" << *comdatKey <<
"\")";
3077 p <<
" alignment(" << *getAlignment() <<
')';
3079 if (getPreferredAlignment())
3080 p <<
" preferred_alignment(" << *getPreferredAlignment() <<
')';
3082 if (getLinkage() != GlobalLinkageKind::ExternalLinkage)
3083 p <<
' ' << stringifyGlobalLinkageKind(getLinkage());
3085 mlir::SymbolTable::Visibility vis = getVisibility();
3086 if (vis != mlir::SymbolTable::Visibility::Public)
3089 if (getGlobalVisibility() != cir::VisibilityKind::Default)
3090 p <<
' ' << stringifyVisibilityKind(getGlobalVisibility());
3096 p.printSymbolName(getSymName());
3097 cir::FuncType fnType = getFunctionType();
3098 function_interface_impl::printFunctionSignature(
3099 p, *
this, fnType.getInputs(), fnType.isVarArg(), fnType.getReturnTypes());
3101 if (std::optional<StringRef> aliaseeName = getAliasee()) {
3103 p.printSymbolName(*aliaseeName);
3107 if (getCallingConv() != cir::CallingConv::C) {
3109 p << stringifyCallingConv(getCallingConv());
3113 if (std::optional<StringRef> personalityName = getPersonality()) {
3114 p <<
" personality(";
3115 p.printSymbolName(*personalityName);
3119 if (mlir::Attribute funcInfo = getFuncInfoAttr()) {
3121 p.printAttribute(funcInfo);
3125 if (
auto globalCtorPriority = getGlobalCtorPriority()) {
3126 p <<
" global_ctor";
3127 if (globalCtorPriority.value() != 65535)
3128 p <<
"(" << globalCtorPriority.value() <<
")";
3131 if (
auto globalDtorPriority = getGlobalDtorPriority()) {
3132 p <<
" global_dtor";
3133 if (globalDtorPriority.value() != 65535)
3134 p <<
"(" << globalDtorPriority.value() <<
")";
3137 if (mlir::ArrayAttr annotations = getAnnotationsAttr()) {
3139 p.printAttribute(annotations);
3145 for (llvm::StringRef name : cir::FuncOp::getAttributeNames())
3146 if (name != CIRDialect::getMemoryEffectsAttrName())
3147 elidedAttrs.push_back(name);
3148 function_interface_impl::printFunctionAttributes(p, *
this, elidedAttrs);
3151 Region &body = getOperation()->getRegion(0);
3152 if (!body.empty()) {
3154 p.printRegion(body,
false,
3159mlir::LogicalResult cir::FuncOp::verify() {
3161 if (!isDeclaration() && getCoroutine()) {
3162 bool foundAwait =
false;
3163 int coroBodyCount = 0;
3164 this->walk([&](Operation *op) {
3165 if (
auto await = dyn_cast<AwaitOp>(op)) {
3167 }
else if (isa<CoroBodyOp>(op)) {
3169 if (coroBodyCount > 1) {
3170 return mlir::WalkResult::interrupt();
3173 return mlir::WalkResult::advance();
3176 return emitOpError()
3177 <<
"coroutine body must use at least one cir.await op";
3178 if (coroBodyCount != 1)
3179 return emitOpError()
3180 <<
"coroutine function must have exactly one cir.body op";
3183 llvm::SmallSet<llvm::StringRef, 16> labels;
3184 llvm::SmallSet<llvm::StringRef, 16> gotos;
3185 llvm::SmallSet<llvm::StringRef, 16> blockAddresses;
3186 bool invalidBlockAddress =
false;
3187 getOperation()->walk([&](mlir::Operation *op) {
3188 if (
auto lab = dyn_cast<cir::LabelOp>(op)) {
3189 labels.insert(lab.getLabel());
3190 }
else if (
auto goTo = dyn_cast<cir::GotoOp>(op)) {
3191 gotos.insert(goTo.getLabel());
3192 }
else if (
auto blkAdd = dyn_cast<cir::BlockAddressOp>(op)) {
3193 if (blkAdd.getBlockAddrInfoAttr().getFunc().getAttr() != getSymName()) {
3195 invalidBlockAddress =
true;
3196 return mlir::WalkResult::interrupt();
3198 blockAddresses.insert(blkAdd.getBlockAddrInfoAttr().getLabel());
3200 return mlir::WalkResult::advance();
3203 if (invalidBlockAddress)
3204 return emitOpError() <<
"blockaddress references a different function";
3206 llvm::SmallSet<llvm::StringRef, 16> mismatched;
3207 if (!labels.empty() || !gotos.empty()) {
3208 mismatched = llvm::set_difference(gotos, labels);
3210 if (!mismatched.empty())
3211 return emitOpError() <<
"goto/label mismatch";
3216 if (!labels.empty() || !blockAddresses.empty()) {
3217 mismatched = llvm::set_difference(blockAddresses, labels);
3219 if (!mismatched.empty())
3220 return emitOpError()
3221 <<
"expects an existing label target in the referenced function";
3235LogicalResult cir::AddOp::verify() {
3236 if (getSaturated() && (getNoSignedWrap() || getNoUnsignedWrap()))
3237 return emitOpError()
3238 <<
"the nsw/nuw flags and the saturated flag are mutually exclusive";
3239 return mlir::success();
3242LogicalResult cir::SubOp::verify() {
3243 if (getSaturated() && (getNoSignedWrap() || getNoUnsignedWrap()))
3244 return emitOpError()
3245 <<
"the nsw/nuw flags and the saturated flag are mutually exclusive";
3246 return mlir::success();
3258void cir::TernaryOp::getSuccessorRegions(
3259 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
3261 if (!point.isParent()) {
3262 regions.emplace_back(getOperation());
3268 regions.push_back(RegionSuccessor(&getTrueRegion()));
3269 regions.push_back(RegionSuccessor(&getFalseRegion()));
3272void cir::TernaryOp::build(
3273 OpBuilder &builder, OperationState &result,
Value cond,
3274 function_ref<
void(OpBuilder &, Location)> trueBuilder,
3275 function_ref<
void(OpBuilder &, Location)> falseBuilder) {
3276 result.addOperands(cond);
3277 OpBuilder::InsertionGuard guard(builder);
3278 Region *trueRegion = result.addRegion();
3279 builder.createBlock(trueRegion);
3280 trueBuilder(builder, result.location);
3281 Region *falseRegion = result.addRegion();
3282 builder.createBlock(falseRegion);
3283 falseBuilder(builder, result.location);
3288 if (trueRegion->back().mightHaveTerminator())
3289 yield = dyn_cast_or_null<cir::YieldOp>(trueRegion->back().getTerminator());
3290 if (!yield && falseRegion->back().mightHaveTerminator())
3291 yield = dyn_cast_or_null<cir::YieldOp>(falseRegion->back().getTerminator());
3293 assert((!yield || yield.getNumOperands() <= 1) &&
3294 "expected zero or one result type");
3295 if (yield && yield.getNumOperands() == 1)
3296 result.addTypes(TypeRange{yield.getOperandTypes().front()});
3303OpFoldResult cir::SelectOp::fold(FoldAdaptor adaptor) {
3304 mlir::Attribute
condition = adaptor.getCondition();
3306 bool conditionValue = mlir::cast<cir::BoolAttr>(
condition).getValue();
3307 return conditionValue ? getTrueValue() : getFalseValue();
3311 mlir::Attribute trueValue = adaptor.getTrueValue();
3312 mlir::Attribute falseValue = adaptor.getFalseValue();
3313 if (trueValue == falseValue)
3315 if (getTrueValue() == getFalseValue())
3316 return getTrueValue();
3321LogicalResult cir::SelectOp::verify() {
3323 auto condTy = dyn_cast<cir::VectorType>(getCondition().
getType());
3330 if (!isa<cir::VectorType>(getTrueValue().
getType()) ||
3331 !isa<cir::VectorType>(getFalseValue().
getType())) {
3332 return emitOpError()
3333 <<
"expected both true and false operands to be vector types "
3334 "when the condition is a vector boolean type";
3343LogicalResult cir::ShiftOp::verify() {
3344 mlir::Operation *op = getOperation();
3345 auto op0VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(0).getType());
3346 auto op1VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(1).getType());
3347 if (!op0VecTy ^ !op1VecTy)
3348 return emitOpError() <<
"input types cannot be one vector and one scalar";
3351 if (op0VecTy.getSize() != op1VecTy.getSize())
3352 return emitOpError() <<
"input vector types must have the same size";
3354 auto opResultTy = mlir::dyn_cast<cir::VectorType>(
getType());
3356 return emitOpError() <<
"the type of the result must be a vector "
3357 <<
"if it is vector shift";
3359 auto op0VecEleTy = mlir::cast<cir::IntType>(op0VecTy.getElementType());
3360 auto op1VecEleTy = mlir::cast<cir::IntType>(op1VecTy.getElementType());
3361 if (op0VecEleTy.getWidth() != op1VecEleTy.getWidth())
3362 return emitOpError()
3363 <<
"vector operands do not have the same elements sizes";
3365 auto resVecEleTy = mlir::cast<cir::IntType>(opResultTy.getElementType());
3366 if (op0VecEleTy.getWidth() != resVecEleTy.getWidth())
3367 return emitOpError() <<
"vector operands and result type do not have the "
3368 "same elements sizes";
3371 return mlir::success();
3378LogicalResult cir::LabelOp::verify() {
3379 mlir::Operation *op = getOperation();
3380 mlir::Block *blk = op->getBlock();
3381 if (&blk->front() != op)
3382 return emitError() <<
"must be the first operation in a block";
3384 return mlir::success();
3391OpFoldResult cir::IncOp::fold(FoldAdaptor adaptor) {
3392 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3393 return adaptor.getInput();
3401OpFoldResult cir::DecOp::fold(FoldAdaptor adaptor) {
3402 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3403 return adaptor.getInput();
3411OpFoldResult cir::MinusOp::fold(FoldAdaptor adaptor) {
3412 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3413 return adaptor.getInput();
3418 mlir::dyn_cast_if_present<cir::IntAttr>(adaptor.getInput())) {
3419 APInt val = intAttr.getValue();
3421 return cir::IntAttr::get(
getType(), val);
3431OpFoldResult cir::FNegOp::fold(FoldAdaptor adaptor) {
3432 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3433 return adaptor.getInput();
3437 mlir::dyn_cast_if_present<cir::FPAttr>(adaptor.getInput())) {
3438 APFloat val = fpAttr.getValue();
3440 return cir::FPAttr::get(
getType(), val);
3450OpFoldResult cir::NotOp::fold(FoldAdaptor adaptor) {
3451 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3452 return adaptor.getInput();
3457 if (mlir::Attribute attr = adaptor.getInput()) {
3458 if (
auto intAttr = mlir::dyn_cast<cir::IntAttr>(attr)) {
3459 APInt val = intAttr.getValue();
3461 return cir::IntAttr::get(
getType(), val);
3463 if (
auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr))
3464 return cir::BoolAttr::get(getContext(), !boolAttr.getValue());
3475 mlir::Type resultTy) {
3478 mlir::Type inputMemberTy;
3479 mlir::Type resultMemberTy;
3480 if (mlir::isa<cir::DataMemberType>(src.getType())) {
3482 mlir::cast<cir::DataMemberType>(src.getType()).getMemberTy();
3483 resultMemberTy = mlir::cast<cir::DataMemberType>(resultTy).getMemberTy();
3486 if (inputMemberTy != resultMemberTy)
3487 return op->emitOpError()
3488 <<
"member types of the operand and the result do not match";
3490 return mlir::success();
3493LogicalResult cir::BaseDataMemberOp::verify() {
3497LogicalResult cir::DerivedDataMemberOp::verify() {
3505LogicalResult cir::BaseMethodOp::verify() {
3509LogicalResult cir::DerivedMethodOp::verify() {
3517void cir::AwaitOp::build(OpBuilder &builder, OperationState &result,
3521 result.addAttribute(getKindAttrName(result.name),
3522 cir::AwaitKindAttr::get(builder.getContext(),
kind));
3524 OpBuilder::InsertionGuard guard(builder);
3525 Region *readyRegion = result.addRegion();
3526 builder.createBlock(readyRegion);
3527 readyBuilder(builder, result.location);
3531 OpBuilder::InsertionGuard guard(builder);
3532 Region *suspendRegion = result.addRegion();
3533 builder.createBlock(suspendRegion);
3534 suspendBuilder(builder, result.location);
3538 OpBuilder::InsertionGuard guard(builder);
3539 Region *resumeRegion = result.addRegion();
3540 builder.createBlock(resumeRegion);
3541 resumeBuilder(builder, result.location);
3545void cir::AwaitOp::getSuccessorRegions(
3546 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
3547 assert(point.isParent() || point.getTerminatorPredecessorOrNull());
3550 if (point.isParent()) {
3551 regions.emplace_back(&getReady());
3555 mlir::Region *parentRegion =
3556 point.getTerminatorPredecessorOrNull()->getParentRegion();
3565 if (&getReady() == parentRegion) {
3566 regions.emplace_back(&getResume());
3567 regions.emplace_back(&getSuspend());
3572 regions.emplace_back(getOperation());
3575LogicalResult cir::AwaitOp::verify() {
3576 if (!isa<ConditionOp>(this->getReady().back().getTerminator()))
3577 return emitOpError(
"ready region must end with cir.condition");
3585void cir::CoroBodyOp::getSuccessorRegions(
3586 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
3587 if (!point.isParent()) {
3588 regions.emplace_back(getOperation());
3592 regions.push_back(RegionSuccessor(&getBody()));
3595LogicalResult cir::CoroBodyOp::verify() {
3596 if (!getOperation()->getParentOfType<FuncOp>().getCoroutine())
3597 return emitOpError(
"enclosing function must be a coroutine");
3601void cir::CoroBodyOp::build(OpBuilder &builder, OperationState &result,
3603 assert(bodyBuilder &&
3604 "the builder callback for 'CoroBodyOp' must be present");
3605 OpBuilder::InsertionGuard guard(builder);
3607 Region *bodyRegion = result.addRegion();
3608 builder.createBlock(bodyRegion);
3609 bodyBuilder(builder, result.location);
3620 mlir::Type srcType, mlir::Type dstType) {
3621 printer.printType(srcType);
3622 if (srcType != dstType) {
3624 printer.printType(dstType);
3629 mlir::Type &srcType,
3630 mlir::Type &dstType) {
3631 if (parser.parseType(srcType))
3632 return mlir::failure();
3633 if (parser.parseOptionalComma().succeeded()) {
3634 if (parser.parseType(dstType))
3635 return mlir::failure();
3639 return mlir::success();
3642LogicalResult cir::CopyOp::verify() {
3647 if (!
getType().getPointee().hasTrait<DataLayoutTypeInterface::Trait>())
3648 return emitError() <<
"missing data layout for pointee type";
3650 if (getSkipTailPadding() &&
3651 !mlir::isa<cir::RecordType>(
getType().getPointee()))
3653 <<
"skip_tail_padding is only valid for record pointee types";
3655 return mlir::success();
3662LogicalResult cir::PtrMaskOp::verify() {
3663 mlir::DataLayout layout = mlir::DataLayout::closest(*
this);
3664 std::optional<uint64_t> indexWidth =
3665 layout.getTypeIndexBitwidth(getPtr().
getType());
3667 return emitOpError() <<
"pointer has no index width";
3669 uint64_t maskWidth = getMask().getType().getWidth();
3670 if (maskWidth != *indexWidth)
3671 return emitOpError() <<
"mask width " << maskWidth
3672 <<
" must equal the pointer index width "
3675 return mlir::success();
3682LogicalResult cir::GetRuntimeMemberOp::verify() {
3683 cir::DataMemberType memberPtrTy = getMember().getType();
3685 if (getAddr().
getType().getPointee() != memberPtrTy.getClassTy())
3686 return emitError() <<
"record type does not match the member pointer type";
3687 if (
getType().getPointee() != memberPtrTy.getMemberTy())
3688 return emitError() <<
"result type does not match the member pointer type";
3689 return mlir::success();
3696LogicalResult cir::GetMethodOp::verify() {
3697 cir::MethodType methodTy = getMethod().getType();
3700 cir::PointerType objectPtrTy = getObject().getType();
3701 mlir::Type objectTy = objectPtrTy.getPointee();
3703 if (methodTy.getClassTy() != objectTy)
3704 return emitError() <<
"method class type and object type do not match";
3707 auto calleeTy = mlir::cast<cir::FuncType>(getCallee().
getType().getPointee());
3708 cir::FuncType methodFuncTy = methodTy.getMemberFuncTy();
3715 if (methodFuncTy.getReturnType() != calleeTy.getReturnType())
3717 <<
"method return type and callee return type do not match";
3722 if (calleeArgsTy.empty())
3723 return emitError() <<
"callee parameter list lacks receiver object ptr";
3725 auto calleeThisArgPtrTy = mlir::dyn_cast<cir::PointerType>(calleeArgsTy[0]);
3726 if (!calleeThisArgPtrTy ||
3727 !mlir::isa<cir::VoidType>(calleeThisArgPtrTy.getPointee())) {
3729 <<
"the first parameter of callee must be a void pointer";
3732 if (calleeArgsTy.size() != methodFuncArgsTy.size())
3733 return emitError() <<
"callee and method parameter counts do not match";
3735 if (calleeArgsTy.size() > 1 &&
3736 calleeArgsTy.slice(1) != methodFuncArgsTy.slice(1))
3738 <<
"callee parameters and method parameters do not match";
3740 return mlir::success();
3751LogicalResult cir::GetMemberOp::verify() {
3752 const auto recordTy = dyn_cast<RecordType>(getAddrTy().getPointee());
3754 return emitError() <<
"expected pointer to a record type";
3756 if (recordTy.getMembers().size() <=
getIndex())
3757 return emitError() <<
"member index out of bounds";
3761 return emitError() <<
"member owns no storage to point at";
3763 if (pointeeTy !=
getType().getPointee())
3764 return emitError() <<
"member type mismatch";
3766 return mlir::success();
3773LogicalResult cir::ExtractMemberOp::verify() {
3774 if (mlir::isa<cir::UnionType>(getRecord().
getType()))
3776 <<
"cir.extract_member currently does not support unions";
3777 auto structTy = mlir::cast<cir::StructType>(getRecord().
getType());
3778 if (structTy.getMembers().size() <=
getIndex())
3779 return emitError() <<
"member index out of bounds";
3780 mlir::Type memberTy = structTy.getMembers()[
getIndex()];
3781 if (mlir::isa<cir::BitFieldType>(memberTy))
3782 return emitError() <<
"cir.extract_member does not support bit-fields";
3784 return emitError() <<
"member type mismatch";
3785 return mlir::success();
3792LogicalResult cir::InsertMemberOp::verify() {
3793 if (mlir::isa<cir::UnionType>(getRecord().
getType()))
3794 return emitError() <<
"cir.insert_member currently does not support unions";
3795 auto structTy = mlir::cast<cir::StructType>(getRecord().
getType());
3796 if (structTy.getMembers().size() <=
getIndex())
3797 return emitError() <<
"member index out of bounds";
3798 mlir::Type memberTy = structTy.getMembers()[
getIndex()];
3799 if (mlir::isa<cir::BitFieldType>(memberTy))
3800 return emitError() <<
"cir.insert_member does not support bit-fields";
3801 if (memberTy != getValue().
getType())
3802 return emitError() <<
"member type mismatch";
3804 return mlir::success();
3811OpFoldResult cir::VecCreateOp::fold(FoldAdaptor adaptor) {
3812 if (llvm::any_of(getElements(), [](mlir::Value value) {
3813 return !value.getDefiningOp<cir::ConstantOp>();
3817 return cir::ConstVectorAttr::get(
3818 getType(), mlir::ArrayAttr::get(getContext(), adaptor.getElements()));
3821LogicalResult cir::VecCreateOp::verify() {
3825 const cir::VectorType vecTy =
getType();
3826 if (getElements().size() != vecTy.getSize()) {
3827 return emitOpError() <<
"operand count of " << getElements().size()
3828 <<
" doesn't match vector type " << vecTy
3829 <<
" element count of " << vecTy.getSize();
3832 const mlir::Type elementType = vecTy.getElementType();
3833 for (
const mlir::Value element : getElements()) {
3834 if (element.getType() != elementType) {
3835 return emitOpError() <<
"operand type " << element.getType()
3836 <<
" doesn't match vector element type "
3848OpFoldResult cir::VecExtractOp::fold(FoldAdaptor adaptor) {
3849 const auto vectorAttr =
3850 llvm::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec());
3854 const auto indexAttr =
3855 llvm::dyn_cast_if_present<cir::IntAttr>(adaptor.getIndex());
3859 const mlir::ArrayAttr elements = vectorAttr.getElts();
3860 const uint64_t index = indexAttr.getUInt();
3861 if (index >= elements.size())
3864 return elements[index];
3871LogicalResult cir::CmpOp::verify() {
3872 if (getFenvAttr() && !cir::isAnyFloatingPointType(getLhs().
getType()))
3873 return emitOpError()
3874 <<
"'fenv' is only valid for floating-point comparisons";
3882LogicalResult cir::VecCmpOp::verify() {
3883 if (getFenvAttr() && !cir::isFPOrVectorOfFPType(getLhs().
getType()))
3884 return emitOpError()
3885 <<
"'fenv' is only valid for floating-point comparisons";
3889OpFoldResult cir::VecCmpOp::fold(FoldAdaptor adaptor) {
3899 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getLhs());
3901 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getRhs());
3902 if (!lhsVecAttr || !rhsVecAttr)
3905 mlir::Type inputElemTy =
3906 mlir::cast<cir::VectorType>(lhsVecAttr.getType()).getElementType();
3907 if (!isAnyIntegerOrFloatingPointType(inputElemTy))
3910 cir::CmpOpKind opKind = adaptor.getKind();
3911 mlir::ArrayAttr lhsVecElhs = lhsVecAttr.getElts();
3912 mlir::ArrayAttr rhsVecElhs = rhsVecAttr.getElts();
3913 uint64_t vecSize = lhsVecElhs.size();
3916 bool isIntAttr = vecSize && mlir::isa<cir::IntAttr>(lhsVecElhs[0]);
3917 bool isUnsignedInt =
3918 isIntAttr && mlir::cast<cir::IntType>(inputElemTy).isUnsigned();
3919 for (uint64_t i = 0; i < vecSize; i++) {
3920 mlir::Attribute lhsAttr = lhsVecElhs[i];
3921 mlir::Attribute rhsAttr = rhsVecElhs[i];
3922 bool cmpResult =
false;
3924 case cir::CmpOpKind::lt: {
3927 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() <
3928 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
3930 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <
3931 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3933 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <
3934 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3938 case cir::CmpOpKind::le: {
3941 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() <=
3942 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
3944 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <=
3945 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3947 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <=
3948 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3952 case cir::CmpOpKind::gt: {
3955 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() >
3956 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
3958 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >
3959 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3961 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >
3962 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3966 case cir::CmpOpKind::ge: {
3969 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() >=
3970 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
3972 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >=
3973 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3975 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >=
3976 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3980 case cir::CmpOpKind::eq: {
3982 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() ==
3983 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3985 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() ==
3986 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3990 case cir::CmpOpKind::ne: {
3992 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() !=
3993 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3995 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() !=
3996 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
4000 case cir::CmpOpKind::one: {
4001 llvm::APFloat::cmpResult cr =
4002 mlir::cast<cir::FPAttr>(lhsAttr).getValue().compare(
4003 mlir::cast<cir::FPAttr>(rhsAttr).getValue());
4005 cr != llvm::APFloat::cmpUnordered && cr != llvm::APFloat::cmpEqual;
4008 case cir::CmpOpKind::uno: {
4009 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue().compare(
4010 mlir::cast<cir::FPAttr>(rhsAttr).getValue()) ==
4011 llvm::APFloat::cmpUnordered;
4020 cir::IntAttr::get(
getType().getElementType(), cmpResult ? -1LL : 0LL);
4023 return cir::ConstVectorAttr::get(
4024 getType(), mlir::ArrayAttr::get(getContext(), elements));
4031OpFoldResult cir::VecShuffleOp::fold(FoldAdaptor adaptor) {
4033 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec1());
4035 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec2());
4036 if (!vec1Attr || !vec2Attr)
4039 mlir::Type vec1ElemTy =
4040 mlir::cast<cir::VectorType>(vec1Attr.getType()).getElementType();
4042 mlir::ArrayAttr vec1Elts = vec1Attr.getElts();
4043 mlir::ArrayAttr vec2Elts = vec2Attr.getElts();
4044 mlir::ArrayAttr indicesElts = adaptor.getIndices();
4047 elements.reserve(indicesElts.size());
4049 uint64_t vec1Size = vec1Elts.size();
4050 for (
const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
4051 if (idxAttr.getSInt() == -1) {
4052 elements.push_back(cir::UndefAttr::get(vec1ElemTy));
4056 uint64_t idxValue = idxAttr.getUInt();
4057 elements.push_back(idxValue < vec1Size ? vec1Elts[idxValue]
4058 : vec2Elts[idxValue - vec1Size]);
4061 return cir::ConstVectorAttr::get(
4062 getType(), mlir::ArrayAttr::get(getContext(), elements));
4065LogicalResult cir::VecShuffleOp::verify() {
4068 if (getIndices().size() != getResult().
getType().getSize()) {
4069 return emitOpError() <<
": the number of elements in " << getIndices()
4070 <<
" and " << getResult().getType() <<
" don't match";
4075 if (getVec1().
getType().getElementType() !=
4076 getResult().
getType().getElementType()) {
4077 return emitOpError() <<
": element types of " << getVec1().getType()
4078 <<
" and " << getResult().getType() <<
" don't match";
4081 const uint64_t maxValidIndex =
4082 getVec1().getType().getSize() + getVec2().getType().getSize() - 1;
4084 getIndices().getAsRange<cir::IntAttr>(), [&](cir::IntAttr idxAttr) {
4085 return idxAttr.getSInt() != -1 && idxAttr.getUInt() > maxValidIndex;
4087 return emitOpError() <<
": index for __builtin_shufflevector must be "
4088 "less than the total number of vector elements";
4097OpFoldResult cir::VecShuffleDynamicOp::fold(FoldAdaptor adaptor) {
4098 mlir::Attribute vec = adaptor.getVec();
4099 mlir::Attribute indices = adaptor.getIndices();
4100 if (mlir::isa_and_nonnull<cir::ConstVectorAttr>(vec) &&
4101 mlir::isa_and_nonnull<cir::ConstVectorAttr>(indices)) {
4102 auto vecAttr = mlir::cast<cir::ConstVectorAttr>(vec);
4103 auto indicesAttr = mlir::cast<cir::ConstVectorAttr>(indices);
4105 mlir::ArrayAttr vecElts = vecAttr.getElts();
4106 mlir::ArrayAttr indicesElts = indicesAttr.getElts();
4108 const uint64_t numElements = vecElts.size();
4111 elements.reserve(numElements);
4113 const uint64_t maskBits = llvm::NextPowerOf2(numElements - 1) - 1;
4114 for (
const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
4115 uint64_t idxValue = idxAttr.getUInt();
4116 uint64_t newIdx = idxValue & maskBits;
4117 elements.push_back(vecElts[newIdx]);
4120 return cir::ConstVectorAttr::get(
4121 getType(), mlir::ArrayAttr::get(getContext(), elements));
4127LogicalResult cir::VecShuffleDynamicOp::verify() {
4129 if (getVec().
getType().getSize() !=
4130 mlir::cast<cir::VectorType>(getIndices().
getType()).getSize()) {
4131 return emitOpError() <<
": the number of elements in " << getVec().getType()
4132 <<
" and " << getIndices().getType() <<
" don't match";
4141LogicalResult cir::VecTernaryOp::verify() {
4146 if (getCond().
getType().getSize() != getLhs().
getType().getSize()) {
4147 return emitOpError() <<
": the number of elements in "
4148 << getCond().getType() <<
" and " << getLhs().getType()
4154OpFoldResult cir::VecTernaryOp::fold(FoldAdaptor adaptor) {
4155 mlir::Attribute cond = adaptor.getCond();
4156 mlir::Attribute lhs = adaptor.getLhs();
4157 mlir::Attribute rhs = adaptor.getRhs();
4159 if (!mlir::isa_and_nonnull<cir::ConstVectorAttr>(cond) ||
4160 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(lhs) ||
4161 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(rhs))
4163 auto condVec = mlir::cast<cir::ConstVectorAttr>(cond);
4164 auto lhsVec = mlir::cast<cir::ConstVectorAttr>(lhs);
4165 auto rhsVec = mlir::cast<cir::ConstVectorAttr>(rhs);
4167 mlir::ArrayAttr condElts = condVec.getElts();
4170 elements.reserve(condElts.size());
4172 for (
const auto &[idx, condAttr] :
4173 llvm::enumerate(condElts.getAsRange<cir::IntAttr>())) {
4174 if (condAttr.getSInt()) {
4175 elements.push_back(lhsVec.getElts()[idx]);
4177 elements.push_back(rhsVec.getElts()[idx]);
4181 cir::VectorType vecTy = getLhs().getType();
4182 return cir::ConstVectorAttr::get(
4183 vecTy, mlir::ArrayAttr::get(getContext(), elements));
4190LogicalResult cir::ComplexCreateOp::verify() {
4193 <<
"operand type of cir.complex.create does not match its result type";
4200OpFoldResult cir::ComplexCreateOp::fold(FoldAdaptor adaptor) {
4201 mlir::Attribute real = adaptor.getReal();
4202 mlir::Attribute imag = adaptor.getImag();
4208 auto realAttr = mlir::cast<mlir::TypedAttr>(real);
4209 auto imagAttr = mlir::cast<mlir::TypedAttr>(imag);
4210 return cir::ConstComplexAttr::get(realAttr, imagAttr);
4217LogicalResult cir::ComplexRealOp::verify() {
4218 mlir::Type operandTy = getOperand().getType();
4219 if (
auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
4220 operandTy = complexOperandTy.getElementType();
4223 emitOpError() <<
": result type does not match operand type";
4230OpFoldResult cir::ComplexRealOp::fold(FoldAdaptor adaptor) {
4231 if (!mlir::isa<cir::ComplexType>(getOperand().
getType()))
4234 if (
auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
4235 return complexCreateOp.getOperand(0);
4238 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
4239 return complex ? complex.getReal() :
nullptr;
4246LogicalResult cir::ComplexImagOp::verify() {
4247 mlir::Type operandTy = getOperand().getType();
4248 if (
auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
4249 operandTy = complexOperandTy.getElementType();
4252 emitOpError() <<
": result type does not match operand type";
4259OpFoldResult cir::ComplexImagOp::fold(FoldAdaptor adaptor) {
4260 if (!mlir::isa<cir::ComplexType>(getOperand().
getType()))
4263 if (
auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
4264 return complexCreateOp.getOperand(1);
4267 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
4268 return complex ? complex.getImag() :
nullptr;
4275LogicalResult cir::ComplexRealPtrOp::verify() {
4276 mlir::Type resultPointeeTy =
getType().getPointee();
4277 cir::PointerType operandPtrTy = getOperand().getType();
4278 auto operandPointeeTy =
4279 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
4281 if (resultPointeeTy != operandPointeeTy.getElementType()) {
4282 return emitOpError() <<
": result type does not match operand type";
4292LogicalResult cir::ComplexImagPtrOp::verify() {
4293 mlir::Type resultPointeeTy =
getType().getPointee();
4294 cir::PointerType operandPtrTy = getOperand().getType();
4295 auto operandPointeeTy =
4296 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
4298 if (resultPointeeTy != operandPointeeTy.getElementType()) {
4299 return emitOpError()
4300 <<
"cir.complex.imag_ptr result type does not match operand type";
4311 llvm::function_ref<llvm::APInt(
const llvm::APInt &)> func,
4312 bool poisonZero =
false) {
4313 if (mlir::isa_and_present<cir::PoisonAttr>(inputAttr)) {
4318 auto input = mlir::dyn_cast_if_present<IntAttr>(inputAttr);
4322 llvm::APInt inputValue = input.getValue();
4323 if (poisonZero && inputValue.isZero())
4324 return cir::PoisonAttr::get(input.getType());
4326 llvm::APInt resultValue = func(inputValue);
4327 return IntAttr::get(input.getType(), resultValue);
4330OpFoldResult BitClrsbOp::fold(FoldAdaptor adaptor) {
4331 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
4332 unsigned resultValue =
4333 inputValue.getBitWidth() - inputValue.getSignificantBits();
4334 return llvm::APInt(inputValue.getBitWidth(), resultValue);
4338OpFoldResult BitClzOp::fold(FoldAdaptor adaptor) {
4341 [](
const llvm::APInt &inputValue) {
4342 unsigned resultValue = inputValue.countLeadingZeros();
4343 return llvm::APInt(inputValue.getBitWidth(), resultValue);
4348OpFoldResult BitCtzOp::fold(FoldAdaptor adaptor) {
4351 [](
const llvm::APInt &inputValue) {
4352 return llvm::APInt(inputValue.getBitWidth(),
4353 inputValue.countTrailingZeros());
4358OpFoldResult BitFfsOp::fold(FoldAdaptor adaptor) {
4359 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
4360 unsigned trailingZeros = inputValue.countTrailingZeros();
4362 trailingZeros == inputValue.getBitWidth() ? 0 : trailingZeros + 1;
4363 return llvm::APInt(inputValue.getBitWidth(), result);
4367OpFoldResult BitParityOp::fold(FoldAdaptor adaptor) {
4368 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
4369 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount() % 2);
4373OpFoldResult BitPopcountOp::fold(FoldAdaptor adaptor) {
4374 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
4375 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount());
4379OpFoldResult BitReverseOp::fold(FoldAdaptor adaptor) {
4380 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
4381 return inputValue.reverseBits();
4385OpFoldResult ByteSwapOp::fold(FoldAdaptor adaptor) {
4386 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
4387 return inputValue.byteSwap();
4391OpFoldResult RotateOp::fold(FoldAdaptor adaptor) {
4392 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()) ||
4393 mlir::isa_and_present<cir::PoisonAttr>(adaptor.getAmount())) {
4395 return cir::PoisonAttr::get(
getType());
4398 auto input = mlir::dyn_cast_if_present<IntAttr>(adaptor.getInput());
4399 auto amount = mlir::dyn_cast_if_present<IntAttr>(adaptor.getAmount());
4400 if (!input && !amount)
4409 llvm::APInt inputValue;
4411 inputValue = input.getValue();
4412 if (inputValue.isZero() || inputValue.isAllOnes()) {
4418 uint64_t amountValue;
4420 amountValue = amount.getValue().urem(getInput().
getType().getWidth());
4421 if (amountValue == 0) {
4427 if (!input || !amount)
4430 assert(inputValue.getBitWidth() == getInput().
getType().getWidth() &&
4431 "input value must have the same bit width as the input type");
4433 llvm::APInt resultValue;
4435 resultValue = inputValue.rotl(amountValue);
4437 resultValue = inputValue.rotr(amountValue);
4439 return IntAttr::get(input.getContext(), input.getType(), resultValue);
4446void cir::InlineAsmOp::print(OpAsmPrinter &p) {
4447 p <<
'(' << getAsmFlavor() <<
", ";
4452 auto *nameIt = names.begin();
4453 auto *attrIt = getOperandAttrs().begin();
4455 for (mlir::OperandRange ops : getAsmOperands()) {
4456 p << *nameIt <<
" = ";
4459 llvm::interleaveComma(llvm::make_range(ops.begin(), ops.end()), p,
4461 p.printOperand(value);
4462 p <<
" : " << value.getType();
4463 if (mlir::isa<mlir::UnitAttr>(*attrIt))
4464 p <<
" (maybe_memory)";
4473 p.printString(getAsmString());
4475 p.printString(getConstraints());
4479 if (getSideEffects())
4480 p <<
" side_effects";
4482 p.printOptionalAttrDict(
4483 getOperation()->getDiscardableAttrDictionary().getValue());
4485 if (
auto v = getRes())
4486 p <<
" -> " << v.getType();
4489void cir::InlineAsmOp::build(OpBuilder &odsBuilder, OperationState &odsState,
4491 StringRef asmString, StringRef constraints,
4492 bool sideEffects, cir::AsmFlavor asmFlavor,
4496 for (
auto operandRange : asmOperands) {
4497 segments.push_back(operandRange.size());
4498 odsState.addOperands(operandRange);
4501 odsState.addAttribute(
4502 "operands_segments",
4503 DenseI32ArrayAttr::get(odsBuilder.getContext(), segments));
4504 odsState.addAttribute(
"asm_string", odsBuilder.getStringAttr(asmString));
4505 odsState.addAttribute(
"constraints", odsBuilder.getStringAttr(constraints));
4506 odsState.addAttribute(
"asm_flavor",
4507 AsmFlavorAttr::get(odsBuilder.getContext(), asmFlavor));
4510 odsState.addAttribute(
"side_effects", odsBuilder.getUnitAttr());
4512 odsState.addAttribute(
"operand_attrs", odsBuilder.getArrayAttr(operandAttrs));
4515ParseResult cir::InlineAsmOp::parse(OpAsmParser &parser,
4516 OperationState &result) {
4519 std::string asmString, constraints;
4521 MLIRContext *ctxt = parser.getBuilder().getContext();
4523 auto error = [&](
const Twine &msg) -> LogicalResult {
4524 return parser.emitError(parser.getCurrentLocation(), msg);
4527 auto expected = [&](
const std::string &c) {
4528 return error(
"expected '" + c +
"'");
4531 if (parser.parseLParen().failed())
4532 return expected(
"(");
4534 auto flavor = FieldParser<AsmFlavor, AsmFlavor>::parse(parser);
4536 return error(
"Unknown AsmFlavor");
4538 if (parser.parseComma().failed())
4539 return expected(
",");
4541 auto parseValue = [&](
Value &v) {
4542 OpAsmParser::UnresolvedOperand op;
4544 if (parser.parseOperand(op) || parser.parseColon())
4545 return error(
"can't parse operand");
4548 if (parser.parseType(typ).failed())
4549 return error(
"can't parse operand type");
4551 if (parser.resolveOperand(op, typ, tmp))
4552 return error(
"can't resolve operand");
4554 return mlir::success();
4557 auto parseOperands = [&](llvm::StringRef
name) {
4558 if (parser.parseKeyword(name).failed())
4559 return error(
"expected " + name +
" operands here");
4560 if (parser.parseEqual().failed())
4561 return expected(
"=");
4562 if (parser.parseLSquare().failed())
4563 return expected(
"[");
4566 if (parser.parseOptionalRSquare().succeeded()) {
4567 operandsGroupSizes.push_back(size);
4568 if (parser.parseComma())
4569 return expected(
",");
4570 return mlir::success();
4573 auto parseOperand = [&]() {
4575 if (parseValue(val).succeeded()) {
4576 result.operands.push_back(val);
4579 if (parser.parseOptionalLParen().failed()) {
4580 operandAttrs.push_back(mlir::DictionaryAttr::get(ctxt));
4581 return mlir::success();
4584 if (parser.parseKeyword(
"maybe_memory").succeeded()) {
4585 operandAttrs.push_back(mlir::UnitAttr::get(ctxt));
4586 if (parser.parseRParen())
4587 return expected(
")");
4588 return mlir::success();
4590 return expected(
"maybe_memory");
4593 return mlir::failure();
4596 if (parser.parseCommaSeparatedList(parseOperand).failed())
4597 return mlir::failure();
4599 if (parser.parseRSquare().failed() || parser.parseComma().failed())
4600 return expected(
"]");
4601 operandsGroupSizes.push_back(size);
4602 return mlir::success();
4605 if (parseOperands(
"out").failed() || parseOperands(
"in").failed() ||
4606 parseOperands(
"in_out").failed())
4607 return error(
"failed to parse operands");
4609 if (parser.parseLBrace())
4610 return expected(
"{");
4611 if (parser.parseString(&asmString))
4612 return error(
"asm string parsing failed");
4613 if (parser.parseString(&constraints))
4614 return error(
"constraints string parsing failed");
4615 if (parser.parseRBrace())
4616 return expected(
"}");
4617 if (parser.parseRParen())
4618 return expected(
")");
4620 if (parser.parseOptionalKeyword(
"side_effects").succeeded())
4621 result.attributes.set(
"side_effects", UnitAttr::get(ctxt));
4623 if (parser.parseOptionalAttrDict(result.attributes).failed())
4624 return mlir::failure();
4626 if (parser.parseOptionalArrow().succeeded() &&
4627 parser.parseType(resType).failed())
4628 return mlir::failure();
4630 result.attributes.set(
"asm_flavor", AsmFlavorAttr::get(ctxt, *flavor));
4631 result.attributes.set(
"asm_string", StringAttr::get(ctxt, asmString));
4632 result.attributes.set(
"constraints", StringAttr::get(ctxt, constraints));
4633 result.attributes.set(
"operand_attrs", ArrayAttr::get(ctxt, operandAttrs));
4634 result.getOrAddProperties<InlineAsmOp::Properties>().operands_segments =
4635 parser.getBuilder().getDenseI32ArrayAttr(operandsGroupSizes);
4637 result.addTypes(TypeRange{resType});
4639 return mlir::success();
4646template <
typename ThrowOpTy>
4649 return mlir::success();
4651 if (op.getNumOperands() != 0) {
4652 if (op.getTypeInfo())
4653 return mlir::success();
4654 return op.emitOpError() <<
"'type_info' symbol attribute missing";
4657 return mlir::failure();
4662mlir::LogicalResult cir::TryThrowOp::verify() {
4670LogicalResult cir::AtomicFetchOp::verify() {
4671 if (getBinop() != cir::AtomicFetchKind::Add &&
4672 getBinop() != cir::AtomicFetchKind::Sub &&
4673 getBinop() != cir::AtomicFetchKind::Max &&
4674 getBinop() != cir::AtomicFetchKind::Min &&
4675 getBinop() != cir::AtomicFetchKind::Maximum &&
4676 getBinop() != cir::AtomicFetchKind::Minimum &&
4677 getBinop() != cir::AtomicFetchKind::MaximumNum &&
4678 getBinop() != cir::AtomicFetchKind::MinimumNum &&
4679 !mlir::isa<cir::IntType>(getVal().
getType()))
4680 return emitError(
"only atomic add, sub, max, min, maximum, minimum, "
4681 "maximum_num, and minimum_num operation could operate on "
4682 "floating-point values");
4684 if ((getBinop() == cir::AtomicFetchKind::Maximum ||
4685 getBinop() == cir::AtomicFetchKind::Minimum ||
4686 getBinop() == cir::AtomicFetchKind::MaximumNum ||
4687 getBinop() == cir::AtomicFetchKind::MinimumNum) &&
4688 !mlir::isa<cir::FPTypeInterface>(getVal().
getType()))
4689 return emitError(
"atomic maximum, minimum, maximum_num, and minimum_num "
4690 "operation could only operate on floating-point values");
4699LogicalResult cir::TypeInfoAttr::verify(
4700 ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError,
4701 ::mlir::Type type, ::mlir::ArrayAttr typeInfoData) {
4703 if (cir::ConstRecordAttr::verify(emitError, type, typeInfoData).failed())
4713void cir::TryOp::getSuccessorRegions(
4714 mlir::RegionBranchPoint point,
4717 if (!point.isParent()) {
4718 regions.emplace_back(getOperation());
4722 regions.push_back(mlir::RegionSuccessor(&getTryRegion()));
4726 for (mlir::Region &handlerRegion : this->getHandlerRegions())
4727 regions.push_back(mlir::RegionSuccessor(&handlerRegion));
4730LogicalResult cir::TryOp::verify() {
4731 mlir::ArrayAttr handlerTypes = getHandlerTypes();
4732 if (!handlerTypes) {
4733 if (!getHandlerRegions().empty())
4735 "handler regions must be empty when no handler types are present");
4739 mlir::MutableArrayRef<mlir::Region> handlerRegions = getHandlerRegions();
4743 if (handlerRegions.size() != handlerTypes.size())
4745 "number of handler regions and handler types must match");
4753 if (llvm::any_of(handlerTypes, [](mlir::Attribute typeAttr) {
4754 return mlir::isa<cir::EhFilterAttr, cir::EhUnexpectedAttr>(typeAttr);
4756 if (handlerTypes.size() != 2 ||
4757 !mlir::isa<cir::EhFilterAttr>(handlerTypes[0]) ||
4758 !mlir::isa<cir::EhUnexpectedAttr>(handlerTypes[1]))
4759 return emitOpError(
"a filter handler must be followed by an unexpected "
4760 "handler, and the two must be the only handlers");
4763 for (
const auto &[typeAttr, handlerRegion] :
4764 llvm::zip(handlerTypes, handlerRegions)) {
4766 mlir::Block &entryBlock = handlerRegion.front();
4767 if (entryBlock.getNumArguments() != 1 ||
4768 !mlir::isa<cir::EhTokenType>(entryBlock.getArgument(0).getType()))
4770 "handler region must have a single '!cir.eh_token' argument");
4774 if (mlir::isa<cir::UnwindAttr, cir::EhFilterAttr, cir::EhUnexpectedAttr>(
4778 if (entryBlock.empty())
4779 return emitOpError(
"catch handler region must not be empty");
4785 if (mlir::isa<cir::EhTerminateOp>(entryBlock.front())) {
4786 if (!mlir::isa<cir::CatchAllAttr>(typeAttr))
4787 return emitOpError(
"'cir.eh.terminate' is only allowed in a catch-all "
4806 mlir::Operation *firstOp = &entryBlock.front();
4807 if (mlir::isa<cir::LifetimeStartOp>(firstOp)) {
4808 mlir::Operation *next = firstOp->getNextNode();
4809 auto lifetimeScope = mlir::dyn_cast_if_present<cir::CleanupScopeOp>(next);
4811 return emitOpError(
"'cir.lifetime.start' in a catch handler region "
4812 "must be followed by the 'cir.cleanup.scope' of "
4813 "its lifetime-end cleanup");
4814 if (lifetimeScope.getBodyRegion().empty())
4816 "'cir.lifetime.start' in a catch handler region must be "
4817 "followed by the 'cir.cleanup.scope' of its lifetime-end "
4819 mlir::Block &scopeBody = lifetimeScope.getBodyRegion().front();
4820 firstOp = scopeBody.empty() ?
nullptr : &scopeBody.front();
4823 if (mlir::isa_and_present<cir::ConstructCatchParamOp>(firstOp))
4824 firstOp = firstOp->getNextNode();
4825 if (!mlir::isa_and_present<cir::BeginCatchOp>(firstOp))
4827 "catch handler region must start with 'cir.begin_catch'");
4835 mlir::MutableArrayRef<mlir::Region> handlerRegions,
4836 mlir::ArrayAttr handlerTypes) {
4840 for (
const auto [typeIdx, typeAttr] : llvm::enumerate(handlerTypes)) {
4844 if (mlir::isa<cir::CatchAllAttr>(typeAttr)) {
4845 printer <<
"catch all ";
4846 }
else if (mlir::isa<cir::UnwindAttr>(typeAttr)) {
4847 printer <<
"unwind ";
4848 }
else if (
auto filterAttr = mlir::dyn_cast<cir::EhFilterAttr>(typeAttr)) {
4849 printer <<
"filter [";
4850 llvm::interleaveComma(
4851 filterAttr.getPermittedTypes(), printer,
4852 [&](mlir::Attribute sym) { printer.printAttribute(sym); });
4854 }
else if (mlir::isa<cir::EhUnexpectedAttr>(typeAttr)) {
4855 printer <<
"unexpected ";
4857 printer <<
"catch [type ";
4858 printer.printAttribute(typeAttr);
4863 mlir::Region ®ion = handlerRegions[typeIdx];
4864 if (!region.empty() && region.front().getNumArguments() > 0) {
4866 printer.printRegionArgument(region.front().getArgument(0));
4870 printer.printRegion(region,
4877 mlir::OpAsmParser &parser,
4879 mlir::ArrayAttr &handlerTypes) {
4881 auto parseCheckedCatcherRegion = [&]() -> mlir::ParseResult {
4882 handlerRegions.emplace_back(
new mlir::Region);
4884 mlir::Region &currRegion = *handlerRegions.back();
4888 if (parser.parseLParen())
4890 mlir::OpAsmParser::Argument arg;
4891 if (parser.parseArgument(arg,
true))
4893 regionArgs.push_back(arg);
4894 if (parser.parseRParen())
4897 mlir::SMLoc regionLoc = parser.getCurrentLocation();
4898 if (parser.parseRegion(currRegion, regionArgs)) {
4899 handlerRegions.clear();
4903 if (currRegion.empty())
4904 return parser.emitError(regionLoc,
"handler region shall not be empty");
4906 if (!(currRegion.back().mightHaveTerminator() &&
4907 currRegion.back().getTerminator()))
4908 return parser.emitError(
4909 regionLoc,
"blocks are expected to be explicitly terminated");
4914 bool hasCatchAll =
false;
4916 while (parser.parseOptionalKeyword(
"catch").succeeded()) {
4917 bool hasLSquare = parser.parseOptionalLSquare().succeeded();
4919 llvm::StringRef attrStr;
4920 if (parser.parseOptionalKeyword(&attrStr, {
"all",
"type"}).failed())
4921 return parser.emitError(parser.getCurrentLocation(),
4922 "expected 'all' or 'type' keyword");
4924 bool isCatchAll = attrStr ==
"all";
4927 return parser.emitError(parser.getCurrentLocation(),
4928 "can't have more than one catch all");
4932 mlir::Attribute exceptionRTTIAttr;
4933 if (!isCatchAll && parser.parseAttribute(exceptionRTTIAttr).failed())
4934 return parser.emitError(parser.getCurrentLocation(),
4935 "expected valid RTTI info attribute");
4937 catcherAttrs.push_back(isCatchAll
4938 ? cir::CatchAllAttr::get(parser.getContext())
4939 : exceptionRTTIAttr);
4941 if (hasLSquare && isCatchAll)
4942 return parser.emitError(parser.getCurrentLocation(),
4943 "catch all dosen't need RTTI info attribute");
4945 if (hasLSquare && parser.parseRSquare().failed())
4946 return parser.emitError(parser.getCurrentLocation(),
4947 "expected `]` after RTTI info attribute");
4949 if (parseCheckedCatcherRegion().failed())
4950 return mlir::failure();
4956 if (parser.parseOptionalKeyword(
"filter").succeeded()) {
4957 mlir::SMLoc filterLoc = parser.getCurrentLocation();
4959 auto parsePermittedType = [&]() -> mlir::ParseResult {
4960 mlir::SMLoc typeLoc = parser.getCurrentLocation();
4961 mlir::Attribute rtti;
4962 if (parser.parseAttribute(rtti).failed())
4963 return mlir::failure();
4964 if (!mlir::isa<cir::GlobalViewAttr>(rtti))
4965 return parser.emitError(typeLoc,
"expected a type info symbol naming a "
4966 "permitted exception type");
4967 permittedTypes.push_back(rtti);
4968 return mlir::success();
4971 .parseCommaSeparatedList(mlir::OpAsmParser::Delimiter::Square,
4974 return mlir::failure();
4976 auto filterAttr = cir::EhFilterAttr::getChecked(
4977 [&]() {
return parser.emitError(filterLoc); }, parser.getContext(),
4978 parser.getBuilder().getArrayAttr(permittedTypes));
4980 return mlir::failure();
4981 catcherAttrs.push_back(filterAttr);
4982 if (parseCheckedCatcherRegion().failed())
4983 return mlir::failure();
4986 if (parser.parseOptionalKeyword(
"unexpected").succeeded()) {
4987 catcherAttrs.push_back(cir::EhUnexpectedAttr::get(parser.getContext()));
4988 if (parseCheckedCatcherRegion().failed())
4989 return mlir::failure();
4992 if (parser.parseOptionalKeyword(
"unwind").succeeded()) {
4994 return parser.emitError(parser.getCurrentLocation(),
4995 "unwind can't be used with catch all");
4997 catcherAttrs.push_back(cir::UnwindAttr::get(parser.getContext()));
4998 if (parseCheckedCatcherRegion().failed())
4999 return mlir::failure();
5002 handlerTypes = parser.getBuilder().getArrayAttr(catcherAttrs);
5003 return mlir::success();
5011cir::EhTypeIdOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
5012 Operation *op = symbolTable.lookupNearestSymbolFrom(*
this, getTypeSymAttr());
5013 if (!isa_and_nonnull<GlobalOp>(op))
5014 return emitOpError(
"'")
5015 << getTypeSym() <<
"' does not reference a valid cir.global";
5023LogicalResult cir::LifetimeStartOp::verify() {
5027LogicalResult cir::LifetimeEndOp::verify() {
5037 auto intAttr = mlir::dyn_cast<mlir::IntegerAttr>(attr);
5038 if (!intAttr || !intAttr.getType().isSignlessInteger(32))
5039 return std::nullopt;
5040 int64_t width = intAttr.getInt();
5043 return std::nullopt;
5044 return static_cast<unsigned>(width);
5047LogicalResult cir::MemChrOp::verify() {
5048 auto moduleOp = (*this)->getParentOfType<mlir::ModuleOp>();
5050 return emitOpError(
"expects an enclosing module");
5053 if (mlir::cast<cir::PointerType>(getSrc().
getType()).getAddrSpace())
5054 return emitOpError(
"src must be in the default address space");
5056 auto checkWidth = [&](cir::IntType type, llvm::StringRef operandName,
5057 llvm::StringRef attrName) -> LogicalResult {
5058 mlir::Attribute
attr = moduleOp->getAttr(attrName);
5060 return emitOpError(
"expects the module to record ") << attrName;
5063 return emitOpError(
"requires ")
5065 <<
" to be a signless i32 holding a fundamental integer width";
5066 if (type.getWidth() != *width)
5067 return emitOpError() << operandName <<
" must have the width recorded in "
5072 if (failed(checkWidth(getPattern().
getType(),
"pattern",
5073 cir::CIRDialect::getIntTypeWidthAttrName())))
5075 return checkWidth(getLen().
getType(),
"len",
5076 cir::CIRDialect::getSizeTypeWidthAttrName());
5083LogicalResult cir::ConstructCatchParamOp::verifySymbolUses(
5084 SymbolTableCollection &symbolTable) {
5085 auto copyFnAttr = getCopyFnAttr();
5089 symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(*
this, getCopyFnAttr());
5091 return emitOpError(
"'")
5092 << *getCopyFn() <<
"' does not reference a valid cir.func";
5094 if (!fn->hasAttr(cir::CIRDialect::getCatchCopyThunkAttrName()))
5095 return emitOpError(
"catch-init copy_fn must be tagged with the ")
5096 << cir::CIRDialect::getCatchCopyThunkAttrName() <<
" attribute";
5098 cir::FuncType fnType = fn.getFunctionType();
5099 if (fnType.getNumInputs() != 2 || !fnType.hasVoidReturn())
5100 return emitOpError(
"catch-init copy_fn must take two pointer arguments and "
5103 if (fnType.getInput(0) != getParamAddr().
getType())
5104 return emitOpError(
"first argument of catch-init copy_fn must match the "
5105 "type of 'param_addr'");
5107 if (fnType.getInput(1) != getParamAddr().
getType())
5109 "second argument of catch-init copy_fn must be a pointer "
5110 "to the catch type");
5119LogicalResult cir::EhDispatchOp::verify() {
5120 mlir::ArrayAttr handlerTypes = getCatchTypesAttr();
5124 bool hasFilter =
false;
5125 for (mlir::Attribute typeAttr : handlerTypes) {
5126 if (!mlir::isa<cir::EhFilterAttr>(typeAttr))
5129 return emitOpError(
"can't have more than one 'filter' handler");
5137 if (hasFilter && getDefaultIsCatchAll())
5139 "'filter' handler requires an 'unwind' default destination");
5146 SmallVectorImpl<Block *> &catchDestinations,
5147 Block *&defaultDestination,
5148 mlir::UnitAttr &defaultIsCatchAll) {
5150 if (parser.parseLSquare())
5154 bool hasCatchAll =
false;
5155 bool hasUnwind =
false;
5158 auto parseHandler = [&]() -> ParseResult {
5160 if (succeeded(parser.parseOptionalKeyword(
"catch_all"))) {
5162 return parser.emitError(parser.getCurrentLocation(),
5163 "duplicate 'catch_all' handler");
5165 return parser.emitError(parser.getCurrentLocation(),
5166 "cannot have both 'catch_all' and 'unwind'");
5169 if (parser.parseColon().failed())
5172 if (parser.parseSuccessor(defaultDestination).failed())
5178 if (succeeded(parser.parseOptionalKeyword(
"unwind"))) {
5180 return parser.emitError(parser.getCurrentLocation(),
5181 "duplicate 'unwind' handler");
5183 return parser.emitError(parser.getCurrentLocation(),
5184 "cannot have both 'catch_all' and 'unwind'");
5187 if (parser.parseColon().failed())
5190 if (parser.parseSuccessor(defaultDestination).failed())
5198 if (succeeded(parser.parseOptionalKeyword(
"filter"))) {
5199 SMLoc filterLoc = parser.getCurrentLocation();
5201 auto parsePermittedType = [&]() -> ParseResult {
5202 mlir::SMLoc typeLoc = parser.getCurrentLocation();
5203 mlir::Attribute rtti;
5204 if (parser.parseAttribute(rtti).failed())
5206 if (!mlir::isa<cir::GlobalViewAttr>(rtti))
5207 return parser.emitError(typeLoc,
5208 "expected a type info symbol naming a "
5209 "permitted exception type");
5210 permittedTypes.push_back(rtti);
5214 .parseCommaSeparatedList(OpAsmParser::Delimiter::Paren,
5219 auto filterAttr = cir::EhFilterAttr::getChecked(
5220 [&]() {
return parser.emitError(filterLoc); }, parser.getContext(),
5221 parser.getBuilder().getArrayAttr(permittedTypes));
5224 handlerTypes.push_back(filterAttr);
5226 if (parser.parseColon().failed())
5230 if (parser.parseSuccessor(dest).failed())
5232 catchDestinations.push_back(dest);
5239 if (parser.parseKeyword(
"catch").failed())
5242 if (parser.parseLParen().failed())
5245 mlir::Attribute catchTypeAttr;
5246 if (parser.parseAttribute(catchTypeAttr).failed())
5248 handlerTypes.push_back(catchTypeAttr);
5250 if (parser.parseRParen().failed())
5253 if (parser.parseColon().failed())
5257 if (parser.parseSuccessor(dest).failed())
5259 catchDestinations.push_back(dest);
5263 if (parser.parseCommaSeparatedList(parseHandler).failed())
5266 if (parser.parseRSquare().failed())
5270 if (!hasCatchAll && !hasUnwind)
5271 return parser.emitError(parser.getCurrentLocation(),
5272 "must have either 'catch_all' or 'unwind' handler");
5275 if (!handlerTypes.empty())
5276 catchTypes = parser.getBuilder().getArrayAttr(handlerTypes);
5279 defaultIsCatchAll = parser.getBuilder().getUnitAttr();
5285 mlir::ArrayAttr catchTypes,
5286 SuccessorRange catchDestinations,
5287 Block *defaultDestination,
5288 mlir::UnitAttr defaultIsCatchAll) {
5296 llvm::zip(catchTypes, catchDestinations),
5298 mlir::Attribute typeAttr = std::get<0>(i);
5299 if (
auto filterAttr = mlir::dyn_cast<cir::EhFilterAttr>(typeAttr)) {
5301 llvm::interleaveComma(
5302 filterAttr.getPermittedTypes(), p,
5303 [&](mlir::Attribute sym) { p.printAttribute(sym); });
5306 p.printAttribute(typeAttr);
5309 p.printSuccessor(std::get<1>(i));
5321 if (defaultIsCatchAll)
5322 p <<
" catch_all : ";
5325 p.printSuccessor(defaultDestination);
5335bool cir::StdFindOp::signatureMatches(mlir::TypeRange operands,
5336 mlir::TypeRange results) {
5337 if (operands.size() != getNumArgs() || results.size() != 1)
5339 mlir::Type iterTy = operands[0];
5340 return iterTy == operands[1] && iterTy == operands[2] && iterTy == results[0];
5347#define GET_OP_CLASSES
5348#include "clang/CIR/Dialect/IR/CIROps.cpp.inc"
static StringRef bytes(const std::vector< T, Allocator > &v)
static const MemRegion * getRegion(const CallEvent &Call, const MutexDescriptor &Descriptor, bool IsLock)
static LogicalResult verifyLoopCleanup(LoopOpTy op)
static LogicalResult verifyOpenCLCXXVersion(ModuleOp module, cir::OpenCLVersionAttr cxxVersion)
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 void printCopyTypes(mlir::OpAsmPrinter &printer, mlir::Operation *, mlir::Type srcType, mlir::Type dstType)
static LogicalResult verifyOffloadContainer(mlir::Operation *op)
mlir::OptionalParseResult parseGlobalMemorySpace(mlir::AsmParser &p, mlir::ptr::MemorySpaceAttrInterface &attr)
static std::optional< unsigned > getRecordedIntegerWidth(mlir::Attribute attr)
Reads a fundamental integer width from a signless i32 attribute.
static bool isCirFunctionPointerType(mlir::Type ty)
static LogicalResult verifyMemberPtrCast(Operation *op, mlir::Value src, mlir::Type resultTy)
static bool isFloatingPointCastKind(cir::CastKind kind)
static LogicalResult verifyOffloadKind(mlir::ModuleOp module, cir::OffloadKind expected)
static mlir::ParseResult parseCallCommon(mlir::OpAsmParser &parser, mlir::OperationState &result, bool hasDestinationBlocks=false)
static mlir::Type memberPointeeType(cir::RecordType recordTy, unsigned idx)
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 ParseResult checkEffectAttrKinds(mlir::OpAsmParser &parser, llvm::SMLoc loc, const mlir::NamedAttrList &attrs)
Reject an effect attribute of the wrong kind in an explicit attribute dictionary.
static void printCallCommon(mlir::Operation *op, mlir::FlatSymbolRefAttr calleeSym, mlir::Value indirectCallee, mlir::OpAsmPrinter &printer, bool isNothrow, ArrayAttr argAttrs, ArrayAttr resAttrs, mlir::Block *normalDest=nullptr, mlir::Block *unwindDest=nullptr)
static void printAssumeBundle(OpAsmPrinter &p, cir::AssumeOp op, cir::AssumeBundleKindAttr kindAttr, OperandRange bundleArgs, TypeRange bundleArgTypes)
static bool areOpenCLVersionsCompatible(cir::OpenCLVersionAttr openCLVersion, cir::OpenCLVersionAttr cxxVersion)
static LogicalResult verifyOpenCLVersionAttrPlacement(Operation *op, NamedAttribute attr)
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 )* )?
static LogicalResult verifyOpenCLVersionAttr(Operation *op, NamedAttribute attr)
static LogicalResult verifyCallCommInSymbolUses(mlir::Operation *op, SymbolTableCollection &symbolTable)
void printGlobalMemorySpace(mlir::AsmPrinter &printer, cir::GlobalOp op, mlir::ptr::MemorySpaceAttrInterface attr)
static bool isOpenCLVersionAttrName(StringRef attrName)
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.
static void printSwitchFlatOpCases(OpAsmPrinter &p, cir::SwitchFlatOp op, Type flagType, mlir::ArrayAttr caseValues, SuccessorRange caseDestinations, OperandRangeRange caseOperands, const TypeRangeRange &caseOperandTypes)
static LogicalResult verifyProducedBy(Operation *op, Value operand, StringRef operandName)
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 mlir::ParseResult parseCopyTypes(mlir::OpAsmParser &parser, mlir::Type &srcType, mlir::Type &dstType)
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 bool isRedundantBeforeReturn(mlir::Region &cleanupRegion)
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
C++ view class that accepts both !cir.struct and !cir.union types.
llvm::ArrayRef< mlir::Type > getMembers() const
mlir::Type memberStorageType(mlir::Type memberTy)
The storage a member is stored as: the access unit for a bit-field member, and the member type itself...
bool isValidFundamentalIntWidth(unsigned width)
void buildTerminatedBody(mlir::OpBuilder &builder, mlir::Location loc)
AllocaOp getUnderlyingAlloca(mlir::Value addr)
The alloca that defines addr, looking through casts that preserve the underlying storage.
mlir::ptr::MemorySpaceAttrInterface normalizeDefaultAddressSpace(mlir::ptr::MemorySpaceAttrInterface addrSpace)
Normalize LangAddressSpace::Default to null (empty attribute).
const AstTypeMatcher< BuiltinType > builtinType
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()