20#include "mlir/IR/Attributes.h"
21#include "mlir/IR/BuiltinOps.h"
22#include "mlir/IR/BuiltinTypes.h"
23#include "mlir/IR/DialectImplementation.h"
24#include "mlir/IR/PatternMatch.h"
25#include "mlir/IR/Value.h"
26#include "mlir/Interfaces/ControlFlowInterfaces.h"
27#include "mlir/Interfaces/FunctionImplementation.h"
28#include "mlir/Support/LLVM.h"
31#include "clang/CIR/Dialect/IR/CIROpsDialect.cpp.inc"
32#include "clang/CIR/Dialect/IR/CIROpsEnums.cpp.inc"
34#include "llvm/ADT/SetOperations.h"
35#include "llvm/ADT/SmallSet.h"
36#include "llvm/ADT/TypeSwitch.h"
37#include "llvm/Support/Casting.h"
38#include "llvm/Support/LogicalResult.h"
50struct CIROpAsmDialectInterface :
public OpAsmDialectInterface {
51 using OpAsmDialectInterface::OpAsmDialectInterface;
53 AliasResult getAlias(Type type, raw_ostream &os)
const final {
54 if (
auto recordType = dyn_cast<cir::RecordType>(type)) {
57 os <<
"rec_anon_" <<
recordType.getKindAsStr();
59 os <<
"rec_" << nameAttr.getValue();
60 return AliasResult::OverridableAlias;
62 if (
auto intType = dyn_cast<cir::IntType>(type)) {
65 unsigned width = intType.getWidth();
66 if (width < 8 || !llvm::isPowerOf2_32(width))
67 return AliasResult::NoAlias;
68 os << intType.getAlias();
69 return AliasResult::OverridableAlias;
71 if (
auto voidType = dyn_cast<cir::VoidType>(type)) {
72 os << voidType.getAlias();
73 return AliasResult::OverridableAlias;
76 return AliasResult::NoAlias;
79 AliasResult getAlias(Attribute attr, raw_ostream &os)
const final {
80 if (
auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr)) {
81 os << (boolAttr.getValue() ?
"true" :
"false");
82 return AliasResult::FinalAlias;
84 if (
auto bitfield = mlir::dyn_cast<cir::BitfieldInfoAttr>(attr)) {
85 os <<
"bfi_" << bitfield.getName().str();
86 return AliasResult::FinalAlias;
88 if (
auto dynCastInfoAttr = mlir::dyn_cast<cir::DynamicCastInfoAttr>(attr)) {
89 os << dynCastInfoAttr.getAlias();
90 return AliasResult::FinalAlias;
92 if (
auto cmpThreeWayInfoAttr =
93 mlir::dyn_cast<cir::CmpThreeWayInfoAttr>(attr)) {
94 os << cmpThreeWayInfoAttr.getAlias();
95 return AliasResult::FinalAlias;
97 return AliasResult::NoAlias;
102void cir::CIRDialect::initialize() {
104 registerAttributes();
105 registerCIRDialectOperations(
this);
106 addInterfaces<CIROpAsmDialectInterface>();
110Operation *cir::CIRDialect::materializeConstant(mlir::OpBuilder &builder,
111 mlir::Attribute value,
113 mlir::Location loc) {
114 return cir::ConstantOp::create(builder, loc, type,
115 mlir::cast<mlir::TypedAttr>(value));
119 return attrName == CIRDialect::getOpenCLVersionAttrName() ||
120 attrName == CIRDialect::getOpenCLCXXVersionAttrName() ||
121 attrName == CIRDialect::getOpenCLSPIRVersionAttrName();
125 NamedAttribute attr) {
126 StringRef attrName = attr.getName().getValue();
127 if (isa<ModuleOp>(op))
130 return op->emitError() << attrName
131 <<
" attribute must be attached to a module";
135 cir::OpenCLVersionAttr cxxVersion) {
136 return (openCLVersion.getMajorVersion() == 2 &&
137 openCLVersion.getMinorVersion() == 0 &&
138 cxxVersion.getMajorVersion() == 1 &&
139 cxxVersion.getMinorVersion() == 0) ||
140 (openCLVersion.getMajorVersion() == 3 &&
141 openCLVersion.getMinorVersion() == 0 &&
142 cxxVersion.getMajorVersion() == 2021 &&
143 cxxVersion.getMinorVersion() == 0);
147 cir::OpenCLVersionAttr cxxVersion) {
148 Attribute openCLAttr =
149 module->getAttr(CIRDialect::getOpenCLVersionAttrName());
151 return module.emitError()
152 << "module attribute '" << CIRDialect::getOpenCLCXXVersionAttrName()
153 << "' requires the companion attribute '"
154 << CIRDialect::getOpenCLVersionAttrName() << "'";
156 auto openCLVersion = dyn_cast<cir::OpenCLVersionAttr>(openCLAttr);
161 return module.emitError("incompatible OpenCL and C++ for OpenCL versions");
167 NamedAttribute attr) {
171 StringRef attrName = attr.getName().getValue();
172 auto version = dyn_cast<cir::OpenCLVersionAttr>(attr.getValue());
174 return op->emitError() <<
"expected " << attrName
175 <<
" to be #cir.cl.version";
178 if (attrName == CIRDialect::getOpenCLCXXVersionAttrName())
184LogicalResult cir::CIRDialect::verifyRegionArgAttribute(
185 Operation *op,
unsigned ,
unsigned ,
186 NamedAttribute attr) {
193LogicalResult cir::CIRDialect::verifyRegionResultAttribute(
194 Operation *op,
unsigned ,
unsigned ,
195 NamedAttribute attr) {
207 cir::OffloadKind expected) {
208 auto attr =
module->getAttrOfType<cir::OffloadKindAttr>(
209 cir::CIRDialect::getOffloadKindAttrName());
211 return module.emitOpError()
212 << "expects '" << cir::CIRDialect::getOffloadKindAttrName()
213 << "' offload kind attribute";
214 if (attr.getValue() != expected)
215 return module.emitOpError()
216 << "expects '" << cir::CIRDialect::getOffloadKindAttrName()
217 << "' value '" << cir::stringifyOffloadKind(expected) << "'";
226 auto container = mlir::dyn_cast<mlir::ModuleOp>(op);
228 return op->emitOpError()
229 <<
"expects '" << cir::CIRDialect::getOffloadContainerAttrName()
230 <<
"' attribute to be attached to '"
231 << mlir::ModuleOp::getOperationName() <<
"'";
233 mlir::Block &body = *container.getBody();
235 return container.emitOpError()
236 <<
"expects host module as the first nested op";
238 auto host = mlir::dyn_cast<mlir::ModuleOp>(body.front());
240 return container.emitOpError()
241 <<
"expects host module as the first nested op";
246 if (std::next(body.begin()) == body.end())
247 return container.emitOpError() <<
"expects at least one device module";
249 for (
auto &op : llvm::drop_begin(body)) {
250 auto module = mlir::dyn_cast<mlir::ModuleOp>(op);
252 return container.emitOpError()
253 <<
"expects only nested builtin.module ops";
261cir::CIRDialect::verifyOperationAttribute(mlir::Operation *op,
262 mlir::NamedAttribute attr) {
263 llvm::StringRef attrName =
attr.getName().getValue();
267 if (attrName == getCXXABIAttrName()) {
268 if (!mlir::isa<mlir::ModuleOp>(op))
269 return op->emitOpError() <<
"expects '" << getCXXABIAttrName()
270 <<
"' attribute to be attached to '"
271 << mlir::ModuleOp::getOperationName() <<
"'";
272 auto abi = mlir::dyn_cast<mlir::StringAttr>(
attr.getValue());
274 return op->emitOpError()
275 <<
"expects '" << getCXXABIAttrName() <<
"' to be a string";
277 StringRef abival = abi.getValue();
279 return op->emitOpError() <<
"unknown C++ ABI '" << abi.getValue() <<
"'";
282 if (
auto triple = op->getAttrOfType<mlir::StringAttr>(getTripleAttrName()))
284 llvm::Triple(triple.getValue()),
kind))
285 return op->emitOpError()
286 <<
"C++ ABI '" << abi.getValue()
287 <<
"' is not supported on target '" << triple.getValue() <<
"'";
292 if (attrName == getOffloadContainerAttrName()) {
293 if (!mlir::isa<mlir::UnitAttr>(
attr.getValue()))
294 return op->emitOpError() <<
"expects '" << getOffloadContainerAttrName()
295 <<
"' to be a unit attribute";
302 if (attrName == getOffloadKindAttrName() && !mlir::isa<mlir::ModuleOp>(op))
303 return op->emitOpError() <<
"expects '" << getOffloadKindAttrName()
304 <<
"' attribute to be attached to '"
305 << mlir::ModuleOp::getOperationName() <<
"'";
307 if (attrName == getModuleFramePointerAttrName()) {
308 if (!mlir::isa<mlir::ModuleOp>(op))
309 return op->emitOpError() <<
"expects '" << getModuleFramePointerAttrName()
310 <<
"' attribute to be attached to '"
311 << mlir::ModuleOp::getOperationName() <<
"'";
312 if (!mlir::isa<cir::FramePointerKindAttr>(
attr.getValue()))
313 return op->emitOpError() <<
"expects '" << getModuleFramePointerAttrName()
314 <<
"' to be a #cir.frame_pointer attribute";
320 if (attrName == getCUDADeviceBinaryAttrName()) {
321 auto bytes = mlir::dyn_cast<mlir::StringAttr>(
attr.getValue());
324 if (!arrayTy || arrayTy.getSize() !=
bytes.size())
325 return op->emitOpError()
326 <<
"expects '" << getCUDADeviceBinaryAttrName()
327 <<
"' to be a string typed as an array of its length";
328 return cir::ConstArrayAttr::verify([&] {
return op->emitOpError(); },
333 if (attrName == getTripleAttrName()) {
334 if (!mlir::isa<mlir::ModuleOp>(op))
335 return op->emitOpError()
336 <<
"expects '" << getTripleAttrName() <<
"' attribute to be "
337 <<
"attached to '" << mlir::ModuleOp::getOperationName() <<
"'";
339 auto tripleStr = mlir::dyn_cast<mlir::StringAttr>(
attr.getValue());
341 return op->emitOpError() <<
"expects '" << getTripleAttrName() <<
"' to "
343 llvm::Triple triple(tripleStr.getValue());
346 if (triple.getArch() == llvm::Triple::UnknownArch)
347 return op->emitOpError()
348 <<
"unknown triple '" << tripleStr.getValue() <<
"' in '"
349 << getTripleAttrName() <<
"' attribute";
352 if (attrName == getOptInfoAttrName()) {
353 if (!mlir::isa<mlir::ModuleOp>(op))
354 return op->emitOpError()
355 <<
"expects '" << getOptInfoAttrName() <<
"' attribute to be "
356 <<
"attached to '" << mlir::ModuleOp::getOperationName() <<
"'";
358 auto optInfo = mlir::dyn_cast<cir::OptInfoAttr>(
attr.getValue());
362 return op->emitOpError()
363 <<
"malformed " << cir::CIRDialect::getOptInfoAttrName()
379 for (
auto en : llvm::enumerate(keywords)) {
380 if (succeeded(parser.parseOptionalKeyword(en.value())))
387template <
typename Ty>
struct EnumTraits {};
389#define REGISTER_ENUM_TYPE(Ty) \
390 template <> struct EnumTraits<cir::Ty> { \
391 static llvm::StringRef stringify(cir::Ty value) { \
392 return stringify##Ty(value); \
394 static unsigned getMaxEnumVal() { return cir::getMaxEnumValFor##Ty(); } \
405template <
typename EnumTy,
typename RetTy = EnumTy>
408 for (
unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
409 names.push_back(EnumTraits<EnumTy>::stringify(
static_cast<EnumTy
>(i)));
413 return static_cast<RetTy
>(defaultValue);
414 return static_cast<RetTy
>(index);
418template <
typename EnumTy,
typename RetTy = EnumTy>
421 for (
unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
422 names.push_back(EnumTraits<EnumTy>::stringify(
static_cast<EnumTy
>(i)));
427 result =
static_cast<RetTy
>(index);
435 Location eLoc = parser.getEncodedSourceLoc(parser.getCurrentLocation());
436 OpBuilder builder(parser.getBuilder().getContext());
441 builder.createBlock(®ion);
443 Block &block = region.back();
445 if (!block.empty() && block.back().hasTrait<OpTrait::IsTerminator>())
449 if (!region.hasOneBlock())
450 return parser.emitError(errLoc,
451 "multi-block region must not omit terminator");
454 builder.setInsertionPointToEnd(&block);
455 cir::YieldOp::create(builder, eLoc);
461 const auto singleNonEmptyBlock = r.hasOneBlock() && !r.back().empty();
462 const auto yieldsNothing = [&r]() {
463 auto y = dyn_cast<cir::YieldOp>(r.back().getTerminator());
464 return y && y.getArgs().empty();
466 return singleNonEmptyBlock && yieldsNothing();
471template <
typename ExpectedProducerOp>
473 StringRef operandName) {
474 Operation *producer = operand.getDefiningOp();
475 if (!producer || !isa<ExpectedProducerOp>(producer))
476 return op->emitOpError()
477 <<
"operand '" << operandName <<
"' must be produced by '"
478 << ExpectedProducerOp::getOperationName() <<
"'";
484 mod->getAttrOfType<mlir::StringAttr>(CIRDialect::getTripleAttrName());
491 return llvm::Triple{tripleAttr.getValue()};
499 cir::InlineKindAttr &inlineKindAttr) {
501 static constexpr llvm::StringRef keywords[] = {
"no_inline",
"always_inline",
505 llvm::StringRef keyword;
506 if (parser.parseOptionalKeyword(&keyword, keywords).failed()) {
512 auto inlineKindResult = ::cir::symbolizeEnum<::cir::InlineKind>(keyword);
513 if (!inlineKindResult) {
514 return parser.emitError(parser.getCurrentLocation(),
"expected one of [")
516 <<
"] for inlineKind, got: " << keyword;
520 ::cir::InlineKindAttr::get(parser.getContext(), *inlineKindResult);
525 if (inlineKindAttr) {
526 p <<
" " << stringifyInlineKind(inlineKindAttr.getValue());
535 mlir::Region ®ion) {
536 auto regionLoc = parser.getCurrentLocation();
537 if (parser.parseRegion(region))
545 cir::ScopeOp &op, mlir::Region ®ion) {
546 printer.printRegion(region,
555void cir::AllocaOp::build(mlir::OpBuilder &odsBuilder,
556 mlir::OperationState &odsState, mlir::Type addr,
557 llvm::StringRef name, mlir::IntegerAttr alignment) {
558 odsState.addAttribute(getNameAttrName(odsState.name),
559 odsBuilder.getStringAttr(name));
561 odsState.addAttribute(getAlignmentAttrName(odsState.name), alignment);
563 odsState.addTypes(addr);
567 mlir::Value ptr = addr;
568 while (cir::CastOp castOp = ptr.getDefiningOp<cir::CastOp>()) {
569 if (!castOp.isAllocaPreservingCast())
571 ptr = castOp.getSrc();
573 return ptr.getDefiningOp<cir::AllocaOp>();
581 auto ptrTy = mlir::cast<cir::PointerType>(op.getAddr().getType());
582 mlir::Type pointeeTy = ptrTy.getPointee();
584 mlir::Block &body = op.getBody().front();
585 if (body.getNumArguments() != 1)
586 return op.emitOpError(
"body must have exactly one block argument");
588 auto expectedEltPtrTy =
589 mlir::dyn_cast<cir::PointerType>(body.getArgument(0).getType());
590 if (!expectedEltPtrTy)
591 return op.emitOpError(
"block argument must be a !cir.ptr type");
593 if (op.getNumElements()) {
594 auto recTy = mlir::dyn_cast<cir::RecordType>(pointeeTy);
596 return op.emitOpError(
597 "when 'num_elements' is present, 'addr' must be a pointer to a "
598 "!cir.struct or !cir.union type");
600 if (expectedEltPtrTy != ptrTy)
601 return op.emitOpError(
"when 'num_elements' is present, 'addr' type must "
602 "match the block argument type");
604 auto arrayTy = mlir::dyn_cast<cir::ArrayType>(pointeeTy);
606 return op.emitOpError(
607 "when 'num_elements' is absent, 'addr' must be a pointer to a "
610 mlir::Type innerEltTy = arrayTy.getElementType();
611 while (
auto nested = mlir::dyn_cast<cir::ArrayType>(innerEltTy))
612 innerEltTy = nested.getElementType();
614 auto recTy = mlir::dyn_cast<cir::RecordType>(innerEltTy);
616 return op.emitOpError(
"the block argument type must be a pointer to a "
617 "!cir.struct or !cir.union type");
619 if (expectedEltPtrTy.getPointee() != innerEltTy)
620 return op.emitOpError(
621 "block argument pointee type must match the innermost array "
624 if (expectedEltPtrTy.getAddrSpace() != ptrTy.getAddrSpace())
625 return op.emitOpError(
626 "block argument address space must match the 'addr' address space");
632LogicalResult cir::ArrayCtor::verify() {
636 mlir::Region &partialDtor = getPartialDtor();
637 if (!partialDtor.empty()) {
638 mlir::Block &dtorBlock = partialDtor.front();
639 if (dtorBlock.getNumArguments() != 1)
640 return emitOpError(
"partial_dtor must have exactly one block argument");
642 auto bodyArgTy = getBody().front().getArgument(0).getType();
643 if (dtorBlock.getArgument(0).getType() != bodyArgTy)
644 return emitOpError(
"partial_dtor block argument type must match "
645 "the body block argument type");
655LogicalResult cir::DeleteArrayOp::verify() {
656 if (getDtorMayThrow() && !getElementDtorAttr())
658 "'dtor_may_throw' requires an 'element_dtor' to be present");
667 cir::AssumeBundleKindAttr kindAttr,
668 OperandRange bundleArgs, TypeRange bundleArgTypes) {
669 cir::AssumeBundleKind
kind = kindAttr.getValue();
670 if (
kind == cir::AssumeBundleKind::None)
673 p <<
" " << cir::stringifyAssumeBundleKind(
kind);
674 if (bundleArgs.empty())
678 p.printOperands(bundleArgs);
680 llvm::interleaveComma(bundleArgTypes, p);
685 OpAsmParser &p, cir::AssumeBundleKindAttr &bundleKindAttr,
689 auto loc = p.getCurrentLocation();
690 if (failed(p.parseOptionalKeyword(&keyword))) {
691 bundleKindAttr = cir::AssumeBundleKindAttr::get(
692 p.getContext(), cir::AssumeBundleKind::None);
696 std::optional<cir::AssumeBundleKind> parsedKind =
697 cir::symbolizeAssumeBundleKind(keyword);
699 return p.emitError(loc,
"unknown assume bundle kind '") << keyword <<
"'";
701 bundleKindAttr = cir::AssumeBundleKindAttr::get(p.getContext(), *parsedKind);
703 if (p.parseOptionalLParen())
706 if (p.parseOperandList(bundleArgs) || p.parseColon() ||
707 p.parseTypeList(bundleArgTypes) || p.parseRParen())
713LogicalResult cir::AssumeOp::verify() {
714 cir::AssumeBundleKind
kind = getBundleKind();
715 size_t numArgs = getBundleArgs().size();
717 if (
kind == cir::AssumeBundleKind::None) {
719 return emitOpError(
"unexpected bundle operands for kind 'none'");
724 return emitOpError(
"expected bundle operands for kind '")
725 << cir::stringifyAssumeBundleKind(
kind) <<
"'";
728 case cir::AssumeBundleKind::Align:
729 if (numArgs != 2 && numArgs != 3)
730 return emitOpError(
"align bundle expects 2 or 3 operands");
732 case cir::AssumeBundleKind::SeparateStorage:
734 return emitOpError(
"separate_storage bundle expects 2 operands");
736 case cir::AssumeBundleKind::Dereferenceable:
738 return emitOpError(
"dereferenceable bundle expects 2 operands");
751cir::LocalInitOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
752 cir::GlobalOp global = getReferencedGlobal(symbolTable);
754 return emitOpError(
"'")
755 << getGlobalName() <<
"' does not reference a valid cir.global";
757 if (getTls() && !global.getTlsModel())
758 return emitOpError(
"access to global not marked thread local");
760 if (!global.getDynamicInitGuard().has_value())
761 return emitOpError(
"static_local attribute mismatch");
773 for (mlir::Operation *parent = op->getParentOp(); parent;
774 parent = parent->getParentOp()) {
775 mlir::Region *ctorRegion =
nullptr;
776 if (
auto global = mlir::dyn_cast<cir::GlobalOp>(parent))
777 ctorRegion = &global.getCtorRegion();
778 else if (
auto localInit = mlir::dyn_cast<cir::LocalInitOp>(parent))
779 ctorRegion = &localInit.getCtorRegion();
780 else if (mlir::isa<cir::FuncOp, cir::RegisterExitDtorOp>(parent))
783 return ctorRegion->isAncestor(op->getParentRegion());
788LogicalResult cir::RegisterExitDtorOp::verify() {
789 mlir::Block &body = getBody().front();
790 if (body.without_terminator().empty())
791 return emitOpError(
"body must destroy the object");
792 if (body.getTerminator()->getNumOperands())
793 return emitOpError(
"body must not yield a value");
795 return emitOpError(
"must be in the ctor region of a cir.global or "
801cir::RegisterExitDtorOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
802 auto global = symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(
803 *
this, getObjectAttr());
805 return emitOpError(
"'")
806 << getObject() <<
"' does not reference a valid cir.global";
807 if (!global.getCtorRegion().empty() || !global.getDtorRegion().empty())
808 return emitOpError(
"object must not have ctor or dtor regions");
820void cir::ConditionOp::getSuccessorRegions(
827 if (
auto loopOp = dyn_cast<LoopOpInterface>(getOperation()->getParentOp())) {
828 regions.emplace_back(&loopOp.getBody());
829 if (mlir::Region *cleanup = loopOp.maybeGetCleanup())
830 regions.emplace_back(cleanup);
832 regions.emplace_back(getOperation());
837 auto await = cast<AwaitOp>(getOperation()->getParentOp());
838 regions.emplace_back(&await.getResume());
839 regions.emplace_back(&await.getSuspend());
843cir::ConditionOp::getMutableSuccessorOperands(RegionSuccessor point) {
845 return MutableOperandRange(getOperation(), 0, 0);
849cir::ResumeOp::getMutableSuccessorOperands(RegionSuccessor point) {
851 return MutableOperandRange(getOperation(), 0, 0);
855cir::CoroSuspendPoint::getMutableSuccessorOperands(RegionSuccessor point) {
857 return MutableOperandRange(getOperation(), 0, 0);
860LogicalResult cir::ConditionOp::verify() {
861 if (!isa<LoopOpInterface, AwaitOp>(getOperation()->getParentOp()))
862 return emitOpError(
"condition must be within a conditional region");
870template <
typename LoopOpTy>
872 std::optional<cir::CleanupKind> cleanupKind = op.getCleanupKind();
876 if (cleanupKind.has_value() == op.getCleanup().empty())
877 return op.emitOpError(
"cleanup kind must be present if and only if the "
878 "cleanup region is non-empty");
883 if (cleanupKind == cir::CleanupKind::EH)
884 return op.emitOpError(
"loop cleanup kind must be 'normal' or 'all', "
899 mlir::Attribute attrType) {
900 if (isa<cir::ConstPtrAttr>(attrType)) {
901 if (!mlir::isa<cir::PointerType>(opType))
902 return op->emitOpError(
903 "pointer constant initializing a non-pointer type");
907 if (isa<cir::DataMemberAttr, cir::DataMemberOffsetAttr, cir::MethodAttr>(
914 if (isa<cir::ZeroAttr>(attrType)) {
915 if (isa<
cir::RecordType, cir::ArrayType, cir::MatrixType, cir::VectorType,
916 cir::ComplexType>(opType))
918 return op->emitOpError(
919 "zero expects struct, array, vector, or complex type");
922 if (mlir::isa<cir::UndefAttr>(attrType)) {
923 if (!mlir::isa<cir::VoidType>(opType))
925 return op->emitOpError(
"undef expects non-void type");
928 if (mlir::isa<cir::BoolAttr>(attrType)) {
929 if (!mlir::isa<cir::BoolType>(opType))
930 return op->emitOpError(
"result type (")
931 << opType <<
") must be '!cir.bool' for '" << attrType <<
"'";
935 if (mlir::isa<cir::IntAttr, cir::FPAttr>(attrType)) {
936 auto at = cast<TypedAttr>(attrType);
937 if (at.getType() != opType) {
938 return op->emitOpError(
"result type (")
939 << opType <<
") does not match value type (" << at.getType()
945 if (mlir::isa<cir::BlockAddrDiffAttr, cir::BlockAddrInfoAttr,
946 cir::ConstArrayAttr, cir::ConstVectorAttr,
947 cir::ConstComplexAttr, cir::ConstRecordAttr,
948 cir::GlobalOffsetAttr, cir::GlobalViewAttr, cir::PoisonAttr,
949 cir::TypeInfoAttr, cir::VTableAttr>(attrType))
952 assert(isa<TypedAttr>(attrType) &&
"What else could we be looking at here?");
953 return op->emitOpError(
"global with type ")
954 << cast<TypedAttr>(attrType).getType() <<
" not yet supported";
957LogicalResult cir::ConstantOp::verify() {
964OpFoldResult cir::ConstantOp::fold(FoldAdaptor ) {
974 case cir::CastKind::floating:
975 case cir::CastKind::int_to_float:
976 case cir::CastKind::float_to_int:
977 case cir::CastKind::float_to_bool:
978 case cir::CastKind::bool_to_float:
979 case cir::CastKind::float_to_complex:
980 case cir::CastKind::float_complex_to_real:
981 case cir::CastKind::float_complex_to_bool:
982 case cir::CastKind::float_complex:
983 case cir::CastKind::float_complex_to_int_complex:
984 case cir::CastKind::int_complex_to_float_complex:
991LogicalResult cir::CastOp::verify() {
992 mlir::Type resType =
getType();
993 mlir::Type srcType = getSrc().getType();
998 <<
"'fenv' is only valid for floating-point cast kinds";
1002 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
1003 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
1004 if (srcPtrTy && resPtrTy && (
kind != cir::CastKind::address_space))
1005 if (srcPtrTy.getAddrSpace() != resPtrTy.getAddrSpace()) {
1006 return emitOpError() <<
"result type address space does not match the "
1007 "address space of the operand";
1010 auto srcVTy = mlir::dyn_cast<cir::VectorType>(srcType);
1011 auto resVTy = mlir::dyn_cast<cir::VectorType>(resType);
1012 if (srcVTy && resVTy) {
1013 if ((
kind == cir::CastKind::int_to_float ||
1014 kind == cir::CastKind::float_to_int) &&
1015 srcVTy.getSize() != resVTy.getSize()) {
1016 return emitOpError()
1017 <<
"vector float-to-int and int-to-float casts require "
1018 "source and destination vectors to have the same number of "
1023 srcType = srcVTy.getElementType();
1024 resType = resVTy.getElementType();
1028 case cir::CastKind::int_to_bool: {
1029 if (!mlir::isa<cir::BoolType>(resType))
1030 return emitOpError() <<
"requires !cir.bool type for result";
1031 if (!mlir::isa<cir::IntType>(srcType))
1032 return emitOpError() <<
"requires !cir.int type for source";
1035 case cir::CastKind::ptr_to_bool: {
1036 if (!mlir::isa<cir::BoolType>(resType))
1037 return emitOpError() <<
"requires !cir.bool type for result";
1038 if (!mlir::isa<cir::PointerType>(srcType))
1039 return emitOpError() <<
"requires !cir.ptr type for source";
1042 case cir::CastKind::integral: {
1043 if (!mlir::isa<cir::IntType>(resType))
1044 return emitOpError() <<
"requires !cir.int type for result";
1045 if (!mlir::isa<cir::IntType>(srcType))
1046 return emitOpError() <<
"requires !cir.int type for source";
1049 case cir::CastKind::array_to_ptrdecay: {
1050 const auto arrayPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
1051 const auto flatPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
1052 if (!arrayPtrTy || !flatPtrTy)
1053 return emitOpError() <<
"requires !cir.ptr type for source and result";
1058 case cir::CastKind::bitcast: {
1060 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
1061 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
1063 if (srcPtrTy && resPtrTy) {
1069 case cir::CastKind::floating: {
1070 if (!mlir::isa<cir::FPTypeInterface>(srcType) ||
1071 !mlir::isa<cir::FPTypeInterface>(resType))
1072 return emitOpError() <<
"requires !cir.float type for source and result";
1075 case cir::CastKind::float_to_int: {
1076 if (!mlir::isa<cir::FPTypeInterface>(srcType))
1077 return emitOpError() <<
"requires !cir.float type for source";
1078 if (!mlir::dyn_cast<cir::IntType>(resType))
1079 return emitOpError() <<
"requires !cir.int type for result";
1082 case cir::CastKind::int_to_ptr: {
1083 if (!mlir::dyn_cast<cir::IntType>(srcType))
1084 return emitOpError() <<
"requires !cir.int type for source";
1085 if (!mlir::dyn_cast<cir::PointerType>(resType))
1086 return emitOpError() <<
"requires !cir.ptr type for result";
1089 case cir::CastKind::ptr_to_int: {
1090 if (!mlir::dyn_cast<cir::PointerType>(srcType))
1091 return emitOpError() <<
"requires !cir.ptr type for source";
1092 if (!mlir::dyn_cast<cir::IntType>(resType))
1093 return emitOpError() <<
"requires !cir.int type for result";
1096 case cir::CastKind::float_to_bool: {
1097 if (!mlir::isa<cir::FPTypeInterface>(srcType))
1098 return emitOpError() <<
"requires !cir.float type for source";
1099 if (!mlir::isa<cir::BoolType>(resType))
1100 return emitOpError() <<
"requires !cir.bool type for result";
1103 case cir::CastKind::bool_to_int: {
1104 if (!mlir::isa<cir::BoolType>(srcType))
1105 return emitOpError() <<
"requires !cir.bool type for source";
1106 if (!mlir::isa<cir::IntType>(resType))
1107 return emitOpError() <<
"requires !cir.int type for result";
1110 case cir::CastKind::int_to_float: {
1111 if (!mlir::isa<cir::IntType>(srcType))
1112 return emitOpError() <<
"requires !cir.int type for source";
1113 if (!mlir::isa<cir::FPTypeInterface>(resType))
1114 return emitOpError() <<
"requires !cir.float type for result";
1117 case cir::CastKind::bool_to_float: {
1118 if (!mlir::isa<cir::BoolType>(srcType))
1119 return emitOpError() <<
"requires !cir.bool type for source";
1120 if (!mlir::isa<cir::FPTypeInterface>(resType))
1121 return emitOpError() <<
"requires !cir.float type for result";
1124 case cir::CastKind::address_space: {
1125 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
1126 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
1127 if (!srcPtrTy || !resPtrTy)
1128 return emitOpError() <<
"requires !cir.ptr type for source and result";
1129 if (srcPtrTy.getPointee() != resPtrTy.getPointee())
1130 return emitOpError() <<
"requires two types differ in addrspace only";
1133 case cir::CastKind::float_to_complex: {
1134 if (!mlir::isa<cir::FPTypeInterface>(srcType))
1135 return emitOpError() <<
"requires !cir.float type for source";
1136 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
1138 return emitOpError() <<
"requires !cir.complex type for result";
1139 if (srcType != resComplexTy.getElementType())
1140 return emitOpError() <<
"requires source type match result element type";
1143 case cir::CastKind::int_to_complex: {
1144 if (!mlir::isa<cir::IntType>(srcType))
1145 return emitOpError() <<
"requires !cir.int type for source";
1146 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
1148 return emitOpError() <<
"requires !cir.complex type for result";
1149 if (srcType != resComplexTy.getElementType())
1150 return emitOpError() <<
"requires source type match result element type";
1153 case cir::CastKind::float_complex_to_real: {
1154 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1156 return emitOpError() <<
"requires !cir.complex type for source";
1157 if (!mlir::isa<cir::FPTypeInterface>(resType))
1158 return emitOpError() <<
"requires !cir.float type for result";
1159 if (srcComplexTy.getElementType() != resType)
1160 return emitOpError() <<
"requires source element type match result type";
1163 case cir::CastKind::int_complex_to_real: {
1164 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1166 return emitOpError() <<
"requires !cir.complex type for source";
1167 if (!mlir::isa<cir::IntType>(resType))
1168 return emitOpError() <<
"requires !cir.int type for result";
1169 if (srcComplexTy.getElementType() != resType)
1170 return emitOpError() <<
"requires source element type match result type";
1173 case cir::CastKind::float_complex_to_bool: {
1174 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1175 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
1176 return emitOpError()
1177 <<
"requires floating point !cir.complex type for source";
1178 if (!mlir::isa<cir::BoolType>(resType))
1179 return emitOpError() <<
"requires !cir.bool type for result";
1182 case cir::CastKind::int_complex_to_bool: {
1183 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1184 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
1185 return emitOpError()
1186 <<
"requires floating point !cir.complex type for source";
1187 if (!mlir::isa<cir::BoolType>(resType))
1188 return emitOpError() <<
"requires !cir.bool type for result";
1191 case cir::CastKind::float_complex: {
1192 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1193 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
1194 return emitOpError()
1195 <<
"requires floating point !cir.complex type for source";
1196 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
1197 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
1198 return emitOpError()
1199 <<
"requires floating point !cir.complex type for result";
1202 case cir::CastKind::float_complex_to_int_complex: {
1203 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1204 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
1205 return emitOpError()
1206 <<
"requires floating point !cir.complex type for source";
1207 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
1208 if (!resComplexTy || !resComplexTy.isIntegerComplex())
1209 return emitOpError() <<
"requires integer !cir.complex type for result";
1212 case cir::CastKind::int_complex: {
1213 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1214 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
1215 return emitOpError() <<
"requires integer !cir.complex type for source";
1216 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
1217 if (!resComplexTy || !resComplexTy.isIntegerComplex())
1218 return emitOpError() <<
"requires integer !cir.complex type for result";
1221 case cir::CastKind::int_complex_to_float_complex: {
1222 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1223 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
1224 return emitOpError() <<
"requires integer !cir.complex type for source";
1225 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
1226 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
1227 return emitOpError()
1228 <<
"requires floating point !cir.complex type for result";
1231 case cir::CastKind::member_ptr_to_bool: {
1232 if (!mlir::isa<cir::DataMemberType, cir::MethodType>(srcType))
1233 return emitOpError()
1234 <<
"requires !cir.data_member or !cir.method type for source";
1235 if (!mlir::isa<cir::BoolType>(resType))
1236 return emitOpError() <<
"requires !cir.bool type for result";
1240 llvm_unreachable(
"Unknown CastOp kind?");
1244 auto kind = op.getKind();
1245 return kind == cir::CastKind::bool_to_int ||
1246 kind == cir::CastKind::int_to_bool ||
kind == cir::CastKind::integral;
1250 const auto ptrTy = mlir::dyn_cast<cir::PointerType>(ty);
1251 return ptrTy && mlir::isa<cir::FuncType>(ptrTy.getPointee());
1255 cir::CastOp head = op, tail = op;
1261 op = head.getSrc().getDefiningOp<cir::CastOp>();
1267 if (head.getKind() == cir::CastKind::bool_to_int &&
1268 tail.getKind() == cir::CastKind::int_to_bool)
1269 return head.getSrc();
1274 if (head.getKind() == cir::CastKind::int_to_bool &&
1275 tail.getKind() == cir::CastKind::int_to_bool)
1276 return head.getResult();
1284 if (tail.getKind() == cir::CastKind::bitcast) {
1285 auto *inner = tail.getSrc().getDefiningOp();
1287 auto innerCast = mlir::dyn_cast<cir::CastOp>(inner);
1288 if (innerCast && innerCast.getKind() == cir::CastKind::bitcast &&
1289 innerCast.getSrc().getType() == tail.getType() &&
1290 innerCast.getType() == tail.getSrc().getType()) {
1291 return innerCast.getSrc();
1299OpFoldResult cir::CastOp::fold(FoldAdaptor adaptor) {
1300 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getSrc())) {
1302 return cir::PoisonAttr::get(getContext(),
getType());
1306 if (mlir::isa_and_present<cir::UndefAttr>(adaptor.getSrc()))
1307 return cir::UndefAttr::get(
getType());
1311 case cir::CastKind::integral:
1312 case cir::CastKind::bitcast:
1313 case cir::CastKind::address_space:
1314 case cir::CastKind::float_complex:
1315 case cir::CastKind::int_complex: {
1329 if (
auto srcConst = getSrc().getDefiningOp<cir::ConstantOp>()) {
1331 case cir::CastKind::integral: {
1332 mlir::Type srcTy = getSrc().getType();
1334 assert(mlir::isa<cir::VectorType>(srcTy) ==
1335 mlir::isa<cir::VectorType>(
getType()));
1336 if (mlir::isa<cir::VectorType>(srcTy))
1339 auto srcIntTy = mlir::cast<cir::IntType>(srcTy);
1340 auto dstIntTy = mlir::cast<cir::IntType>(
getType());
1341 auto constIntAttr = srcConst.getValueAttr<cir::IntAttr>();
1345 APInt srcValue = constIntAttr.getValue();
1346 APInt newVal = srcIntTy.isSigned()
1347 ? srcValue.sextOrTrunc(dstIntTy.getWidth())
1348 : srcValue.zextOrTrunc(dstIntTy.getWidth());
1349 return cir::IntAttr::get(dstIntTy, newVal);
1362LogicalResult cir::BuiltinIntCastOp::verify() {
1363 mlir::Type srcType = getSrc().getType();
1364 mlir::Type resType =
getType();
1366 auto srcCirInt = mlir::dyn_cast<cir::IntType>(srcType);
1367 auto resCirInt = mlir::dyn_cast<cir::IntType>(resType);
1371 if (
static_cast<bool>(srcCirInt) ==
static_cast<bool>(resCirInt))
1372 return emitOpError()
1373 <<
"requires exactly one '!cir.int' operand or result; the other "
1374 "must be a builtin integer or 'index' type";
1376 mlir::Type
builtinType = srcCirInt ? resType : srcType;
1377 if (!mlir::isa<mlir::IntegerType, mlir::IndexType>(builtinType))
1378 return emitOpError() <<
"requires a builtin integer or 'index' type on the "
1383 if (
auto builtinInt = mlir::dyn_cast<mlir::IntegerType>(builtinType)) {
1384 cir::IntType cirInt = srcCirInt ? srcCirInt : resCirInt;
1385 if (cirInt.getWidth() != builtinInt.getWidth())
1386 return emitOpError()
1387 <<
"requires the CIR and builtin integer types to have the same "
1388 "width; use 'cir.cast' for width conversions";
1394OpFoldResult cir::BuiltinIntCastOp::fold(FoldAdaptor adaptor) {
1397 if (
auto inner = getSrc().getDefiningOp<cir::BuiltinIntCastOp>())
1398 if (inner.getSrc().getType() ==
getType())
1399 return inner.getSrc();
1407mlir::OperandRange cir::CallOp::getArgOperands() {
1409 return getArgs().drop_front(1);
1413mlir::MutableOperandRange cir::CallOp::getArgOperandsMutable() {
1414 mlir::MutableOperandRange args = getArgsMutable();
1416 return args.slice(1, args.size() - 1);
1420mlir::Value cir::CallOp::getIndirectCall() {
1421 assert(isIndirect());
1422 return getOperand(0);
1426Value cir::CallOp::getArgOperand(
unsigned i) {
1429 return getOperand(i);
1433unsigned cir::CallOp::getNumArgOperands() {
1435 return this->getOperation()->getNumOperands() - 1;
1436 return this->getOperation()->getNumOperands();
1439static mlir::ParseResult
1441 mlir::OperationState &result) {
1442 mlir::Block *normalDestSuccessor;
1443 if (parser.parseSuccessor(normalDestSuccessor))
1444 return mlir::failure();
1446 if (parser.parseComma())
1447 return mlir::failure();
1449 mlir::Block *unwindDestSuccessor;
1450 if (parser.parseSuccessor(unwindDestSuccessor))
1451 return mlir::failure();
1453 result.addSuccessors(normalDestSuccessor);
1454 result.addSuccessors(unwindDestSuccessor);
1455 return mlir::success();
1464 const mlir::NamedAttrList &attrs) {
1465 if (mlir::Attribute effects =
1466 attrs.get(CIRDialect::getMemoryEffectsAttrName()))
1467 if (!mlir::isa<cir::MemoryEffectsAttr>(effects))
1468 return parser.emitError(loc,
"attribute '")
1469 << CIRDialect::getMemoryEffectsAttrName()
1470 <<
"' must be a #cir.memory_effects attribute";
1472 if (mlir::Attribute uwtable = attrs.get(CIRDialect::getUwtableAttrName()))
1473 if (!mlir::isa<cir::UnwindTableKindAttr>(uwtable))
1474 return parser.emitError(loc,
"attribute '")
1475 << CIRDialect::getUwtableAttrName()
1476 <<
"' must be a #cir.uwtable attribute";
1478 if (mlir::Attribute framePointer =
1479 attrs.get(CIRDialect::getFramePointerAttrName()))
1480 if (!mlir::isa<cir::FramePointerKindAttr>(framePointer))
1481 return parser.emitError(loc,
"attribute '")
1482 << CIRDialect::getFramePointerAttrName()
1483 <<
"' must be a #cir.frame_pointer attribute";
1485 for (llvm::StringRef name :
1486 {CIRDialect::getNoUnwindAttrName(), CIRDialect::getWillReturnAttrName(),
1487 CIRDialect::getMustProgressAttrName()})
1488 if (mlir::Attribute flag = attrs.get(name))
1489 if (!mlir::isa<mlir::UnitAttr>(flag))
1490 return parser.emitError(loc,
"attribute '")
1491 << name <<
"' must be a unit attribute";
1493 return mlir::success();
1497 mlir::OperationState &result,
1498 bool hasDestinationBlocks =
false) {
1501 mlir::FlatSymbolRefAttr calleeAttr;
1505 .parseOptionalAttribute(calleeAttr, CIRDialect::getCalleeAttrName(),
1508 OpAsmParser::UnresolvedOperand indirectVal;
1510 if (parser.parseOperand(indirectVal).failed())
1512 ops.push_back(indirectVal);
1515 if (parser.parseLParen())
1516 return mlir::failure();
1518 opsLoc = parser.getCurrentLocation();
1519 if (parser.parseOperandList(ops))
1520 return mlir::failure();
1521 if (parser.parseRParen())
1522 return mlir::failure();
1524 if (hasDestinationBlocks &&
1526 return ::mlir::failure();
1529 if (parser.parseOptionalKeyword(
"cc").succeeded()) {
1530 cir::CallingConv callingConv;
1531 if (parser.parseLParen().failed())
1534 return parser.emitError(parser.getCurrentLocation(),
1535 "unknown calling convention");
1536 if (parser.parseRParen().failed())
1538 result.addAttribute(
1539 CIRDialect::getCallingConvAttrName(),
1540 cir::CallingConvAttr::get(parser.getContext(), callingConv));
1543 if (parser.parseOptionalKeyword(
"musttail").succeeded())
1544 result.addAttribute(CIRDialect::getMustTailAttrName(),
1545 mlir::UnitAttr::get(parser.getContext()));
1547 if (parser.parseOptionalKeyword(
"nothrow").succeeded())
1548 result.addAttribute(CIRDialect::getNoThrowAttrName(),
1549 mlir::UnitAttr::get(parser.getContext()));
1551 if (parser.parseOptionalKeyword(
"nounwind").succeeded())
1552 result.addAttribute(CIRDialect::getNoUnwindAttrName(),
1553 mlir::UnitAttr::get(parser.getContext()));
1555 if (parser.parseOptionalKeyword(
"willreturn").succeeded())
1556 result.addAttribute(CIRDialect::getWillReturnAttrName(),
1557 mlir::UnitAttr::get(parser.getContext()));
1559 llvm::SMLoc attrsLoc = parser.getCurrentLocation();
1560 if (parser.parseOptionalAttrDict(result.attributes))
1561 return ::mlir::failure();
1564 return ::mlir::failure();
1566 if (parser.parseColon())
1567 return ::mlir::failure();
1573 if (call_interface_impl::parseFunctionSignature(parser, argTypes, argAttrs,
1574 resultTypes, resultAttrs))
1575 return mlir::failure();
1577 if (resultTypes.size() > 1 || resultAttrs.size() > 1)
1578 return parser.emitError(
1579 parser.getCurrentLocation(),
1580 "functions with multiple return types are not supported");
1582 result.addTypes(resultTypes);
1584 if (parser.resolveOperands(ops, argTypes, opsLoc, result.operands))
1585 return mlir::failure();
1587 if (!resultAttrs.empty() && resultAttrs[0])
1588 result.addAttribute(
1589 CIRDialect::getResAttrsAttrName(),
1590 mlir::ArrayAttr::get(parser.getContext(), {resultAttrs[0]}));
1595 bool argAttrsEmpty =
true;
1597 llvm::transform(argAttrs, std::back_inserter(convertedArgAttrs),
1598 [&](DictionaryAttr da) -> mlir::Attribute {
1600 argAttrsEmpty =
false;
1604 if (!argAttrsEmpty) {
1609 argAttrsRef = argAttrsRef.drop_front();
1611 result.addAttribute(CIRDialect::getArgAttrsAttrName(),
1612 mlir::ArrayAttr::get(parser.getContext(), argAttrsRef));
1615 return mlir::success();
1619 mlir::FlatSymbolRefAttr calleeSym,
1620 mlir::Value indirectCallee,
1621 mlir::OpAsmPrinter &printer,
bool isNothrow,
1622 ArrayAttr argAttrs, ArrayAttr resAttrs,
1623 mlir::Block *normalDest =
nullptr,
1624 mlir::Block *unwindDest =
nullptr) {
1627 auto callLikeOp = mlir::cast<cir::CIRCallOpInterface>(op);
1628 auto ops = callLikeOp.getArgOperands();
1632 printer.printAttributeWithoutType(calleeSym);
1635 assert(indirectCallee);
1636 printer << indirectCallee;
1639 printer <<
"(" << ops <<
")";
1642 assert(unwindDest &&
"expected two successors");
1643 auto tryCall = cast<cir::TryCallOp>(op);
1644 printer <<
' ' << tryCall.getNormalDest();
1647 printer << tryCall.getUnwindDest();
1650 cir::CallingConv callingConv = callLikeOp.getCallingConv();
1651 if (callingConv != cir::CallingConv::C)
1652 printer <<
" cc(" << stringifyCallingConv(callingConv) <<
")";
1654 if (op->hasAttr(CIRDialect::getMustTailAttrName()))
1655 printer <<
" musttail";
1658 printer <<
" nothrow";
1660 if (op->hasAttr(CIRDialect::getNoUnwindAttrName()))
1661 printer <<
" nounwind";
1663 if (op->hasAttr(CIRDialect::getWillReturnAttrName()))
1664 printer <<
" willreturn";
1666 llvm::StringRef elidedAttrs[] = {
1667 CIRDialect::getCalleeAttrName(),
1668 CIRDialect::getCallingConvAttrName(),
1669 CIRDialect::getMustTailAttrName(),
1670 CIRDialect::getNoThrowAttrName(),
1671 CIRDialect::getNoUnwindAttrName(),
1672 CIRDialect::getWillReturnAttrName(),
1673 CIRDialect::getOperandSegmentSizesAttrName(),
1680 for (mlir::NamedAttribute attr : op->getDiscardableAttrs())
1681 if (!llvm::is_contained(elidedAttrs, attr.getName()))
1682 attrs.push_back(attr);
1683 op->getName().walkInherentAttrs(op, [&](llvm::StringRef name,
1684 mlir::Attribute &attr) {
1685 if (!llvm::is_contained(elidedAttrs, name))
1686 attrs.emplace_back(mlir::StringAttr::get(op->getContext(), name), attr);
1688 llvm::sort(attrs, [](mlir::NamedAttribute lhs, mlir::NamedAttribute rhs) {
1689 return lhs.getName().strref() < rhs.getName().strref();
1691 printer.printOptionalAttrDict(attrs);
1693 if (calleeSym || !argAttrs) {
1694 call_interface_impl::printFunctionSignature(
1695 printer, op->getOperands().getTypes(), argAttrs,
1696 false, op->getResultTypes(), resAttrs);
1704 shimmedArgAttrs.push_back(mlir::DictionaryAttr::get(op->getContext(), {}));
1705 shimmedArgAttrs.append(argAttrs.begin(), argAttrs.end());
1706 call_interface_impl::printFunctionSignature(
1707 printer, op->getOperands().getTypes(),
1708 mlir::ArrayAttr::get(op->getContext(), shimmedArgAttrs),
1709 false, op->getResultTypes(), resAttrs);
1713mlir::ParseResult cir::CallOp::parse(mlir::OpAsmParser &parser,
1714 mlir::OperationState &result) {
1718void cir::CallOp::print(mlir::OpAsmPrinter &p) {
1719 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() :
nullptr;
1720 printCallCommon(*
this, getCalleeAttr(), indirectCallee, p, getNothrow(),
1721 getArgAttrsAttr(), getResAttrsAttr());
1726 SymbolTableCollection &symbolTable) {
1727 auto callIf = cast<cir::CIRCallOpInterface>(op);
1731 cir::FuncType fnType;
1732 bool hasPrototype =
true;
1734 op->getAttrOfType<FlatSymbolRefAttr>(CIRDialect::getCalleeAttrName());
1736 if (op->getNumOperands() == 0)
1737 return op->emitOpError(
"indirect call requires a callee operand");
1738 mlir::Type calleeTy = callIf.getIndirectCall().getType();
1739 if (
auto ptrTy = mlir::dyn_cast<cir::PointerType>(calleeTy))
1740 fnType = mlir::dyn_cast<cir::FuncType>(ptrTy.getPointee());
1742 return op->emitOpError()
1743 <<
"indirect callee must be a pointer to a function, but has type "
1746 auto fn = symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(op, fnAttr);
1748 return op->emitOpError() <<
"'" << fnAttr.getValue()
1749 <<
"' does not reference a valid function";
1750 fnType = fn.getFunctionType();
1751 hasPrototype = !fn.getNoProto();
1757 unsigned numCallOperands = callIf.getNumArgOperands();
1758 unsigned numFnOpOperands = fnType.getNumInputs();
1760 if (!fnType.isVarArg() && numCallOperands != numFnOpOperands)
1761 return op->emitOpError(
"incorrect number of operands for callee");
1762 if (fnType.isVarArg() && numCallOperands < numFnOpOperands)
1763 return op->emitOpError(
"too few operands for callee");
1765 for (
unsigned i = 0, e = numFnOpOperands; i != e; ++i)
1766 if (callIf.getArgOperand(i).getType() != fnType.getInput(i))
1767 return op->emitOpError(
"operand type mismatch: expected operand type ")
1768 << fnType.getInput(i) <<
", but provided "
1769 << callIf.getArgOperand(i).getType() <<
" for operand number "
1776 if (fnType.hasVoidReturn() && op->getNumResults() != 0)
1777 return op->emitOpError(
"callee returns void but call has results");
1780 if (!fnType.hasVoidReturn() && op->getNumResults() != 1)
1781 return op->emitOpError(
"incorrect number of results for callee");
1784 if (!fnType.hasVoidReturn() &&
1785 op->getResultTypes().front() != fnType.getReturnType()) {
1786 return op->emitOpError(
"result type mismatch: expected ")
1787 << fnType.getReturnType() <<
", but provided "
1788 << op->getResult(0).getType();
1791 return mlir::success();
1795cir::CallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1803mlir::OperandRange cir::TryCallOp::getArgOperands() {
1805 return getArgs().drop_front(1);
1809mlir::MutableOperandRange cir::TryCallOp::getArgOperandsMutable() {
1810 mlir::MutableOperandRange args = getArgsMutable();
1812 return args.slice(1, args.size() - 1);
1816mlir::Value cir::TryCallOp::getIndirectCall() {
1817 assert(isIndirect());
1818 return getOperand(0);
1822Value cir::TryCallOp::getArgOperand(
unsigned i) {
1825 return getOperand(i);
1829unsigned cir::TryCallOp::getNumArgOperands() {
1831 return this->getOperation()->getNumOperands() - 1;
1832 return this->getOperation()->getNumOperands();
1836cir::TryCallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1840mlir::ParseResult cir::TryCallOp::parse(mlir::OpAsmParser &parser,
1841 mlir::OperationState &result) {
1845void cir::TryCallOp::print(::mlir::OpAsmPrinter &p) {
1846 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() :
nullptr;
1847 printCallCommon(*
this, getCalleeAttr(), indirectCallee, p, getNothrow(),
1848 getArgAttrsAttr(), getResAttrsAttr(), getNormalDest(),
1857 cir::FuncOp function) {
1859 if (op.getNumOperands() > 1)
1860 return op.emitOpError() <<
"expects at most 1 return operand";
1863 auto expectedTy = function.getFunctionType().getReturnType();
1865 (op.getNumOperands() == 0 ? cir::VoidType::get(op.getContext())
1866 : op.getOperand(0).getType());
1867 if (actualTy != expectedTy)
1868 return op.emitOpError() <<
"returns " << actualTy
1869 <<
" but enclosing function returns " << expectedTy;
1871 return mlir::success();
1874mlir::LogicalResult cir::ReturnOp::verify() {
1877 auto *fnOp = getOperation()->getParentOp();
1878 while (!isa<cir::FuncOp>(fnOp))
1879 fnOp = fnOp->getParentOp();
1892ParseResult cir::IfOp::parse(OpAsmParser &parser, OperationState &result) {
1894 result.regions.reserve(2);
1895 Region *thenRegion = result.addRegion();
1896 Region *elseRegion = result.addRegion();
1898 mlir::Builder &builder = parser.getBuilder();
1899 OpAsmParser::UnresolvedOperand cond;
1900 Type boolType = cir::BoolType::get(builder.getContext());
1902 if (parser.parseOperand(cond) ||
1903 parser.resolveOperand(cond, boolType, result.operands))
1907 mlir::SMLoc parseThenLoc = parser.getCurrentLocation();
1908 if (parser.parseRegion(*thenRegion, {}, {}))
1915 if (!parser.parseOptionalKeyword(
"else")) {
1916 mlir::SMLoc parseElseLoc = parser.getCurrentLocation();
1917 if (parser.parseRegion(*elseRegion, {}, {}))
1924 if (parser.parseOptionalAttrDict(result.attributes))
1929void cir::IfOp::print(OpAsmPrinter &p) {
1930 p <<
" " << getCondition() <<
" ";
1931 mlir::Region &thenRegion = this->getThenRegion();
1932 p.printRegion(thenRegion,
1937 mlir::Region &elseRegion = this->getElseRegion();
1938 if (!elseRegion.empty()) {
1940 p.printRegion(elseRegion,
1945 p.printOptionalAttrDict(
1946 getOperation()->getDiscardableAttrDictionary().getValue());
1952 cir::YieldOp::create(builder, loc);
1960void cir::IfOp::getSuccessorRegions(mlir::RegionBranchPoint point,
1961 SmallVectorImpl<RegionSuccessor> ®ions) {
1963 if (!point.isParent()) {
1964 regions.emplace_back(getOperation());
1969 Region *elseRegion = &this->getElseRegion();
1970 if (elseRegion->empty())
1971 elseRegion =
nullptr;
1974 regions.push_back(RegionSuccessor(&getThenRegion()));
1976 regions.push_back(RegionSuccessor(elseRegion));
1978 regions.emplace_back(getOperation());
1981void cir::IfOp::build(OpBuilder &builder, OperationState &result,
Value cond,
1984 assert(thenBuilder &&
"the builder callback for 'then' must be present");
1985 result.addOperands(cond);
1987 OpBuilder::InsertionGuard guard(builder);
1988 Region *thenRegion = result.addRegion();
1989 builder.createBlock(thenRegion);
1990 thenBuilder(builder, result.location);
1992 Region *elseRegion = result.addRegion();
1993 if (!withElseRegion)
1996 builder.createBlock(elseRegion);
1997 elseBuilder(builder, result.location);
2004void cir::ScopeOp::build(
2005 OpBuilder &builder, OperationState &result,
2006 function_ref<
void(OpBuilder &, Type &, Location)> scopeBuilder) {
2007 assert(scopeBuilder &&
"the builder callback for 'then' must be present");
2009 OpBuilder::InsertionGuard guard(builder);
2010 Region *scopeRegion = result.addRegion();
2011 builder.createBlock(scopeRegion);
2015 scopeBuilder(builder, yieldTy, result.location);
2018 result.addTypes(TypeRange{yieldTy});
2021void cir::ScopeOp::build(
2022 OpBuilder &builder, OperationState &result,
2023 function_ref<
void(OpBuilder &, Location)> scopeBuilder) {
2024 assert(scopeBuilder &&
"the builder callback for 'then' must be present");
2025 OpBuilder::InsertionGuard guard(builder);
2026 Region *scopeRegion = result.addRegion();
2027 builder.createBlock(scopeRegion);
2029 scopeBuilder(builder, result.location);
2032LogicalResult cir::ScopeOp::verify() {
2033 if (getRegion().empty()) {
2034 return emitOpError() <<
"cir.scope must not be empty since it should "
2035 "include at least an implicit cir.yield ";
2038 mlir::Block &lastBlock = getRegion().back();
2039 if (lastBlock.empty() || !lastBlock.mightHaveTerminator() ||
2040 !lastBlock.getTerminator()->hasTrait<OpTrait::IsTerminator>())
2041 return emitOpError() <<
"last block of cir.scope must be terminated";
2045LogicalResult cir::ScopeOp::fold(FoldAdaptor ,
2046 SmallVectorImpl<OpFoldResult> &results) {
2048 if (!getRegion().hasOneBlock())
2050 Block &block = getRegion().front();
2051 if (block.getOperations().size() != 1)
2054 auto yield = dyn_cast<cir::YieldOp>(block.front());
2059 if (getNumResults() != 1 || yield.getNumOperands() != 1)
2062 results.push_back(yield.getOperand(0));
2071 for (mlir::Block &block : cleanupRegion) {
2072 for (mlir::Operation &op : block) {
2073 if (isa<cir::YieldOp, cir::LifetimeEndOp, cir::StackRestoreOp>(op))
2076 auto loadOp = dyn_cast<cir::LoadOp>(op);
2077 if (loadOp && loadOp.getResult().hasOneUse() &&
2078 isa<cir::StackRestoreOp>(*loadOp.getResult().getUsers().begin()))
2086LogicalResult cir::CleanupScopeOp::verify() {
2090 cir::CallOp mustTailCall;
2091 getBodyRegion().walk([&](cir::CallOp callOp) {
2092 if (!callOp.getMusttail())
2093 return WalkResult::advance();
2094 mustTailCall = callOp;
2095 return WalkResult::interrupt();
2103 InFlightDiagnostic diag =
2104 emitOpError(
"cleanup is not redundant before a return, so it cannot be "
2105 "skipped by a musttail call");
2106 diag.attachNote(mustTailCall.getLoc()) <<
"musttail call is here";
2110void cir::CleanupScopeOp::getSuccessorRegions(
2111 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
2116 if (point.isParent()) {
2117 regions.reserve(regions.size() + 2);
2118 regions.emplace_back(&getBodyRegion());
2119 regions.emplace_back(&getCleanupRegion());
2123 mlir::Operation *term = point.getTerminatorPredecessorOrNull();
2124 if (term->getParentRegion() == &getCleanupRegion()) {
2125 regions.emplace_back(getOperation());
2129 regions.emplace_back(&getCleanupRegion());
2134 cir::CleanupKindAttr
kind = getCleanupKindAttr();
2135 if (isa<cir::ResumeOp>(term) ? !
kind.isEH() : !
kind.isNormal())
2136 regions.emplace_back(getOperation());
2139LogicalResult cir::CleanupScopeOp::canonicalize(CleanupScopeOp op,
2140 PatternRewriter &rewriter) {
2141 auto isRegionTrivial = [](Region ®ion) {
2142 assert(!region.empty() &&
"CleanupScopeOp regions must not be empty");
2143 if (!region.hasOneBlock())
2145 Block &block = llvm::getSingleElement(region);
2146 return llvm::hasSingleElement(block) &&
2147 isa<cir::YieldOp>(llvm::getSingleElement(block));
2150 Region &body = op.getBodyRegion();
2151 Region &
cleanup = op.getCleanupRegion();
2155 if (op.getCleanupKind() == CleanupKind::EH && isRegionTrivial(body)) {
2156 rewriter.eraseOp(op);
2162 if (!isRegionTrivial(cleanup) || !body.hasOneBlock())
2165 Block &bodyBlock = body.front();
2166 if (!isa<cir::YieldOp>(bodyBlock.getTerminator()))
2169 Operation *yield = bodyBlock.getTerminator();
2170 rewriter.inlineBlockBefore(&bodyBlock, op);
2171 rewriter.eraseOp(yield);
2172 rewriter.eraseOp(op);
2176void cir::CleanupScopeOp::build(
2177 OpBuilder &builder, OperationState &result, CleanupKind cleanupKind,
2178 function_ref<
void(OpBuilder &, Location)> bodyBuilder,
2179 function_ref<
void(OpBuilder &, Location)> cleanupBuilder) {
2180 result.addAttribute(getCleanupKindAttrName(result.name),
2181 CleanupKindAttr::get(builder.getContext(), cleanupKind));
2183 OpBuilder::InsertionGuard guard(builder);
2186 Region *bodyRegion = result.addRegion();
2187 builder.createBlock(bodyRegion);
2189 bodyBuilder(builder, result.location);
2192 Region *cleanupRegion = result.addRegion();
2193 builder.createBlock(cleanupRegion);
2195 cleanupBuilder(builder, result.location);
2210LogicalResult cir::BrOp::canonicalize(BrOp op, PatternRewriter &rewriter) {
2211 Block *src = op->getBlock();
2212 Block *dst = op.getDest();
2219 if (src->getNumSuccessors() != 1 || dst->getSinglePredecessor() != src)
2224 if (isa<cir::LabelOp, cir::IndirectBrOp>(dst->front()))
2230 if (llvm::any_of(op.getDestOperands(), [&](
Value operand) {
2231 auto arg = dyn_cast<BlockArgument>(operand);
2232 return arg && arg.getOwner() == dst;
2238 rewriter.eraseOp(op);
2239 rewriter.mergeBlocks(dst, src, operands);
2243mlir::SuccessorOperands cir::BrOp::getSuccessorOperands(
unsigned index) {
2244 assert(index == 0 &&
"invalid successor index");
2245 return mlir::SuccessorOperands(getDestOperandsMutable());
2256mlir::SuccessorOperands
2257cir::IndirectBrOp::getSuccessorOperands(
unsigned index) {
2258 assert(index < getNumSuccessors() &&
"invalid successor index");
2259 return mlir::SuccessorOperands(getSuccOperandsMutable()[index]);
2263 OpAsmParser &parser, Type &flagType,
2264 SmallVectorImpl<Block *> &succOperandBlocks,
2267 if (failed(parser.parseCommaSeparatedList(
2268 OpAsmParser::Delimiter::Square,
2270 Block *destination = nullptr;
2271 SmallVector<OpAsmParser::UnresolvedOperand> operands;
2272 SmallVector<Type> operandTypes;
2274 if (parser.parseSuccessor(destination).failed())
2277 if (succeeded(parser.parseOptionalLParen())) {
2278 if (failed(parser.parseOperandList(
2279 operands, OpAsmParser::Delimiter::None)) ||
2280 failed(parser.parseColonTypeList(operandTypes)) ||
2281 failed(parser.parseRParen()))
2284 succOperandBlocks.push_back(destination);
2285 succOperands.emplace_back(operands);
2286 succOperandsTypes.emplace_back(operandTypes);
2289 "successor blocks")))
2295 Type flagType, SuccessorRange succs,
2296 OperandRangeRange succOperands,
2297 const TypeRangeRange &succOperandsTypes) {
2300 llvm::zip(succs, succOperands),
2303 p.printSuccessorAndUseList(std::get<0>(i), std::get<1>(i));
2306 if (!succOperands.empty())
2315mlir::SuccessorOperands cir::BrCondOp::getSuccessorOperands(
unsigned index) {
2316 assert(index < getNumSuccessors() &&
"invalid successor index");
2317 return SuccessorOperands(index == 0 ? getDestOperandsTrueMutable()
2318 : getDestOperandsFalseMutable());
2322 if (IntegerAttr condAttr = dyn_cast_if_present<IntegerAttr>(operands.front()))
2323 return condAttr.getValue().isOne() ? getDestTrue() : getDestFalse();
2331void cir::CaseOp::build(OpBuilder &builder, OperationState &result,
2332 ArrayAttr value, CaseOpKind
kind,
2333 OpBuilder::InsertPoint &insertPoint) {
2334 OpBuilder::InsertionGuard guardSwitch(builder);
2335 result.addAttribute(
"value", value);
2336 result.getOrAddProperties<Properties>().
kind =
2337 cir::CaseOpKindAttr::get(builder.getContext(),
kind);
2338 Region *caseRegion = result.addRegion();
2339 builder.createBlock(caseRegion);
2341 insertPoint = builder.saveInsertionPoint();
2348void cir::SwitchOp::build(OpBuilder &builder, OperationState &result,
2350 assert(switchBuilder &&
"the builder callback for regions must be present");
2351 OpBuilder::InsertionGuard guardSwitch(builder);
2352 Region *switchRegion = result.addRegion();
2353 builder.createBlock(switchRegion);
2354 result.addOperands({cond});
2355 switchBuilder(builder, result.location, result);
2359 walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
2361 if (isa<cir::SwitchOp>(op) && op != *
this)
2362 return WalkResult::skip();
2364 if (
auto caseOp = dyn_cast<cir::CaseOp>(op))
2365 cases.push_back(caseOp);
2367 return WalkResult::advance();
2372 collectCases(cases);
2374 if (getBody().empty())
2377 if (!isa<YieldOp>(getBody().front().back()))
2380 if (!llvm::all_of(getBody().front(),
2381 [](Operation &op) {
return isa<CaseOp, YieldOp>(op); }))
2384 return llvm::all_of(cases, [
this](CaseOp op) {
2385 return op->getParentOfType<SwitchOp>() == *
this;
2393void cir::SwitchFlatOp::build(OpBuilder &builder, OperationState &result,
2394 Value value, Block *defaultDestination,
2395 ValueRange defaultOperands,
2397 BlockRange caseDestinations,
2400 std::vector<mlir::Attribute> caseValuesAttrs;
2401 for (
const APInt &val : caseValues)
2402 caseValuesAttrs.push_back(cir::IntAttr::get(value.getType(), val));
2403 mlir::ArrayAttr attrs = ArrayAttr::get(builder.getContext(), caseValuesAttrs);
2405 build(builder, result, value, defaultOperands, caseOperands, attrs,
2406 defaultDestination, caseDestinations);
2409SuccessorOperands cir::SwitchFlatOp::getSuccessorOperands(
unsigned index) {
2410 assert(index < getNumSuccessors() &&
"invalid successor index");
2412 return SuccessorOperands(getDefaultOperandsMutable());
2413 return SuccessorOperands(getCaseOperandsMutable()[index - 1]);
2418 auto cond = dyn_cast_if_present<cir::IntAttr>(operands.front());
2421 for (
auto [value, dest] : llvm::zip(getCaseValues(), getCaseDestinations())) {
2422 const APInt &caseValue = cast<cir::IntAttr>(value).getValue();
2423 if (caseValue == cond.getValue())
2426 return getDefaultDestination();
2432 OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues,
2433 SmallVectorImpl<Block *> &caseDestinations,
2437 if (failed(parser.parseLSquare()))
2439 if (succeeded(parser.parseOptionalRSquare()))
2443 auto parseCase = [&]() {
2445 if (failed(parser.parseInteger(value)))
2448 values.push_back(cir::IntAttr::get(flagType, value));
2453 if (parser.parseColon() || parser.parseSuccessor(destination))
2455 if (!parser.parseOptionalLParen()) {
2456 if (parser.parseOperandList(operands, OpAsmParser::Delimiter::None,
2458 parser.parseColonTypeList(operandTypes) || parser.parseRParen())
2461 caseDestinations.push_back(destination);
2462 caseOperands.emplace_back(operands);
2463 caseOperandTypes.emplace_back(operandTypes);
2466 if (failed(parser.parseCommaSeparatedList(parseCase)))
2469 caseValues = ArrayAttr::get(flagType.getContext(), values);
2471 return parser.parseRSquare();
2475 Type flagType, mlir::ArrayAttr caseValues,
2476 SuccessorRange caseDestinations,
2477 OperandRangeRange caseOperands,
2478 const TypeRangeRange &caseOperandTypes) {
2488 llvm::zip(caseValues, caseDestinations),
2491 mlir::Attribute a = std::get<0>(i);
2492 p << mlir::cast<cir::IntAttr>(a).getValue();
2494 p.printSuccessorAndUseList(std::get<1>(i), caseOperands[index++]);
2509 mlir::Attribute &valueAttr) {
2511 return parser.parseAttribute(valueAttr,
"value", attr);
2515 p.printAttribute(value);
2518mlir::LogicalResult cir::GlobalOp::verify() {
2521 if (mlir::isa<cir::FuncType>(getSymType()))
2522 return emitOpError(
"global type cannot be a function type");
2526 if (getInitialValue().has_value()) {
2534 if (!getCtorRegion().empty() && !getInitialValue().has_value())
2536 "cannot have a constructor region without an initial value");
2538 std::optional<DynamicInitInfoAttr>
info = getDynamicInitInfo();
2540 if ((getDynamicInitGuard().has_value()) && (!info ||
info->getLocal()) &&
2541 (!getCtorRegion().empty() || !getDtorRegion().empty()))
2543 "Cannot have a static-local global-op with a constructor or "
2544 "destructor, they require in-function initialization via LocalInitOp");
2550 if (getDynamicInitGuard().has_value() != getDynamicInitInfo().has_value())
2551 return emitOpError(
"'dynamic_init_guard' and 'dynamic_init_info' must be "
2552 "present together");
2561 if (getDynamicInitGuard().has_value() && !getTlsRefs()->getGuardName())
2562 return emitOpError(
"cannot have a dynamic-init guard combined with "
2563 "ordered tls references");
2565 return emitOpError(
"'tls_refs' only valid for tls");
2568 if (getAliasee().has_value()) {
2569 if (getInitialValue().has_value() || !getCtorRegion().empty() ||
2570 !getDtorRegion().empty())
2571 return emitOpError(
"global alias shall not have an initializer or "
2572 "constructor/destructor regions");
2581void cir::GlobalOp::build(
2582 OpBuilder &odsBuilder, OperationState &odsState, llvm::StringRef sym_name,
2583 mlir::Type sym_type,
bool isConstant,
2584 mlir::ptr::MemorySpaceAttrInterface addrSpace,
2585 cir::GlobalLinkageKind linkage,
2586 function_ref<
void(OpBuilder &, Location)> ctorBuilder,
2587 function_ref<
void(OpBuilder &, Location)> dtorBuilder) {
2588 odsState.addAttribute(getSymNameAttrName(odsState.name),
2589 odsBuilder.getStringAttr(sym_name));
2590 odsState.addAttribute(getSymTypeAttrName(odsState.name),
2591 mlir::TypeAttr::get(sym_type));
2592 auto &properties = odsState.getOrAddProperties<cir::GlobalOp::Properties>();
2593 properties.setConstant(isConstant);
2597 odsState.addAttribute(getAddrSpaceAttrName(odsState.name), addrSpace);
2599 cir::GlobalLinkageKindAttr linkageAttr =
2600 cir::GlobalLinkageKindAttr::get(odsBuilder.getContext(), linkage);
2601 odsState.addAttribute(getLinkageAttrName(odsState.name), linkageAttr);
2603 Region *ctorRegion = odsState.addRegion();
2605 odsBuilder.createBlock(ctorRegion);
2606 ctorBuilder(odsBuilder, odsState.location);
2609 Region *dtorRegion = odsState.addRegion();
2611 odsBuilder.createBlock(dtorRegion);
2612 dtorBuilder(odsBuilder, odsState.location);
2621void cir::GlobalOp::getSuccessorRegions(
2622 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
2624 if (!point.isParent()) {
2625 regions.emplace_back(getOperation());
2630 Region *ctorRegion = &this->getCtorRegion();
2631 if (ctorRegion->empty())
2632 ctorRegion =
nullptr;
2635 Region *dtorRegion = &this->getDtorRegion();
2636 if (dtorRegion->empty())
2637 dtorRegion =
nullptr;
2641 regions.push_back(RegionSuccessor(ctorRegion));
2643 regions.push_back(RegionSuccessor(dtorRegion));
2650 if (!comdat.getValue().empty())
2651 p <<
"(\"" << comdat.getValue() <<
"\")";
2655 StringAttr comdat) {
2660 if (parser.parseOptionalKeyword(
"comdat").failed())
2662 std::string comdatKey;
2663 if (succeeded(parser.parseOptionalLParen())) {
2664 if (parser.parseString(&comdatKey).failed() ||
2665 parser.parseRParen().failed())
2668 comdatAttr = parser.getBuilder().getStringAttr(comdatKey);
2673 TypeAttr type, Attribute initAttr,
2674 mlir::Region &ctorRegion,
2675 mlir::Region &dtorRegion) {
2676 auto printType = [&]() { p <<
": " << type; };
2679 if (op.isDeclaration() || op.getAliasee()) {
2688 if (!ctorRegion.empty()) {
2690 p.printRegion(ctorRegion,
2695 if (!dtorRegion.empty()) {
2697 p.printRegion(dtorRegion,
2705 Attribute &initialValueAttr,
2706 mlir::Region &ctorRegion,
2707 mlir::Region &dtorRegion) {
2709 if (parser.parseOptionalEqual().failed()) {
2712 if (parser.parseColonType(opTy))
2721 assert(mlir::isa<mlir::TypedAttr>(initialValueAttr) &&
2722 "Non-typed attrs shouldn't appear here.");
2723 opTy = mlir::cast<mlir::TypedAttr>(initialValueAttr).getType();
2727 if (!parser.parseOptionalKeyword(
"ctor")) {
2728 auto parseLoc = parser.getCurrentLocation();
2729 if (parser.parseRegion(ctorRegion, {}, {}))
2737 if (!parser.parseOptionalKeyword(
"dtor")) {
2738 auto parseLoc = parser.getCurrentLocation();
2739 if (parser.parseRegion(dtorRegion, {}, {}))
2746 typeAttr = TypeAttr::get(opTy);
2755cir::GetGlobalOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2758 mlir::Operation *op =
2759 symbolTable.lookupNearestSymbolFrom(*
this, getNameAttr());
2760 if (op ==
nullptr || !(isa<GlobalOp>(op) || isa<FuncOp>(op)))
2761 return emitOpError(
"'")
2763 <<
"' does not reference a valid cir.global or cir.func";
2766 mlir::ptr::MemorySpaceAttrInterface symAddrSpaceAttr{};
2767 if (
auto g = dyn_cast<GlobalOp>(op)) {
2768 symTy = g.getSymType();
2769 symAddrSpaceAttr = g.getAddrSpaceAttr();
2772 if (getTls() && !g.getTlsModel())
2773 return emitOpError(
"access to global not marked thread local");
2778 bool getGlobalIsStaticLocal = getStaticLocal();
2779 bool globalIsStaticLocal =
2780 g.getDynamicInitGuard().has_value() &&
2781 (!g.getDynamicInitInfo() || g.getDynamicInitInfo()->getLocal());
2783 if (getGlobalIsStaticLocal != globalIsStaticLocal &&
2784 !getOperation()->getParentOfType<cir::GlobalOp>())
2785 return emitOpError(
"static_local attribute mismatch");
2786 }
else if (
auto f = dyn_cast<FuncOp>(op)) {
2787 symTy = f.getFunctionType();
2789 llvm_unreachable(
"Unexpected operation for GetGlobalOp");
2792 auto resultType = dyn_cast<PointerType>(getAddr().
getType());
2793 if (!resultType || symTy != resultType.getPointee())
2794 return emitOpError(
"result type pointee type '")
2795 << resultType.getPointee() <<
"' does not match type " << symTy
2796 <<
" of the global @" <<
getName();
2800 dyn_cast_if_present<TargetAddressSpaceAttr>(resultType.getAddrSpace());
2802 isa<FuncOp>(op) && targetAS &&
2803 targetAS.getValue() ==
2806 if (!isProgramAS && symAddrSpaceAttr != resultType.getAddrSpace()) {
2807 return emitOpError()
2808 <<
"result type address space does not match the address "
2809 "space of the global @"
2821cir::VTableAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2827 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*
this, getNameAttr());
2829 return emitOpError(
"'")
2830 <<
name <<
"' does not reference a valid cir.global";
2831 std::optional<mlir::Attribute> init = op.getInitialValue();
2834 if (!isa<cir::VTableAttr>(*init))
2835 return emitOpError(
"Expected #cir.vtable in initializer for global '")
2845cir::VTTAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2854 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*
this, getNameAttr());
2856 return emitOpError(
"'")
2857 <<
name <<
"' does not reference a valid cir.global";
2858 std::optional<mlir::Attribute> init = op.getInitialValue();
2861 if (!isa<cir::ConstArrayAttr>(*init))
2863 "Expected constant array in initializer for global VTT '")
2868LogicalResult cir::VTTAddrPointOp::verify() {
2870 if (
getName() && getSymAddr())
2871 return emitOpError(
"should use either a symbol or value, but not both");
2877 mlir::Type resultType = getAddr().getType();
2878 mlir::Type resTy = cir::PointerType::get(
2879 cir::PointerType::get(cir::VoidType::get(getContext())));
2881 if (resultType != resTy)
2882 return emitOpError(
"result type must be ")
2883 << resTy <<
", but provided result type is " << resultType;
2898 return name == CIRDialect::getMemoryEffectsAttrName() ||
2899 name == CIRDialect::getUwtableAttrName() ||
2900 name == CIRDialect::getFramePointerAttrName();
2903void cir::FuncOp::build(OpBuilder &builder, OperationState &result,
2904 StringRef name, FuncType type,
2905 GlobalLinkageKind linkage, CallingConv callingConv) {
2907 result.addAttribute(getSymNameAttrName(result.name),
2908 builder.getStringAttr(name));
2909 result.addAttribute(getFunctionTypeAttrName(result.name),
2910 TypeAttr::get(type));
2911 result.addAttribute(
2913 GlobalLinkageKindAttr::get(builder.getContext(), linkage));
2914 result.addAttribute(getCallingConvAttrName(result.name),
2915 CallingConvAttr::get(builder.getContext(), callingConv));
2918 result.addAttribute(getRequiresCallConvLoweringAttrName(result.name),
2919 builder.getUnitAttr());
2927cir::AnnotationAttr::verify(function_ref<InFlightDiagnostic()> emitError,
2928 mlir::StringAttr name, mlir::ArrayAttr args) {
2931 for (mlir::Attribute arg : args) {
2932 if (!isa<mlir::StringAttr, mlir::IntegerAttr>(arg))
2933 return emitError() <<
"annotation args must be StringAttr or IntegerAttr,"
2939ParseResult cir::FuncOp::parse(OpAsmParser &parser, OperationState &state) {
2940 llvm::SMLoc loc = parser.getCurrentLocation();
2941 mlir::Builder &builder = parser.getBuilder();
2943 mlir::StringAttr builtinNameAttr = getBuiltinAttrName(state.name);
2944 mlir::StringAttr coroutineKindNameAttr = getCoroutineKindAttrName(state.name);
2945 mlir::StringAttr inlineKindNameAttr = getInlineKindAttrName(state.name);
2946 mlir::StringAttr lambdaNameAttr = getLambdaAttrName(state.name);
2947 mlir::StringAttr noProtoNameAttr = getNoProtoAttrName(state.name);
2948 mlir::StringAttr requiresCallConvLoweringNameAttr =
2949 getRequiresCallConvLoweringAttrName(state.name);
2950 mlir::StringAttr comdatNameAttr = getComdatAttrName(state.name);
2951 mlir::StringAttr alignmentNameAttr = getAlignmentAttrName(state.name);
2952 mlir::StringAttr preferredAlignmentNameAttr =
2953 getPreferredAlignmentAttrName(state.name);
2954 mlir::StringAttr visNameAttr = getSymVisibilityAttrName(state.name);
2955 mlir::StringAttr dsoLocalNameAttr = getDsoLocalAttrName(state.name);
2956 mlir::StringAttr unnamedAddrNameAttr = getUnnamedAddrAttrName(state.name);
2957 mlir::StringAttr funcInfoNameAttr = getFuncInfoAttrName(state.name);
2959 if (::mlir::succeeded(parser.parseOptionalKeyword(builtinNameAttr.strref())))
2960 state.addAttribute(builtinNameAttr, parser.getBuilder().getUnitAttr());
2964 static constexpr llvm::StringRef keywords[] = {
"coroutine",
2965 "flattened_coroutine"};
2966 llvm::StringRef keyword;
2967 if (parser.parseOptionalKeyword(&keyword, keywords).succeeded())
2969 coroutineKindNameAttr,
2970 cir::CoroutineKindAttr::get(builder.getContext(),
2971 *cir::symbolizeCoroutineKind(keyword)));
2975 cir::InlineKindAttr inlineKindAttr;
2979 state.addAttribute(inlineKindNameAttr, inlineKindAttr);
2981 if (::mlir::succeeded(parser.parseOptionalKeyword(lambdaNameAttr.strref())))
2982 state.addAttribute(lambdaNameAttr, parser.getBuilder().getUnitAttr());
2983 if (parser.parseOptionalKeyword(noProtoNameAttr).succeeded())
2984 state.addAttribute(noProtoNameAttr, parser.getBuilder().getUnitAttr());
2987 StringAttr comdatAttr;
2991 state.addAttribute(comdatNameAttr, comdatAttr);
2994 auto parseAlignmentBody = [&](
int64_t &value) {
2995 if (parser.parseLParen().failed() || parser.parseInteger(value).failed() ||
2996 parser.parseRParen().failed())
3000 return static_cast<LogicalResult
>(parser.emitError(
3001 loc,
"function alignment must be a positive integer"));
3006 if (parser.parseOptionalKeyword(alignmentNameAttr).succeeded()) {
3008 if (parseAlignmentBody(value).failed())
3010 state.addAttribute(alignmentNameAttr, builder.getI64IntegerAttr(value));
3013 if (parser.parseOptionalKeyword(preferredAlignmentNameAttr).succeeded()) {
3015 if (parseAlignmentBody(value).failed())
3017 state.addAttribute(preferredAlignmentNameAttr,
3018 builder.getI64IntegerAttr(value));
3023 GlobalLinkageKindAttr::get(
3024 parser.getContext(),
3026 parser, GlobalLinkageKind::ExternalLinkage)));
3028 ::llvm::StringRef visAttrStr;
3029 if (parser.parseOptionalKeyword(&visAttrStr, {
"private",
"public",
"nested"})
3031 state.addAttribute(visNameAttr,
3032 parser.getBuilder().getStringAttr(visAttrStr));
3035 state.getOrAddProperties<cir::FuncOp::Properties>().global_visibility =
3038 if (parser.parseOptionalKeyword(dsoLocalNameAttr).succeeded())
3039 state.addAttribute(dsoLocalNameAttr, parser.getBuilder().getUnitAttr());
3041 if (parser.parseOptionalKeyword(unnamedAddrNameAttr).succeeded())
3042 state.addAttribute(unnamedAddrNameAttr, parser.getBuilder().getUnitAttr());
3044 StringAttr nameAttr;
3045 if (parser.parseSymbolName(nameAttr, getSymNameAttrName(state.name),
3051 bool isVariadic =
false;
3052 if (function_interface_impl::parseFunctionSignatureWithArguments(
3053 parser,
true, arguments, isVariadic, resultTypes,
3058 bool argAttrsEmpty =
true;
3059 for (OpAsmParser::Argument &arg : arguments) {
3060 argTypes.push_back(
arg.type);
3064 argAttrs.push_back(
arg.attrs);
3066 argAttrsEmpty =
false;
3070 if (resultTypes.size() > 1 || resultAttrs.size() > 1)
3071 return parser.emitError(
3072 loc,
"functions with multiple return types are not supported");
3074 mlir::Type returnType =
3075 (resultTypes.empty() ? cir::VoidType::get(builder.getContext())
3076 : resultTypes.front());
3078 cir::FuncType fnType =
3079 cir::FuncType::getChecked([&]() {
return parser.emitError(loc); },
3080 argTypes, returnType, isVariadic);
3084 state.addAttribute(getFunctionTypeAttrName(state.name),
3085 TypeAttr::get(fnType));
3087 if (!resultAttrs.empty() && resultAttrs[0])
3089 getResAttrsAttrName(state.name),
3090 mlir::ArrayAttr::get(parser.getContext(), {resultAttrs[0]}));
3093 state.addAttribute(getArgAttrsAttrName(state.name),
3094 mlir::ArrayAttr::get(parser.getContext(), argAttrs));
3096 bool hasAlias =
false;
3097 mlir::StringAttr aliaseeNameAttr = getAliaseeAttrName(state.name);
3098 if (parser.parseOptionalKeyword(
"alias").succeeded()) {
3099 if (parser.parseLParen().failed())
3101 mlir::StringAttr aliaseeAttr;
3102 if (parser.parseOptionalSymbolName(aliaseeAttr).failed())
3104 state.addAttribute(aliaseeNameAttr, FlatSymbolRefAttr::get(aliaseeAttr));
3105 if (parser.parseRParen().failed())
3110 mlir::StringAttr personalityNameAttr = getPersonalityAttrName(state.name);
3111 if (parser.parseOptionalKeyword(
"personality").succeeded()) {
3112 if (parser.parseLParen().failed())
3114 mlir::StringAttr personalityAttr;
3115 if (parser.parseOptionalSymbolName(personalityAttr).failed())
3117 state.addAttribute(personalityNameAttr,
3118 FlatSymbolRefAttr::get(personalityAttr));
3119 if (parser.parseRParen().failed())
3124 mlir::StringAttr callConvNameAttr = getCallingConvAttrName(state.name);
3125 cir::CallingConv callConv = cir::CallingConv::C;
3126 if (parser.parseOptionalKeyword(
"cc").succeeded()) {
3127 if (parser.parseLParen().failed())
3130 return parser.emitError(loc) <<
"unknown calling convention";
3131 if (parser.parseRParen().failed())
3134 state.addAttribute(callConvNameAttr,
3135 cir::CallingConvAttr::get(parser.getContext(), callConv));
3137 auto parseGlobalDtorCtor =
3138 [&](StringRef keyword,
3139 llvm::function_ref<void(std::optional<int> prio)> createAttr)
3140 -> mlir::LogicalResult {
3141 if (mlir::succeeded(parser.parseOptionalKeyword(keyword))) {
3142 std::optional<int> priority;
3143 if (mlir::succeeded(parser.parseOptionalLParen())) {
3144 auto parsedPriority = mlir::FieldParser<int>::parse(parser);
3145 if (mlir::failed(parsedPriority))
3146 return parser.emitError(parser.getCurrentLocation(),
3147 "failed to parse 'priority', of type 'int'");
3148 priority = parsedPriority.value_or(
int());
3150 if (parser.parseRParen())
3153 createAttr(priority);
3159 if (parser.parseOptionalKeyword(
"func_info").succeeded()) {
3160 if (parser.parseLess().failed())
3163 llvm::SMLoc attrLoc = parser.getCurrentLocation();
3164 mlir::Attribute
attr;
3165 if (parser.parseAttribute(attr).failed())
3167 if (!mlir::isa<cir::CXXCtorAttr, cir::CXXDtorAttr, cir::CXXAssignAttr,
3168 cir::FuncIdentityAttr>(attr))
3169 return parser.emitError(attrLoc,
3170 "expected a function info attribute, got ")
3172 state.addAttribute(funcInfoNameAttr, attr);
3174 if (parser.parseGreater().failed())
3178 if (parseGlobalDtorCtor(
"global_ctor", [&](std::optional<int> priority) {
3179 mlir::IntegerAttr globalCtorPriorityAttr =
3180 builder.getI32IntegerAttr(priority.value_or(65535));
3181 state.addAttribute(getGlobalCtorPriorityAttrName(state.name),
3182 globalCtorPriorityAttr);
3186 if (parseGlobalDtorCtor(
"global_dtor", [&](std::optional<int> priority) {
3187 mlir::IntegerAttr globalDtorPriorityAttr =
3188 builder.getI32IntegerAttr(priority.value_or(65535));
3189 state.addAttribute(getGlobalDtorPriorityAttrName(state.name),
3190 globalDtorPriorityAttr);
3195 mlir::StringAttr annotationsNameAttr = getAnnotationsAttrName(state.name);
3196 mlir::ArrayAttr annotationsAttr;
3197 if (parser.parseOptionalAttribute(annotationsAttr).has_value() &&
3199 state.addAttribute(annotationsNameAttr, annotationsAttr);
3201 if (parser.parseOptionalKeyword(requiresCallConvLoweringNameAttr).succeeded())
3202 state.addAttribute(requiresCallConvLoweringNameAttr,
3203 parser.getBuilder().getUnitAttr());
3206 NamedAttrList parsedAttrs;
3207 llvm::SMLoc attrsLoc = parser.getCurrentLocation();
3208 if (parser.parseOptionalAttrDictWithKeyword(parsedAttrs))
3212 for (StringRef disallowed : cir::FuncOp::getAttributeNames()) {
3215 if (parsedAttrs.get(disallowed))
3216 return parser.emitError(loc,
"attribute '")
3218 <<
"' should not be specified in the explicit attribute list";
3224 state.attributes.append(parsedAttrs);
3227 auto *body = state.addRegion();
3228 OptionalParseResult parseResult = parser.parseOptionalRegion(
3229 *body, arguments,
false);
3230 if (parseResult.has_value()) {
3232 return parser.emitError(loc,
"function alias shall not have a body");
3233 if (failed(*parseResult))
3237 return parser.emitError(loc,
"expected non-empty function body");
3246bool cir::FuncOp::isDeclaration() {
3249 std::optional<StringRef> aliasee = getAliasee();
3251 return getFunctionBody().empty();
3257bool cir::FuncOp::isCXXSpecialMemberFunction() {
3260 mlir::Attribute
attr = getFuncInfoAttr();
3261 return attr && mlir::isa<CXXCtorAttr, CXXDtorAttr, CXXAssignAttr>(attr);
3264bool cir::FuncOp::isCxxConstructor() {
3265 auto attr = getFuncInfoAttr();
3266 return attr && dyn_cast<CXXCtorAttr>(attr);
3269bool cir::FuncOp::isCxxDestructor() {
3270 auto attr = getFuncInfoAttr();
3271 return attr && dyn_cast<CXXDtorAttr>(attr);
3274bool cir::FuncOp::isCxxSpecialAssignment() {
3275 auto attr = getFuncInfoAttr();
3276 return attr && dyn_cast<CXXAssignAttr>(attr);
3279std::optional<CtorKind> cir::FuncOp::getCxxConstructorKind() {
3280 mlir::Attribute
attr = getFuncInfoAttr();
3282 if (
auto ctor = dyn_cast<CXXCtorAttr>(attr))
3283 return ctor.getCtorKind();
3285 return std::nullopt;
3288std::optional<AssignKind> cir::FuncOp::getCxxSpecialAssignKind() {
3289 mlir::Attribute
attr = getFuncInfoAttr();
3291 if (
auto assign = dyn_cast<CXXAssignAttr>(attr))
3292 return assign.getAssignKind();
3294 return std::nullopt;
3297bool cir::FuncOp::isCxxTrivialMemberFunction() {
3298 mlir::Attribute
attr = getFuncInfoAttr();
3300 if (
auto ctor = dyn_cast<CXXCtorAttr>(attr))
3301 return ctor.getIsTrivial();
3302 if (
auto dtor = dyn_cast<CXXDtorAttr>(attr))
3303 return dtor.getIsTrivial();
3304 if (
auto assign = dyn_cast<CXXAssignAttr>(attr))
3305 return assign.getIsTrivial();
3310mlir::Region *cir::FuncOp::getCallableRegion() {
3314 if (getBody().empty())
3319void cir::FuncOp::print(OpAsmPrinter &p) {
3323 if (std::optional<cir::CoroutineKind> coroKind = getCoroutineKind())
3324 p <<
' ' << cir::stringifyCoroutineKind(*coroKind);
3334 if (getComdatAttr()) {
3340 p <<
" alignment(" << *getAlignment() <<
')';
3342 if (getPreferredAlignment())
3343 p <<
" preferred_alignment(" << *getPreferredAlignment() <<
')';
3345 if (getLinkage() != GlobalLinkageKind::ExternalLinkage)
3346 p <<
' ' << stringifyGlobalLinkageKind(getLinkage());
3348 mlir::SymbolTable::Visibility vis = getVisibility();
3349 if (vis != mlir::SymbolTable::Visibility::Public)
3352 if (getGlobalVisibility() != cir::VisibilityKind::Default)
3353 p <<
' ' << stringifyVisibilityKind(getGlobalVisibility());
3358 if (getUnnamedAddr())
3359 p <<
" unnamed_addr";
3362 p.printSymbolName(getSymName());
3363 cir::FuncType fnType = getFunctionType();
3364 function_interface_impl::printFunctionSignature(
3365 p, *
this, fnType.getInputs(), fnType.isVarArg(), fnType.getReturnTypes());
3367 if (std::optional<StringRef> aliaseeName = getAliasee()) {
3369 p.printSymbolName(*aliaseeName);
3373 if (getCallingConv() != cir::CallingConv::C) {
3375 p << stringifyCallingConv(getCallingConv());
3379 if (std::optional<StringRef> personalityName = getPersonality()) {
3380 p <<
" personality(";
3381 p.printSymbolName(*personalityName);
3385 if (mlir::Attribute funcInfo = getFuncInfoAttr()) {
3387 p.printAttribute(funcInfo);
3391 if (
auto globalCtorPriority = getGlobalCtorPriority()) {
3392 p <<
" global_ctor";
3393 if (globalCtorPriority.value() != 65535)
3394 p <<
"(" << globalCtorPriority.value() <<
")";
3397 if (
auto globalDtorPriority = getGlobalDtorPriority()) {
3398 p <<
" global_dtor";
3399 if (globalDtorPriority.value() != 65535)
3400 p <<
"(" << globalDtorPriority.value() <<
")";
3403 if (mlir::ArrayAttr annotations = getAnnotationsAttr()) {
3405 p.printAttribute(annotations);
3408 if (getRequiresCallConvLowering())
3409 p <<
' ' << getRequiresCallConvLoweringAttrName().getValue();
3413 for (llvm::StringRef name : cir::FuncOp::getAttributeNames())
3415 elidedAttrs.push_back(name);
3416 function_interface_impl::printFunctionAttributes(p, *
this, elidedAttrs);
3419 Region &body = getOperation()->getRegion(0);
3420 if (!body.empty()) {
3422 p.printRegion(body,
false,
3427mlir::LogicalResult cir::FuncOp::verify() {
3429 if (!isDeclaration() && getCoroutineKind() == cir::CoroutineKind::Coroutine) {
3430 int coroutineOpCount = 0;
3431 this->walk([&](Operation *op) {
3432 if (isa<CoroutineOp>(op)) {
3434 if (coroutineOpCount > 1) {
3435 return mlir::WalkResult::interrupt();
3438 return mlir::WalkResult::advance();
3440 if (coroutineOpCount != 1)
3441 return emitOpError()
3442 <<
"coroutine function must have exactly one cir.coroutine op";
3445 llvm::SmallSet<llvm::StringRef, 16> labels;
3446 llvm::SmallSet<llvm::StringRef, 16> gotos;
3447 llvm::SmallSet<llvm::StringRef, 16> blockAddresses;
3448 bool invalidBlockAddress =
false;
3449 getOperation()->walk([&](mlir::Operation *op) {
3450 if (
auto lab = dyn_cast<cir::LabelOp>(op)) {
3451 labels.insert(lab.getLabel());
3452 }
else if (
auto goTo = dyn_cast<cir::GotoOp>(op)) {
3453 gotos.insert(goTo.getLabel());
3454 }
else if (
auto blkAdd = dyn_cast<cir::BlockAddressOp>(op)) {
3455 if (blkAdd.getBlockAddrInfoAttr().getFunc().getAttr() != getSymName()) {
3457 invalidBlockAddress =
true;
3458 return mlir::WalkResult::interrupt();
3460 blockAddresses.insert(blkAdd.getBlockAddrInfoAttr().getLabel());
3462 return mlir::WalkResult::advance();
3465 if (invalidBlockAddress)
3466 return emitOpError() <<
"blockaddress references a different function";
3468 llvm::SmallSet<llvm::StringRef, 16> mismatched;
3469 if (!labels.empty() || !gotos.empty()) {
3470 mismatched = llvm::set_difference(gotos, labels);
3472 if (!mismatched.empty())
3473 return emitOpError() <<
"goto/label mismatch";
3478 if (!labels.empty() || !blockAddresses.empty()) {
3479 mismatched = llvm::set_difference(blockAddresses, labels);
3481 if (!mismatched.empty())
3482 return emitOpError()
3483 <<
"expects an existing label target in the referenced function";
3493void cir::TernaryOp::build(
3494 OpBuilder &builder, OperationState &result,
Value cond,
3495 function_ref<
void(OpBuilder &, Location)> trueBuilder,
3496 function_ref<
void(OpBuilder &, Location)> falseBuilder) {
3497 result.addOperands(cond);
3498 OpBuilder::InsertionGuard guard(builder);
3499 Region *trueRegion = result.addRegion();
3500 builder.createBlock(trueRegion);
3501 trueBuilder(builder, result.location);
3502 Region *falseRegion = result.addRegion();
3503 builder.createBlock(falseRegion);
3504 falseBuilder(builder, result.location);
3509 if (trueRegion->back().mightHaveTerminator())
3510 yield = dyn_cast_or_null<cir::YieldOp>(trueRegion->back().getTerminator());
3511 if (!yield && falseRegion->back().mightHaveTerminator())
3512 yield = dyn_cast_or_null<cir::YieldOp>(falseRegion->back().getTerminator());
3514 assert((!yield || yield.getNumOperands() <= 1) &&
3515 "expected zero or one result type");
3516 if (yield && yield.getNumOperands() == 1)
3517 result.addTypes(TypeRange{yield.getOperandTypes().front()});
3524OpFoldResult cir::SelectOp::fold(FoldAdaptor adaptor) {
3526 mlir::dyn_cast_if_present<cir::BoolAttr>(adaptor.getCondition()))
3527 return condition.getValue() ? getTrueValue() : getFalseValue();
3530 mlir::Attribute trueValue = adaptor.getTrueValue();
3531 mlir::Attribute falseValue = adaptor.getFalseValue();
3532 if (trueValue == falseValue)
3534 if (getTrueValue() == getFalseValue())
3535 return getTrueValue();
3540LogicalResult cir::SelectOp::verify() {
3542 auto condTy = dyn_cast<cir::VectorType>(getCondition().
getType());
3549 if (!isa<cir::VectorType>(getTrueValue().
getType()) ||
3550 !isa<cir::VectorType>(getFalseValue().
getType())) {
3551 return emitOpError()
3552 <<
"expected both true and false operands to be vector types "
3553 "when the condition is a vector boolean type";
3562LogicalResult cir::ShiftOp::verify() {
3563 mlir::Operation *op = getOperation();
3564 auto op0VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(0).getType());
3565 auto op1VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(1).getType());
3566 if (!op0VecTy ^ !op1VecTy)
3567 return emitOpError() <<
"input types cannot be one vector and one scalar";
3570 if (op0VecTy.getSize() != op1VecTy.getSize())
3571 return emitOpError() <<
"input vector types must have the same size";
3573 auto opResultTy = mlir::dyn_cast<cir::VectorType>(
getType());
3575 return emitOpError() <<
"the type of the result must be a vector "
3576 <<
"if it is vector shift";
3578 auto op0VecEleTy = mlir::cast<cir::IntType>(op0VecTy.getElementType());
3579 auto op1VecEleTy = mlir::cast<cir::IntType>(op1VecTy.getElementType());
3580 if (op0VecEleTy.getWidth() != op1VecEleTy.getWidth())
3581 return emitOpError()
3582 <<
"vector operands do not have the same elements sizes";
3584 auto resVecEleTy = mlir::cast<cir::IntType>(opResultTy.getElementType());
3585 if (op0VecEleTy.getWidth() != resVecEleTy.getWidth())
3586 return emitOpError() <<
"vector operands and result type do not have the "
3587 "same elements sizes";
3590 return mlir::success();
3597LogicalResult cir::LabelOp::verify() {
3598 mlir::Operation *op = getOperation();
3599 mlir::Block *blk = op->getBlock();
3600 if (&blk->front() != op)
3601 return emitError() <<
"must be the first operation in a block";
3603 return mlir::success();
3610OpFoldResult cir::IncOp::fold(FoldAdaptor adaptor) {
3611 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3612 return adaptor.getInput();
3620OpFoldResult cir::DecOp::fold(FoldAdaptor adaptor) {
3621 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3622 return adaptor.getInput();
3630OpFoldResult cir::MinusOp::fold(FoldAdaptor adaptor) {
3631 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3632 return adaptor.getInput();
3637 mlir::dyn_cast_if_present<cir::IntAttr>(adaptor.getInput())) {
3638 APInt val = intAttr.getValue();
3640 return cir::IntAttr::get(
getType(), val);
3650OpFoldResult cir::FNegOp::fold(FoldAdaptor adaptor) {
3651 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3652 return adaptor.getInput();
3656 mlir::dyn_cast_if_present<cir::FPAttr>(adaptor.getInput())) {
3657 APFloat val = fpAttr.getValue();
3659 return cir::FPAttr::get(
getType(), val);
3669OpFoldResult cir::NotOp::fold(FoldAdaptor adaptor) {
3670 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3671 return adaptor.getInput();
3676 if (mlir::Attribute attr = adaptor.getInput()) {
3677 if (
auto intAttr = mlir::dyn_cast<cir::IntAttr>(attr)) {
3678 APInt val = intAttr.getValue();
3680 return cir::IntAttr::get(
getType(), val);
3682 if (
auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr))
3683 return cir::BoolAttr::get(getContext(), !boolAttr.getValue());
3693LogicalResult cir::BaseClassAddrOp::verify() {
3694 if (getSrcAddr().
getType().getAddrSpace() !=
getType().getAddrSpace())
3695 return emitOpError() <<
"address space mismatch";
3696 return mlir::success();
3699LogicalResult cir::DerivedClassAddrOp::verify() {
3700 if (getSrcAddr().
getType().getAddrSpace() !=
getType().getAddrSpace())
3701 return emitOpError() <<
"address space mismatch";
3702 return mlir::success();
3710 mlir::Type resultTy) {
3713 mlir::Type inputMemberTy;
3714 mlir::Type resultMemberTy;
3715 if (mlir::isa<cir::DataMemberType>(src.getType())) {
3717 mlir::cast<cir::DataMemberType>(src.getType()).getMemberTy();
3718 resultMemberTy = mlir::cast<cir::DataMemberType>(resultTy).getMemberTy();
3721 if (inputMemberTy != resultMemberTy)
3722 return op->emitOpError()
3723 <<
"member types of the operand and the result do not match";
3725 return mlir::success();
3728LogicalResult cir::BaseDataMemberOp::verify() {
3732LogicalResult cir::DerivedDataMemberOp::verify() {
3740LogicalResult cir::BaseMethodOp::verify() {
3744LogicalResult cir::DerivedMethodOp::verify() {
3752void cir::AwaitOp::build(OpBuilder &builder, OperationState &result,
3756 result.addAttribute(getKindAttrName(result.name),
3757 cir::AwaitKindAttr::get(builder.getContext(),
kind));
3759 OpBuilder::InsertionGuard guard(builder);
3760 Region *readyRegion = result.addRegion();
3761 builder.createBlock(readyRegion);
3762 readyBuilder(builder, result.location);
3766 OpBuilder::InsertionGuard guard(builder);
3767 Region *suspendRegion = result.addRegion();
3768 builder.createBlock(suspendRegion);
3769 suspendBuilder(builder, result.location);
3773 OpBuilder::InsertionGuard guard(builder);
3774 Region *resumeRegion = result.addRegion();
3775 builder.createBlock(resumeRegion);
3776 resumeBuilder(builder, result.location);
3780void cir::AwaitOp::getSuccessorRegions(
3781 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
3782 assert(point.isParent() || point.getTerminatorPredecessorOrNull());
3785 if (point.isParent()) {
3786 regions.emplace_back(&getReady());
3790 mlir::Region *parentRegion =
3791 point.getTerminatorPredecessorOrNull()->getParentRegion();
3800 if (&getReady() == parentRegion) {
3801 regions.emplace_back(&getResume());
3802 regions.emplace_back(&getSuspend());
3809 if (&getSuspend() == parentRegion) {
3810 regions.emplace_back(&getResume());
3811 regions.emplace_back(getOperation());
3816 regions.emplace_back(getOperation());
3819LogicalResult cir::AwaitOp::verify() {
3820 if (!isa<ConditionOp>(this->getReady().back().getTerminator()))
3821 return emitOpError(
"ready region must end with cir.condition");
3822 if (this->getSuspend().empty())
3823 return emitOpError(
"suspend region must not be empty");
3824 if (!isa<CoroSuspendPoint>(this->getSuspend().back().getTerminator()))
3825 return emitOpError(
"suspend region must end with cir.coro.suspend_point");
3833LogicalResult cir::CoReturnOp::verify() {
3834 mlir::Operation *coRet = getOperation();
3835 auto coroutine = coRet->getParentOfType<CoroutineOp>();
3836 if (!coroutine.getBody().isAncestor(getOperation()->getParentRegion()))
3837 return emitOpError(
"must be inside the cir.coroutine body region");
3845void cir::CoroutineOp::build(OpBuilder &builder, OperationState &result,
3852 OpBuilder::InsertionGuard guard(builder);
3853 Region *initialRegion = result.addRegion();
3854 builder.createBlock(initialRegion);
3855 initialSuspendBuilder(builder, result.location);
3859 OpBuilder::InsertionGuard guard(builder);
3860 Region *bodyRegion = result.addRegion();
3861 builder.createBlock(bodyRegion);
3862 bodyBuilder(builder, result.location);
3866 OpBuilder::InsertionGuard guard(builder);
3867 Region *finalRegion = result.addRegion();
3868 builder.createBlock(finalRegion);
3869 finalSuspendBuilder(builder, result.location);
3873 OpBuilder::InsertionGuard guard(builder);
3874 Region *destroyRegion = result.addRegion();
3875 builder.createBlock(destroyRegion);
3876 destroyBuilder(builder, result.location);
3880 OpBuilder::InsertionGuard guard(builder);
3881 Region *exitRegion = result.addRegion();
3882 builder.createBlock(exitRegion);
3883 exitBuilder(builder, result.location);
3887void cir::CoroutineOp::getSuccessorRegions(
3888 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
3891 if (point.isParent()) {
3892 regions.emplace_back(&getInitialSuspend());
3896 mlir::Region *parent =
3897 point.getTerminatorPredecessorOrNull()->getParentRegion();
3903 if (parent == &getInitialSuspend()) {
3904 regions.emplace_back(&getBody());
3905 regions.emplace_back(&getExit());
3906 regions.emplace_back(&getDestroy());
3914 if (parent == &getBody()) {
3915 regions.emplace_back(&getFinalSuspend());
3916 regions.emplace_back(&getExit());
3917 regions.emplace_back(&getDestroy());
3925 if (parent == &getFinalSuspend()) {
3926 regions.emplace_back(
3928 regions.emplace_back(&getExit());
3936 if (parent == &getDestroy()) {
3937 regions.emplace_back(&getExit());
3938 regions.push_back(RegionSuccessor(getOperation()));
3942 if (parent == &getExit()) {
3943 regions.emplace_back(getOperation());
3949cir::CoroutineOp::getSuccessorInputs(RegionSuccessor successor) {
3950 return ValueRange();
3953LogicalResult cir::CoroutineOp::verify() {
3954 mlir::Region &initialSuspend = getInitialSuspend();
3955 mlir::Region &body = getBody();
3956 mlir::Region &finalSuspend = getFinalSuspend();
3957 mlir::Region &destroy = getDestroy();
3958 mlir::Region &exit = getExit();
3963 int initAwaitCount = 0;
3964 bool hasInvalidAwait =
false;
3966 initialSuspend.walk([&](Operation *op) {
3967 auto awaitOp = mlir::dyn_cast<AwaitOp>(op);
3969 return mlir::WalkResult::advance();
3971 if (awaitOp.getKind() == cir::AwaitKind::Init)
3974 hasInvalidAwait =
true;
3976 if (initAwaitCount > 1 || hasInvalidAwait)
3977 return mlir::WalkResult::interrupt();
3979 return mlir::WalkResult::advance();
3982 if (hasInvalidAwait)
3983 return emitOpError(
"'initial_suspend' must not contain any cir.await other "
3984 "than the 'init' one");
3985 if (initAwaitCount != 1)
3987 "must have exactly one 'init' cir.await in 'initial_suspend'");
3990 int finalAwaitCount = 0;
3991 hasInvalidAwait =
false;
3993 finalSuspend.walk([&](Operation *op) {
3994 auto awaitOp = mlir::dyn_cast<AwaitOp>(op);
3996 return mlir::WalkResult::advance();
3998 if (awaitOp.getKind() == cir::AwaitKind::Final)
4001 hasInvalidAwait =
true;
4003 if (finalAwaitCount > 1 || hasInvalidAwait)
4004 return mlir::WalkResult::interrupt();
4006 return mlir::WalkResult::advance();
4009 if (hasInvalidAwait)
4010 return emitOpError(
"'final_suspend' must not contain any cir.await other "
4011 "than the 'final' one");
4012 if (finalAwaitCount > 1)
4014 "must have one or zero 'final' cir.await in 'final_suspend'");
4021 if (initialSuspend.empty() || initialSuspend.back().empty())
4022 return emitOpError(
"initial_suspend region must not be empty");
4023 if (!isa<YieldOp>(initialSuspend.back().back()))
4024 return emitOpError(
"'initial_suspend' must end with cir.yield");
4026 if (body.empty() || body.back().empty())
4027 return emitOpError(
"'body' region must not be empty");
4028 if (!isa<YieldOp, CoReturnOp>(body.back().back()))
4029 return emitOpError(
"'body' must end with cir.yield or cir.co_return");
4031 if (finalSuspend.empty() || finalSuspend.back().empty())
4032 return emitOpError(
"'final_suspend' region must not be empty");
4033 if (!isa<YieldOp>(finalSuspend.back().back()))
4034 return emitOpError(
"'final_suspend' must end with cir.yield");
4036 if (destroy.empty() || destroy.back().empty())
4037 return emitOpError(
"'destroy' region must not be empty");
4038 if (!isa<YieldOp>(destroy.back().back()))
4039 return emitOpError(
"'destroy' must end with cir.yield");
4041 if (exit.empty() || exit.back().empty())
4042 return emitOpError(
"'exit' region must not be empty");
4043 if (!isa<ReturnOp>(exit.back().back()))
4044 return emitOpError(
"'exit' must end with cir.return");
4046 return mlir::success();
4057 mlir::Type srcType, mlir::Type dstType) {
4058 printer.printType(srcType);
4059 if (srcType != dstType) {
4061 printer.printType(dstType);
4066 mlir::Type &srcType,
4067 mlir::Type &dstType) {
4068 if (parser.parseType(srcType))
4069 return mlir::failure();
4070 if (parser.parseOptionalComma().succeeded()) {
4071 if (parser.parseType(dstType))
4072 return mlir::failure();
4076 return mlir::success();
4079LogicalResult cir::CopyOp::verify() {
4084 if (!
getType().getPointee().hasTrait<DataLayoutTypeInterface::Trait>())
4085 return emitError() <<
"missing data layout for pointee type";
4087 if (getSkipTailPadding() &&
4088 !mlir::isa<cir::RecordType>(
getType().getPointee()))
4090 <<
"skip_tail_padding is only valid for record pointee types";
4092 return mlir::success();
4099LogicalResult cir::PtrMaskOp::verify() {
4100 mlir::DataLayout layout = mlir::DataLayout::closest(*
this);
4101 std::optional<uint64_t> indexWidth =
4102 layout.getTypeIndexBitwidth(getPtr().
getType());
4104 return emitOpError() <<
"pointer has no index width";
4106 uint64_t maskWidth = getMask().getType().getWidth();
4107 if (maskWidth != *indexWidth)
4108 return emitOpError() <<
"mask width " << maskWidth
4109 <<
" must equal the pointer index width "
4112 return mlir::success();
4119LogicalResult cir::GetRuntimeMemberOp::verify() {
4120 cir::DataMemberType memberPtrTy = getMember().getType();
4122 if (getAddr().
getType().getPointee() != memberPtrTy.getClassTy())
4123 return emitError() <<
"record type does not match the member pointer type";
4124 if (
getType().getPointee() != memberPtrTy.getMemberTy())
4125 return emitError() <<
"result type does not match the member pointer type";
4126 if (
getType().getAddrSpace() != getAddr().
getType().getAddrSpace())
4128 <<
"result address space does not match the object address space";
4129 return mlir::success();
4136LogicalResult cir::GetMethodOp::verify() {
4137 cir::MethodType methodTy = getMethod().getType();
4140 cir::PointerType objectPtrTy = getObject().getType();
4141 mlir::Type objectTy = objectPtrTy.getPointee();
4143 if (methodTy.getClassTy() != objectTy)
4144 return emitError() <<
"method class type and object type do not match";
4147 auto calleeTy = mlir::cast<cir::FuncType>(getCallee().
getType().getPointee());
4148 cir::FuncType methodFuncTy = methodTy.getMemberFuncTy();
4155 if (methodFuncTy.getReturnType() != calleeTy.getReturnType())
4157 <<
"method return type and callee return type do not match";
4162 if (calleeArgsTy.empty())
4163 return emitError() <<
"callee parameter list lacks receiver object ptr";
4165 auto calleeThisArgPtrTy = mlir::dyn_cast<cir::PointerType>(calleeArgsTy[0]);
4166 if (!calleeThisArgPtrTy ||
4167 !mlir::isa<cir::VoidType>(calleeThisArgPtrTy.getPointee())) {
4169 <<
"the first parameter of callee must be a void pointer";
4172 if (calleeArgsTy.size() != methodFuncArgsTy.size())
4173 return emitError() <<
"callee and method parameter counts do not match";
4175 if (calleeArgsTy.size() > 1 &&
4176 calleeArgsTy.slice(1) != methodFuncArgsTy.slice(1))
4178 <<
"callee parameters and method parameters do not match";
4180 return mlir::success();
4191LogicalResult cir::GetMemberOp::verify() {
4192 const auto recordTy = dyn_cast<RecordType>(getAddrTy().getPointee());
4194 return emitError() <<
"expected pointer to a record type";
4196 if (recordTy.getMembers().size() <=
getIndex())
4197 return emitError() <<
"member index out of bounds";
4201 return emitError() <<
"member owns no storage to point at";
4203 if (pointeeTy !=
getType().getPointee())
4204 return emitError() <<
"member type mismatch";
4206 if (getAddrTy().getAddrSpace() !=
getType().getAddrSpace())
4207 return emitError() <<
"address space mismatch";
4209 return mlir::success();
4216LogicalResult cir::ExtractMemberOp::verify() {
4217 if (mlir::isa<cir::UnionType>(getRecord().
getType()))
4219 <<
"cir.extract_member currently does not support unions";
4220 auto structTy = mlir::cast<cir::StructType>(getRecord().
getType());
4221 if (structTy.getMembers().size() <=
getIndex())
4222 return emitError() <<
"member index out of bounds";
4223 mlir::Type memberTy = structTy.getMembers()[
getIndex()];
4224 if (mlir::isa<cir::BitFieldType>(memberTy))
4225 return emitError() <<
"cir.extract_member does not support bit-fields";
4227 return emitError() <<
"member type mismatch";
4228 return mlir::success();
4235LogicalResult cir::InsertMemberOp::verify() {
4236 if (mlir::isa<cir::UnionType>(getRecord().
getType()))
4237 return emitError() <<
"cir.insert_member currently does not support unions";
4238 auto structTy = mlir::cast<cir::StructType>(getRecord().
getType());
4239 if (structTy.getMembers().size() <=
getIndex())
4240 return emitError() <<
"member index out of bounds";
4241 mlir::Type memberTy = structTy.getMembers()[
getIndex()];
4242 if (mlir::isa<cir::BitFieldType>(memberTy))
4243 return emitError() <<
"cir.insert_member does not support bit-fields";
4244 if (memberTy != getValue().
getType())
4245 return emitError() <<
"member type mismatch";
4247 return mlir::success();
4254OpFoldResult cir::VecCreateOp::fold(FoldAdaptor adaptor) {
4255 if (llvm::any_of(getElements(), [](mlir::Value value) {
4256 return !value.getDefiningOp<cir::ConstantOp>();
4260 return cir::ConstVectorAttr::get(
4261 getType(), mlir::ArrayAttr::get(getContext(), adaptor.getElements()));
4264LogicalResult cir::VecCreateOp::verify() {
4268 const cir::VectorType vecTy =
getType();
4269 if (vecTy.isScalable())
4270 return emitOpError() <<
"scalable vectors are not supported";
4272 if (getElements().size() != vecTy.getFixedSize()) {
4273 return emitOpError() <<
"operand count of " << getElements().size()
4274 <<
" doesn't match vector type " << vecTy
4275 <<
" element count of " << vecTy.getFixedSize();
4278 const mlir::Type elementType = vecTy.getElementType();
4279 for (
const mlir::Value element : getElements()) {
4280 if (element.getType() != elementType) {
4281 return emitOpError() <<
"operand type " << element.getType()
4282 <<
" doesn't match vector element type "
4294OpFoldResult cir::VecExtractOp::fold(FoldAdaptor adaptor) {
4295 const auto vectorAttr =
4296 llvm::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec());
4300 const auto indexAttr =
4301 llvm::dyn_cast_if_present<cir::IntAttr>(adaptor.getIndex());
4305 const mlir::ArrayAttr elements = vectorAttr.getElts();
4306 const uint64_t index = indexAttr.getUInt();
4307 if (index >= elements.size())
4310 return elements[index];
4317LogicalResult cir::CmpOp::verify() {
4318 if (getFenvAttr() && !cir::isAnyFloatingPointType(getLhs().
getType()))
4319 return emitOpError()
4320 <<
"'fenv' is only valid for floating-point comparisons";
4328LogicalResult cir::VecCmpOp::verify() {
4329 if (getFenvAttr() && !cir::isFPOrVectorOfFPType(getLhs().
getType()))
4330 return emitOpError()
4331 <<
"'fenv' is only valid for floating-point comparisons";
4335OpFoldResult cir::VecCmpOp::fold(FoldAdaptor adaptor) {
4345 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getLhs());
4347 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getRhs());
4348 if (!lhsVecAttr || !rhsVecAttr)
4351 mlir::Type inputElemTy =
4352 mlir::cast<cir::VectorType>(lhsVecAttr.getType()).getElementType();
4353 if (!isAnyIntegerOrFloatingPointType(inputElemTy))
4356 cir::CmpOpKind opKind = adaptor.getKind();
4357 mlir::ArrayAttr lhsVecElhs = lhsVecAttr.getElts();
4358 mlir::ArrayAttr rhsVecElhs = rhsVecAttr.getElts();
4359 uint64_t vecSize = lhsVecElhs.size();
4362 bool isIntAttr = vecSize && mlir::isa<cir::IntAttr>(lhsVecElhs[0]);
4363 bool isUnsignedInt =
4364 isIntAttr && mlir::cast<cir::IntType>(inputElemTy).isUnsigned();
4365 for (uint64_t i = 0; i < vecSize; i++) {
4366 mlir::Attribute lhsAttr = lhsVecElhs[i];
4367 mlir::Attribute rhsAttr = rhsVecElhs[i];
4368 bool cmpResult =
false;
4370 case cir::CmpOpKind::lt: {
4373 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() <
4374 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
4376 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <
4377 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
4379 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <
4380 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
4384 case cir::CmpOpKind::le: {
4387 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() <=
4388 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
4390 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <=
4391 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
4393 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <=
4394 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
4398 case cir::CmpOpKind::gt: {
4401 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() >
4402 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
4404 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >
4405 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
4407 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >
4408 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
4412 case cir::CmpOpKind::ge: {
4415 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() >=
4416 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
4418 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >=
4419 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
4421 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >=
4422 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
4426 case cir::CmpOpKind::eq: {
4428 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() ==
4429 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
4431 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() ==
4432 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
4436 case cir::CmpOpKind::ne: {
4438 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() !=
4439 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
4441 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() !=
4442 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
4446 case cir::CmpOpKind::one: {
4447 llvm::APFloat::cmpResult cr =
4448 mlir::cast<cir::FPAttr>(lhsAttr).getValue().compare(
4449 mlir::cast<cir::FPAttr>(rhsAttr).getValue());
4451 cr != llvm::APFloat::cmpUnordered && cr != llvm::APFloat::cmpEqual;
4454 case cir::CmpOpKind::uno: {
4455 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue().compare(
4456 mlir::cast<cir::FPAttr>(rhsAttr).getValue()) ==
4457 llvm::APFloat::cmpUnordered;
4466 cir::IntAttr::get(
getType().getElementType(), cmpResult ? -1LL : 0LL);
4469 return cir::ConstVectorAttr::get(
4470 getType(), mlir::ArrayAttr::get(getContext(), elements));
4477OpFoldResult cir::VecShuffleOp::fold(FoldAdaptor adaptor) {
4479 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec1());
4481 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec2());
4482 if (!vec1Attr || !vec2Attr)
4485 mlir::Type vec1ElemTy =
4486 mlir::cast<cir::VectorType>(vec1Attr.getType()).getElementType();
4488 mlir::ArrayAttr vec1Elts = vec1Attr.getElts();
4489 mlir::ArrayAttr vec2Elts = vec2Attr.getElts();
4490 mlir::ArrayAttr indicesElts = adaptor.getIndices();
4493 elements.reserve(indicesElts.size());
4495 uint64_t vec1Size = vec1Elts.size();
4496 for (
const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
4497 if (idxAttr.getSInt() == -1) {
4498 elements.push_back(cir::UndefAttr::get(vec1ElemTy));
4502 uint64_t idxValue = idxAttr.getUInt();
4503 elements.push_back(idxValue < vec1Size ? vec1Elts[idxValue]
4504 : vec2Elts[idxValue - vec1Size]);
4507 return cir::ConstVectorAttr::get(
4508 getType(), mlir::ArrayAttr::get(getContext(), elements));
4511LogicalResult cir::VecShuffleOp::verify() {
4512 if (getVec1().
getType().isScalable() || getVec2().
getType().isScalable() ||
4513 getResult().
getType().isScalable())
4514 return emitOpError() <<
"scalable vectors are not supported";
4518 if (getIndices().size() != getResult().
getType().getFixedSize()) {
4519 return emitOpError() <<
": the number of elements in " << getIndices()
4520 <<
" and " << getResult().getType() <<
" don't match";
4525 if (getVec1().
getType().getElementType() !=
4526 getResult().
getType().getElementType()) {
4527 return emitOpError() <<
": element types of " << getVec1().getType()
4528 <<
" and " << getResult().getType() <<
" don't match";
4531 const uint64_t maxValidIndex = getVec1().getType().getFixedSize() +
4532 getVec2().getType().getFixedSize() - 1;
4534 getIndices().getAsRange<cir::IntAttr>(), [&](cir::IntAttr idxAttr) {
4535 return idxAttr.getSInt() != -1 && idxAttr.getUInt() > maxValidIndex;
4537 return emitOpError() <<
": index for __builtin_shufflevector must be "
4538 "less than the total number of vector elements";
4547OpFoldResult cir::VecShuffleDynamicOp::fold(FoldAdaptor adaptor) {
4548 mlir::Attribute vec = adaptor.getVec();
4549 mlir::Attribute indices = adaptor.getIndices();
4550 if (mlir::isa_and_nonnull<cir::ConstVectorAttr>(vec) &&
4551 mlir::isa_and_nonnull<cir::ConstVectorAttr>(indices)) {
4552 auto vecAttr = mlir::cast<cir::ConstVectorAttr>(vec);
4553 auto indicesAttr = mlir::cast<cir::ConstVectorAttr>(indices);
4555 mlir::ArrayAttr vecElts = vecAttr.getElts();
4556 mlir::ArrayAttr indicesElts = indicesAttr.getElts();
4558 const uint64_t numElements = vecElts.size();
4561 elements.reserve(numElements);
4563 const uint64_t maskBits = llvm::NextPowerOf2(numElements - 1) - 1;
4564 for (
const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
4565 uint64_t idxValue = idxAttr.getUInt();
4566 uint64_t newIdx = idxValue & maskBits;
4567 elements.push_back(vecElts[newIdx]);
4570 return cir::ConstVectorAttr::get(
4571 getType(), mlir::ArrayAttr::get(getContext(), elements));
4577LogicalResult cir::VecShuffleDynamicOp::verify() {
4579 if (getVec().
getType().getSize() !=
4580 mlir::cast<cir::VectorType>(getIndices().
getType()).getSize()) {
4581 return emitOpError() <<
": the number of elements in " << getVec().getType()
4582 <<
" and " << getIndices().getType() <<
" don't match";
4591LogicalResult cir::VecTernaryOp::verify() {
4596 if (getCond().
getType().getSize() != getLhs().
getType().getSize()) {
4597 return emitOpError() <<
": the number of elements in "
4598 << getCond().getType() <<
" and " << getLhs().getType()
4604OpFoldResult cir::VecTernaryOp::fold(FoldAdaptor adaptor) {
4605 mlir::Attribute cond = adaptor.getCond();
4606 mlir::Attribute lhs = adaptor.getLhs();
4607 mlir::Attribute rhs = adaptor.getRhs();
4609 if (!mlir::isa_and_nonnull<cir::ConstVectorAttr>(cond) ||
4610 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(lhs) ||
4611 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(rhs))
4613 auto condVec = mlir::cast<cir::ConstVectorAttr>(cond);
4614 auto lhsVec = mlir::cast<cir::ConstVectorAttr>(lhs);
4615 auto rhsVec = mlir::cast<cir::ConstVectorAttr>(rhs);
4617 mlir::ArrayAttr condElts = condVec.getElts();
4620 elements.reserve(condElts.size());
4622 for (
const auto &[idx, condAttr] :
4623 llvm::enumerate(condElts.getAsRange<cir::IntAttr>())) {
4624 if (condAttr.getSInt()) {
4625 elements.push_back(lhsVec.getElts()[idx]);
4627 elements.push_back(rhsVec.getElts()[idx]);
4631 cir::VectorType vecTy = getLhs().getType();
4632 return cir::ConstVectorAttr::get(
4633 vecTy, mlir::ArrayAttr::get(getContext(), elements));
4640LogicalResult cir::MatrixTransposeOp::verify() {
4641 cir::MatrixType valueTy = getValue().getType();
4642 cir::MatrixType resultTy = getResult().getType();
4644 if ((valueTy.getElementType() != resultTy.getElementType()) ||
4645 (valueTy.getNumRows() != resultTy.getNumColumns()) ||
4646 (valueTy.getNumColumns() != resultTy.getNumRows())) {
4648 cir::MatrixType::get(valueTy.getElementType(), valueTy.getNumColumns(),
4649 valueTy.getNumRows());
4650 emitOpError() <<
"operand type " << valueTy <<
" expects result type of "
4651 << expectedTy <<
" but got " << resultTy;
4662LogicalResult cir::ComplexCreateOp::verify() {
4665 <<
"operand type of cir.complex.create does not match its result type";
4672OpFoldResult cir::ComplexCreateOp::fold(FoldAdaptor adaptor) {
4673 mlir::Attribute real = adaptor.getReal();
4674 mlir::Attribute imag = adaptor.getImag();
4680 auto realAttr = mlir::cast<mlir::TypedAttr>(real);
4681 auto imagAttr = mlir::cast<mlir::TypedAttr>(imag);
4682 return cir::ConstComplexAttr::get(realAttr, imagAttr);
4689LogicalResult cir::ComplexRealOp::verify() {
4690 mlir::Type operandTy = getOperand().getType();
4691 if (
auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
4692 operandTy = complexOperandTy.getElementType();
4695 emitOpError() <<
": result type does not match operand type";
4702OpFoldResult cir::ComplexRealOp::fold(FoldAdaptor adaptor) {
4703 if (!mlir::isa<cir::ComplexType>(getOperand().
getType()))
4706 if (
auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
4707 return complexCreateOp.getOperand(0);
4710 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
4711 return complex ? complex.getReal() :
nullptr;
4718LogicalResult cir::ComplexImagOp::verify() {
4719 mlir::Type operandTy = getOperand().getType();
4720 if (
auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
4721 operandTy = complexOperandTy.getElementType();
4724 emitOpError() <<
": result type does not match operand type";
4731OpFoldResult cir::ComplexImagOp::fold(FoldAdaptor adaptor) {
4732 if (!mlir::isa<cir::ComplexType>(getOperand().
getType()))
4735 if (
auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
4736 return complexCreateOp.getOperand(1);
4739 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
4740 return complex ? complex.getImag() :
nullptr;
4747LogicalResult cir::ComplexRealPtrOp::verify() {
4748 mlir::Type resultPointeeTy =
getType().getPointee();
4749 cir::PointerType operandPtrTy = getOperand().getType();
4750 auto operandPointeeTy =
4751 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
4753 if (resultPointeeTy != operandPointeeTy.getElementType()) {
4754 return emitOpError() <<
": result type does not match operand type";
4764LogicalResult cir::ComplexImagPtrOp::verify() {
4765 mlir::Type resultPointeeTy =
getType().getPointee();
4766 cir::PointerType operandPtrTy = getOperand().getType();
4767 auto operandPointeeTy =
4768 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
4770 if (resultPointeeTy != operandPointeeTy.getElementType()) {
4771 return emitOpError()
4772 <<
"cir.complex.imag_ptr result type does not match operand type";
4783 llvm::function_ref<llvm::APInt(
const llvm::APInt &)> func,
4784 bool poisonZero =
false) {
4785 if (mlir::isa_and_present<cir::PoisonAttr>(inputAttr)) {
4790 auto input = mlir::dyn_cast_if_present<IntAttr>(inputAttr);
4794 llvm::APInt inputValue = input.getValue();
4795 if (poisonZero && inputValue.isZero())
4796 return cir::PoisonAttr::get(input.getType());
4798 llvm::APInt resultValue = func(inputValue);
4799 return IntAttr::get(input.getType(), resultValue);
4802OpFoldResult BitClrsbOp::fold(FoldAdaptor adaptor) {
4803 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
4804 unsigned resultValue =
4805 inputValue.getBitWidth() - inputValue.getSignificantBits();
4806 return llvm::APInt(inputValue.getBitWidth(), resultValue);
4810OpFoldResult BitClzOp::fold(FoldAdaptor adaptor) {
4813 [](
const llvm::APInt &inputValue) {
4814 unsigned resultValue = inputValue.countLeadingZeros();
4815 return llvm::APInt(inputValue.getBitWidth(), resultValue);
4820OpFoldResult BitCtzOp::fold(FoldAdaptor adaptor) {
4823 [](
const llvm::APInt &inputValue) {
4824 return llvm::APInt(inputValue.getBitWidth(),
4825 inputValue.countTrailingZeros());
4830OpFoldResult BitFfsOp::fold(FoldAdaptor adaptor) {
4831 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
4832 unsigned trailingZeros = inputValue.countTrailingZeros();
4834 trailingZeros == inputValue.getBitWidth() ? 0 : trailingZeros + 1;
4835 return llvm::APInt(inputValue.getBitWidth(), result);
4839OpFoldResult BitParityOp::fold(FoldAdaptor adaptor) {
4840 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
4841 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount() % 2);
4845OpFoldResult BitPopcountOp::fold(FoldAdaptor adaptor) {
4846 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
4847 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount());
4851OpFoldResult BitReverseOp::fold(FoldAdaptor adaptor) {
4852 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
4853 return inputValue.reverseBits();
4857OpFoldResult ByteSwapOp::fold(FoldAdaptor adaptor) {
4858 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
4859 return inputValue.byteSwap();
4863OpFoldResult RotateOp::fold(FoldAdaptor adaptor) {
4864 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()) ||
4865 mlir::isa_and_present<cir::PoisonAttr>(adaptor.getAmount())) {
4867 return cir::PoisonAttr::get(
getType());
4870 auto input = mlir::dyn_cast_if_present<IntAttr>(adaptor.getInput());
4871 auto amount = mlir::dyn_cast_if_present<IntAttr>(adaptor.getAmount());
4872 if (!input && !amount)
4881 llvm::APInt inputValue;
4883 inputValue = input.getValue();
4884 if (inputValue.isZero() || inputValue.isAllOnes()) {
4890 uint64_t amountValue;
4892 amountValue = amount.getValue().urem(getInput().
getType().getWidth());
4893 if (amountValue == 0) {
4899 if (!input || !amount)
4902 assert(inputValue.getBitWidth() == getInput().
getType().getWidth() &&
4903 "input value must have the same bit width as the input type");
4905 llvm::APInt resultValue;
4907 resultValue = inputValue.rotl(amountValue);
4909 resultValue = inputValue.rotr(amountValue);
4911 return IntAttr::get(input.getContext(), input.getType(), resultValue);
4918void cir::InlineAsmOp::print(OpAsmPrinter &p) {
4919 p <<
'(' << getAsmFlavor() <<
", ";
4924 auto *nameIt = names.begin();
4925 auto *attrIt = getOperandAttrs().begin();
4927 for (mlir::OperandRange ops : getAsmOperands()) {
4928 p << *nameIt <<
" = ";
4931 llvm::interleaveComma(llvm::make_range(ops.begin(), ops.end()), p,
4933 p.printOperand(value);
4934 p <<
" : " << value.getType();
4935 if (mlir::isa<mlir::UnitAttr>(*attrIt))
4936 p <<
" (maybe_memory)";
4945 p.printString(getAsmString());
4947 p.printString(getConstraints());
4951 if (getSideEffects())
4952 p <<
" side_effects";
4954 p.printOptionalAttrDict(
4955 getOperation()->getDiscardableAttrDictionary().getValue());
4957 if (
auto v = getRes())
4958 p <<
" -> " << v.getType();
4961void cir::InlineAsmOp::build(OpBuilder &odsBuilder, OperationState &odsState,
4963 StringRef asmString, StringRef constraints,
4964 bool sideEffects, cir::AsmFlavor asmFlavor,
4968 for (
auto operandRange : asmOperands) {
4969 segments.push_back(operandRange.size());
4970 odsState.addOperands(operandRange);
4973 odsState.addAttribute(
4974 "operands_segments",
4975 DenseI32ArrayAttr::get(odsBuilder.getContext(), segments));
4976 odsState.addAttribute(
"asm_string", odsBuilder.getStringAttr(asmString));
4977 odsState.addAttribute(
"constraints", odsBuilder.getStringAttr(constraints));
4978 odsState.addAttribute(
"asm_flavor",
4979 AsmFlavorAttr::get(odsBuilder.getContext(), asmFlavor));
4982 odsState.addAttribute(
"side_effects", odsBuilder.getUnitAttr());
4984 odsState.addAttribute(
"operand_attrs", odsBuilder.getArrayAttr(operandAttrs));
4987ParseResult cir::InlineAsmOp::parse(OpAsmParser &parser,
4988 OperationState &result) {
4991 std::string asmString, constraints;
4993 MLIRContext *ctxt = parser.getBuilder().getContext();
4995 auto error = [&](
const Twine &msg) -> LogicalResult {
4996 return parser.emitError(parser.getCurrentLocation(), msg);
4999 auto expected = [&](
const std::string &c) {
5000 return error(
"expected '" + c +
"'");
5003 if (parser.parseLParen().failed())
5004 return expected(
"(");
5006 auto flavor = FieldParser<AsmFlavor, AsmFlavor>::parse(parser);
5008 return error(
"Unknown AsmFlavor");
5010 if (parser.parseComma().failed())
5011 return expected(
",");
5013 auto parseValue = [&](
Value &v) {
5014 OpAsmParser::UnresolvedOperand op;
5016 if (parser.parseOperand(op) || parser.parseColon())
5017 return error(
"can't parse operand");
5020 if (parser.parseType(typ).failed())
5021 return error(
"can't parse operand type");
5023 if (parser.resolveOperand(op, typ, tmp))
5024 return error(
"can't resolve operand");
5026 return mlir::success();
5029 auto parseOperands = [&](llvm::StringRef
name) {
5030 if (parser.parseKeyword(name).failed())
5031 return error(
"expected " + name +
" operands here");
5032 if (parser.parseEqual().failed())
5033 return expected(
"=");
5034 if (parser.parseLSquare().failed())
5035 return expected(
"[");
5038 if (parser.parseOptionalRSquare().succeeded()) {
5039 operandsGroupSizes.push_back(size);
5040 if (parser.parseComma())
5041 return expected(
",");
5042 return mlir::success();
5045 auto parseOperand = [&]() {
5047 if (parseValue(val).succeeded()) {
5048 result.operands.push_back(val);
5051 if (parser.parseOptionalLParen().failed()) {
5052 operandAttrs.push_back(mlir::DictionaryAttr::get(ctxt));
5053 return mlir::success();
5056 if (parser.parseKeyword(
"maybe_memory").succeeded()) {
5057 operandAttrs.push_back(mlir::UnitAttr::get(ctxt));
5058 if (parser.parseRParen())
5059 return expected(
")");
5060 return mlir::success();
5062 return expected(
"maybe_memory");
5065 return mlir::failure();
5068 if (parser.parseCommaSeparatedList(parseOperand).failed())
5069 return mlir::failure();
5071 if (parser.parseRSquare().failed() || parser.parseComma().failed())
5072 return expected(
"]");
5073 operandsGroupSizes.push_back(size);
5074 return mlir::success();
5077 if (parseOperands(
"out").failed() || parseOperands(
"in").failed() ||
5078 parseOperands(
"in_out").failed())
5079 return error(
"failed to parse operands");
5081 if (parser.parseLBrace())
5082 return expected(
"{");
5083 if (parser.parseString(&asmString))
5084 return error(
"asm string parsing failed");
5085 if (parser.parseString(&constraints))
5086 return error(
"constraints string parsing failed");
5087 if (parser.parseRBrace())
5088 return expected(
"}");
5089 if (parser.parseRParen())
5090 return expected(
")");
5092 if (parser.parseOptionalKeyword(
"side_effects").succeeded())
5093 result.attributes.set(
"side_effects", UnitAttr::get(ctxt));
5095 if (parser.parseOptionalAttrDict(result.attributes).failed())
5096 return mlir::failure();
5098 if (parser.parseOptionalArrow().succeeded() &&
5099 parser.parseType(resType).failed())
5100 return mlir::failure();
5102 result.attributes.set(
"asm_flavor", AsmFlavorAttr::get(ctxt, *flavor));
5103 result.attributes.set(
"asm_string", StringAttr::get(ctxt, asmString));
5104 result.attributes.set(
"constraints", StringAttr::get(ctxt, constraints));
5105 result.attributes.set(
"operand_attrs", ArrayAttr::get(ctxt, operandAttrs));
5106 result.getOrAddProperties<InlineAsmOp::Properties>().operands_segments =
5107 parser.getBuilder().getDenseI32ArrayAttr(operandsGroupSizes);
5109 result.addTypes(TypeRange{resType});
5111 return mlir::success();
5114void InlineAsmOp::getEffects(
5118 if (getSideEffects()) {
5119 effects.emplace_back(mlir::MemoryEffects::Read::get());
5120 effects.emplace_back(mlir::MemoryEffects::Write::get());
5128template <
typename ThrowOpTy>
5131 return mlir::success();
5133 if (op.getNumOperands() != 0) {
5134 if (op.getTypeInfo())
5135 return mlir::success();
5136 return op.emitOpError() <<
"'type_info' symbol attribute missing";
5139 return mlir::failure();
5144mlir::LogicalResult cir::TryThrowOp::verify() {
5152LogicalResult cir::AtomicFetchOp::verify() {
5153 if (getBinop() != cir::AtomicFetchKind::Add &&
5154 getBinop() != cir::AtomicFetchKind::Sub &&
5155 getBinop() != cir::AtomicFetchKind::Max &&
5156 getBinop() != cir::AtomicFetchKind::Min &&
5157 getBinop() != cir::AtomicFetchKind::Maximum &&
5158 getBinop() != cir::AtomicFetchKind::Minimum &&
5159 getBinop() != cir::AtomicFetchKind::MaximumNum &&
5160 getBinop() != cir::AtomicFetchKind::MinimumNum &&
5161 !mlir::isa<cir::IntType>(getVal().
getType()))
5162 return emitError(
"only atomic add, sub, max, min, maximum, minimum, "
5163 "maximum_num, and minimum_num operation could operate on "
5164 "floating-point values");
5166 if ((getBinop() == cir::AtomicFetchKind::Maximum ||
5167 getBinop() == cir::AtomicFetchKind::Minimum ||
5168 getBinop() == cir::AtomicFetchKind::MaximumNum ||
5169 getBinop() == cir::AtomicFetchKind::MinimumNum) &&
5170 !cir::isFPOrVectorOfFPType(getVal().
getType()))
5171 return emitError(
"atomic maximum, minimum, maximum_num, and minimum_num "
5172 "operation could only operate on floating-point values");
5181LogicalResult cir::TypeInfoAttr::verify(
5182 ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError,
5183 ::mlir::Type type, ::mlir::ArrayAttr typeInfoData) {
5185 if (cir::ConstRecordAttr::verify(emitError, type, typeInfoData).failed())
5195void cir::TryOp::getSuccessorRegions(
5196 mlir::RegionBranchPoint point,
5198 if (point.isParent()) {
5199 regions.emplace_back(&getTryRegion());
5202 mlir::Operation *term = point.getTerminatorPredecessorOrNull();
5203 if (term->getParentRegion() != &getTryRegion()) {
5204 regions.emplace_back(getOperation());
5209 if (!isa<cir::ResumeOp>(term) || getHandlerRegions().empty())
5210 regions.emplace_back(getOperation());
5219 regions.reserve(regions.size() + getHandlerRegions().size());
5220 for (mlir::Region &handlerRegion : getHandlerRegions())
5221 regions.emplace_back(&handlerRegion);
5232 cir::ConstructCatchParamOp constructOp) {
5233 mlir::WalkResult result =
5234 handlerRegion.walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
5235 if (mlir::isa<cir::TryOp>(op))
5236 return mlir::WalkResult::skip();
5237 auto initOp = mlir::dyn_cast<cir::InitCatchParamOp>(op);
5239 return mlir::WalkResult::advance();
5241 cir::InitCatchKind
kind = initOp.getKind();
5243 constructOp && constructOp.getParamAddr() == initOp.getParamAddr();
5244 if (sameParam && constructOp.getKind() !=
kind) {
5245 initOp.emitOpError(
"kind '")
5246 << cir::stringifyInitCatchKind(
kind)
5247 <<
"' does not match the kind '"
5248 << cir::stringifyInitCatchKind(constructOp.getKind())
5249 <<
"' of the preceding 'cir.construct_catch_param'";
5250 return mlir::WalkResult::interrupt();
5252 if ((
kind == cir::InitCatchKind::ReferenceToPointer ||
5253 kind == cir::InitCatchKind::NonTrivialCopy) &&
5255 initOp.emitOpError(
"'")
5256 << cir::stringifyInitCatchKind(
kind)
5257 <<
"' requires a preceding 'cir.construct_catch_param' of the "
5258 "same kind on the same parameter";
5259 return mlir::WalkResult::interrupt();
5261 return mlir::WalkResult::advance();
5263 return failure(result.wasInterrupted());
5266LogicalResult cir::TryOp::verifyRegions() {
5267 mlir::ArrayAttr handlerTypes = getHandlerTypes();
5268 if (!handlerTypes) {
5269 if (!getHandlerRegions().empty())
5271 "handler regions must be empty when no handler types are present");
5275 mlir::MutableArrayRef<mlir::Region> handlerRegions = getHandlerRegions();
5279 if (handlerRegions.size() != handlerTypes.size())
5281 "number of handler regions and handler types must match");
5289 if (llvm::any_of(handlerTypes, [](mlir::Attribute typeAttr) {
5290 return mlir::isa<cir::EhFilterAttr, cir::EhUnexpectedAttr>(typeAttr);
5292 if (handlerTypes.size() != 2 ||
5293 !mlir::isa<cir::EhFilterAttr>(handlerTypes[0]) ||
5294 !mlir::isa<cir::EhUnexpectedAttr>(handlerTypes[1]))
5295 return emitOpError(
"a filter handler must be followed by an unexpected "
5296 "handler, and the two must be the only handlers");
5299 for (
const auto &[typeAttr, handlerRegion] :
5300 llvm::zip(handlerTypes, handlerRegions)) {
5302 mlir::Block &entryBlock = handlerRegion.front();
5303 if (entryBlock.getNumArguments() != 1 ||
5304 !mlir::isa<cir::EhTokenType>(entryBlock.getArgument(0).getType()))
5306 "handler region must have a single '!cir.eh_token' argument");
5310 if (mlir::isa<cir::UnwindAttr, cir::EhFilterAttr, cir::EhUnexpectedAttr>(
5314 if (entryBlock.empty())
5315 return emitOpError(
"catch handler region must not be empty");
5321 if (mlir::isa<cir::EhTerminateOp>(entryBlock.front())) {
5322 if (!mlir::isa<cir::CatchAllAttr>(typeAttr))
5323 return emitOpError(
"'cir.eh.terminate' is only allowed in a catch-all "
5342 mlir::Operation *firstOp = &entryBlock.front();
5343 if (mlir::isa<cir::LifetimeStartOp>(firstOp)) {
5344 mlir::Operation *next = firstOp->getNextNode();
5345 auto lifetimeScope = mlir::dyn_cast_if_present<cir::CleanupScopeOp>(next);
5347 return emitOpError(
"'cir.lifetime.start' in a catch handler region "
5348 "must be followed by the 'cir.cleanup.scope' of "
5349 "its lifetime-end cleanup");
5350 if (lifetimeScope.getBodyRegion().empty())
5352 "'cir.lifetime.start' in a catch handler region must be "
5353 "followed by the 'cir.cleanup.scope' of its lifetime-end "
5355 mlir::Block &scopeBody = lifetimeScope.getBodyRegion().front();
5356 firstOp = scopeBody.empty() ?
nullptr : &scopeBody.front();
5360 mlir::dyn_cast_if_present<cir::ConstructCatchParamOp>(firstOp);
5362 firstOp = firstOp->getNextNode();
5363 if (!mlir::isa_and_present<cir::BeginCatchOp>(firstOp))
5365 "catch handler region must start with 'cir.begin_catch'");
5375 mlir::OpAsmPrinter &printer, cir::TryOp op,
5376 mlir::MutableArrayRef<mlir::Region> handlerRegions,
5377 mlir::ArrayAttr handlerTypes) {
5381 for (
const auto [typeIdx, typeAttr] : llvm::enumerate(handlerTypes)) {
5385 if (mlir::isa<cir::CatchAllAttr>(typeAttr)) {
5386 printer <<
"catch all ";
5387 }
else if (mlir::isa<cir::UnwindAttr>(typeAttr)) {
5388 printer <<
"unwind ";
5389 }
else if (
auto filterAttr = mlir::dyn_cast<cir::EhFilterAttr>(typeAttr)) {
5390 printer <<
"filter [";
5391 llvm::interleaveComma(
5392 filterAttr.getPermittedTypes(), printer,
5393 [&](mlir::Attribute sym) { printer.printAttribute(sym); });
5395 }
else if (mlir::isa<cir::EhUnexpectedAttr>(typeAttr)) {
5396 printer <<
"unexpected ";
5398 printer <<
"catch [type ";
5399 printer.printAttribute(typeAttr);
5404 mlir::Region ®ion = handlerRegions[typeIdx];
5405 if (!region.empty() && region.front().getNumArguments() > 0) {
5407 printer.printRegionArgument(region.front().getArgument(0));
5411 printer.printRegion(region,
5418 mlir::OpAsmParser &parser,
5420 mlir::ArrayAttr &handlerTypes) {
5422 auto parseCheckedCatcherRegion = [&]() -> mlir::ParseResult {
5423 handlerRegions.emplace_back(
new mlir::Region);
5425 mlir::Region &currRegion = *handlerRegions.back();
5429 if (parser.parseLParen())
5431 mlir::OpAsmParser::Argument arg;
5432 if (parser.parseArgument(arg,
true))
5434 regionArgs.push_back(arg);
5435 if (parser.parseRParen())
5438 mlir::SMLoc regionLoc = parser.getCurrentLocation();
5439 if (parser.parseRegion(currRegion, regionArgs)) {
5440 handlerRegions.clear();
5444 if (currRegion.empty())
5445 return parser.emitError(regionLoc,
"handler region shall not be empty");
5447 if (!(currRegion.back().mightHaveTerminator() &&
5448 currRegion.back().getTerminator()))
5449 return parser.emitError(
5450 regionLoc,
"blocks are expected to be explicitly terminated");
5455 bool hasCatchAll =
false;
5457 while (parser.parseOptionalKeyword(
"catch").succeeded()) {
5458 bool hasLSquare = parser.parseOptionalLSquare().succeeded();
5460 llvm::StringRef attrStr;
5461 if (parser.parseOptionalKeyword(&attrStr, {
"all",
"type"}).failed())
5462 return parser.emitError(parser.getCurrentLocation(),
5463 "expected 'all' or 'type' keyword");
5465 bool isCatchAll = attrStr ==
"all";
5468 return parser.emitError(parser.getCurrentLocation(),
5469 "can't have more than one catch all");
5473 mlir::Attribute exceptionRTTIAttr;
5474 if (!isCatchAll && parser.parseAttribute(exceptionRTTIAttr).failed())
5475 return parser.emitError(parser.getCurrentLocation(),
5476 "expected valid RTTI info attribute");
5478 catcherAttrs.push_back(isCatchAll
5479 ? cir::CatchAllAttr::get(parser.getContext())
5480 : exceptionRTTIAttr);
5482 if (hasLSquare && isCatchAll)
5483 return parser.emitError(parser.getCurrentLocation(),
5484 "catch all dosen't need RTTI info attribute");
5486 if (hasLSquare && parser.parseRSquare().failed())
5487 return parser.emitError(parser.getCurrentLocation(),
5488 "expected `]` after RTTI info attribute");
5490 if (parseCheckedCatcherRegion().failed())
5491 return mlir::failure();
5497 if (parser.parseOptionalKeyword(
"filter").succeeded()) {
5498 mlir::SMLoc filterLoc = parser.getCurrentLocation();
5500 auto parsePermittedType = [&]() -> mlir::ParseResult {
5501 mlir::SMLoc typeLoc = parser.getCurrentLocation();
5502 mlir::Attribute rtti;
5503 if (parser.parseAttribute(rtti).failed())
5504 return mlir::failure();
5505 if (!mlir::isa<cir::GlobalViewAttr>(rtti))
5506 return parser.emitError(typeLoc,
"expected a type info symbol naming a "
5507 "permitted exception type");
5508 permittedTypes.push_back(rtti);
5509 return mlir::success();
5512 .parseCommaSeparatedList(mlir::OpAsmParser::Delimiter::Square,
5515 return mlir::failure();
5517 auto filterAttr = cir::EhFilterAttr::getChecked(
5518 [&]() {
return parser.emitError(filterLoc); }, parser.getContext(),
5519 parser.getBuilder().getArrayAttr(permittedTypes));
5521 return mlir::failure();
5522 catcherAttrs.push_back(filterAttr);
5523 if (parseCheckedCatcherRegion().failed())
5524 return mlir::failure();
5527 if (parser.parseOptionalKeyword(
"unexpected").succeeded()) {
5528 catcherAttrs.push_back(cir::EhUnexpectedAttr::get(parser.getContext()));
5529 if (parseCheckedCatcherRegion().failed())
5530 return mlir::failure();
5533 if (parser.parseOptionalKeyword(
"unwind").succeeded()) {
5535 return parser.emitError(parser.getCurrentLocation(),
5536 "unwind can't be used with catch all");
5538 catcherAttrs.push_back(cir::UnwindAttr::get(parser.getContext()));
5539 if (parseCheckedCatcherRegion().failed())
5540 return mlir::failure();
5543 handlerTypes = parser.getBuilder().getArrayAttr(catcherAttrs);
5544 return mlir::success();
5552cir::EhTypeIdOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
5553 Operation *op = symbolTable.lookupNearestSymbolFrom(*
this, getTypeSymAttr());
5554 if (!isa_and_nonnull<GlobalOp>(op))
5555 return emitOpError(
"'")
5556 << getTypeSym() <<
"' does not reference a valid cir.global";
5564LogicalResult cir::LifetimeStartOp::verify() {
5568LogicalResult cir::LifetimeEndOp::verify() {
5578 auto intAttr = mlir::dyn_cast<mlir::IntegerAttr>(attr);
5579 if (!intAttr || !intAttr.getType().isSignlessInteger(32))
5580 return std::nullopt;
5581 int64_t width = intAttr.getInt();
5584 return std::nullopt;
5585 return static_cast<unsigned>(width);
5588LogicalResult cir::MemChrOp::verify() {
5589 auto moduleOp = (*this)->getParentOfType<mlir::ModuleOp>();
5591 return emitOpError(
"expects an enclosing module");
5594 if (mlir::cast<cir::PointerType>(getSrc().
getType()).getAddrSpace())
5595 return emitOpError(
"src must be in the default address space");
5597 auto checkWidth = [&](cir::IntType type, llvm::StringRef operandName,
5598 llvm::StringRef attrName) -> LogicalResult {
5599 mlir::Attribute
attr = moduleOp->getAttr(attrName);
5601 return emitOpError(
"expects the module to record ") << attrName;
5604 return emitOpError(
"requires ")
5606 <<
" to be a signless i32 holding a fundamental integer width";
5607 if (type.getWidth() != *width)
5608 return emitOpError() << operandName <<
" must have the width recorded in "
5613 if (failed(checkWidth(getPattern().
getType(),
"pattern",
5614 cir::CIRDialect::getIntTypeWidthAttrName())))
5616 return checkWidth(getLen().
getType(),
"len",
5617 cir::CIRDialect::getSizeTypeWidthAttrName());
5628 cir::InitCatchKind
kind,
5629 cir::PointerType paramAddrType) {
5630 if (
kind != cir::InitCatchKind::ReferenceToPointer &&
5631 kind != cir::InitCatchKind::ReferenceToRecordPointer)
5634 auto refType = mlir::dyn_cast<cir::PointerType>(paramAddrType.getPointee());
5635 if (!refType || !mlir::isa<cir::PointerType>(refType.getPointee()))
5636 return op->emitOpError(
"'")
5637 << cir::stringifyInitCatchKind(
kind)
5638 <<
"' requires 'param_addr' to be the address of a reference to a "
5643LogicalResult cir::InitCatchParamOp::verify() {
5651LogicalResult cir::ConstructCatchParamOp::verify() {
5655LogicalResult cir::ConstructCatchParamOp::verifySymbolUses(
5656 SymbolTableCollection &symbolTable) {
5657 auto copyFnAttr = getCopyFnAttr();
5661 symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(*
this, getCopyFnAttr());
5663 return emitOpError(
"'")
5664 << *getCopyFn() <<
"' does not reference a valid cir.func";
5666 if (!fn->hasAttr(cir::CIRDialect::getCatchCopyThunkAttrName()))
5667 return emitOpError(
"catch-init copy_fn must be tagged with the ")
5668 << cir::CIRDialect::getCatchCopyThunkAttrName() <<
" attribute";
5670 cir::FuncType fnType = fn.getFunctionType();
5671 if (fnType.getNumInputs() != 2 || !fnType.hasVoidReturn())
5672 return emitOpError(
"catch-init copy_fn must take two pointer arguments and "
5675 if (fnType.getInput(0) != getParamAddr().
getType())
5676 return emitOpError(
"first argument of catch-init copy_fn must match the "
5677 "type of 'param_addr'");
5679 if (fnType.getInput(1) != getParamAddr().
getType())
5681 "second argument of catch-init copy_fn must be a pointer "
5682 "to the catch type");
5691LogicalResult cir::EhDispatchOp::verify() {
5692 mlir::ArrayAttr handlerTypes = getCatchTypesAttr();
5696 bool hasFilter =
false;
5697 for (mlir::Attribute typeAttr : handlerTypes) {
5698 if (!mlir::isa<cir::EhFilterAttr>(typeAttr))
5701 return emitOpError(
"can't have more than one 'filter' handler");
5709 if (hasFilter && getDefaultIsCatchAll())
5711 "'filter' handler requires an 'unwind' default destination");
5717 OpAsmParser &parser, mlir::ArrayAttr &catchTypes,
5718 SmallVectorImpl<Block *> &catchDestinations, Block *&defaultDestination,
5719 mlir::UnitAttr &defaultIsCatchAll) {
5721 if (parser.parseLSquare())
5725 bool hasCatchAll =
false;
5726 bool hasUnwind =
false;
5729 auto parseHandler = [&]() -> ParseResult {
5731 if (succeeded(parser.parseOptionalKeyword(
"catch_all"))) {
5733 return parser.emitError(parser.getCurrentLocation(),
5734 "duplicate 'catch_all' handler");
5736 return parser.emitError(parser.getCurrentLocation(),
5737 "cannot have both 'catch_all' and 'unwind'");
5740 if (parser.parseColon().failed())
5743 if (parser.parseSuccessor(defaultDestination).failed())
5749 if (succeeded(parser.parseOptionalKeyword(
"unwind"))) {
5751 return parser.emitError(parser.getCurrentLocation(),
5752 "duplicate 'unwind' handler");
5754 return parser.emitError(parser.getCurrentLocation(),
5755 "cannot have both 'catch_all' and 'unwind'");
5758 if (parser.parseColon().failed())
5761 if (parser.parseSuccessor(defaultDestination).failed())
5769 if (succeeded(parser.parseOptionalKeyword(
"filter"))) {
5770 SMLoc filterLoc = parser.getCurrentLocation();
5772 auto parsePermittedType = [&]() -> ParseResult {
5773 mlir::SMLoc
typeLoc = parser.getCurrentLocation();
5774 mlir::Attribute rtti;
5775 if (parser.parseAttribute(rtti).failed())
5777 if (!mlir::isa<cir::GlobalViewAttr>(rtti))
5778 return parser.emitError(typeLoc,
5779 "expected a type info symbol naming a "
5780 "permitted exception type");
5781 permittedTypes.push_back(rtti);
5785 .parseCommaSeparatedList(OpAsmParser::Delimiter::Paren,
5790 auto filterAttr = cir::EhFilterAttr::getChecked(
5791 [&]() {
return parser.emitError(filterLoc); }, parser.getContext(),
5792 parser.getBuilder().getArrayAttr(permittedTypes));
5795 handlerTypes.push_back(filterAttr);
5797 if (parser.parseColon().failed())
5801 if (parser.parseSuccessor(dest).failed())
5803 catchDestinations.push_back(dest);
5810 if (parser.parseKeyword(
"catch").failed())
5813 if (parser.parseLParen().failed())
5816 mlir::Attribute catchTypeAttr;
5817 if (parser.parseAttribute(catchTypeAttr).failed())
5819 handlerTypes.push_back(catchTypeAttr);
5821 if (parser.parseRParen().failed())
5824 if (parser.parseColon().failed())
5828 if (parser.parseSuccessor(dest).failed())
5830 catchDestinations.push_back(dest);
5834 if (parser.parseCommaSeparatedList(parseHandler).failed())
5837 if (parser.parseRSquare().failed())
5841 if (!hasCatchAll && !hasUnwind)
5842 return parser.emitError(parser.getCurrentLocation(),
5843 "must have either 'catch_all' or 'unwind' handler");
5846 if (!handlerTypes.empty())
5847 catchTypes = parser.getBuilder().getArrayAttr(handlerTypes);
5850 defaultIsCatchAll = parser.getBuilder().getUnitAttr();
5856 mlir::ArrayAttr catchTypes,
5857 SuccessorRange catchDestinations,
5858 Block *defaultDestination,
5859 mlir::UnitAttr defaultIsCatchAll) {
5867 llvm::zip(catchTypes, catchDestinations),
5869 mlir::Attribute typeAttr = std::get<0>(i);
5870 if (
auto filterAttr = mlir::dyn_cast<cir::EhFilterAttr>(typeAttr)) {
5872 llvm::interleaveComma(
5873 filterAttr.getPermittedTypes(), p,
5874 [&](mlir::Attribute sym) { p.printAttribute(sym); });
5877 p.printAttribute(typeAttr);
5880 p.printSuccessor(std::get<1>(i));
5892 if (defaultIsCatchAll)
5893 p <<
" catch_all : ";
5896 p.printSuccessor(defaultDestination);
5906bool cir::StdFindOp::signatureMatches(mlir::TypeRange operands,
5907 mlir::TypeRange results) {
5908 if (operands.size() != getNumArgs() || results.size() != 1)
5910 mlir::Type iterTy = operands[0];
5911 return iterTy == operands[1] && iterTy == operands[2] && iterTy == results[0];
static StringRef bytes(const std::vector< T, Allocator > &v)
static LogicalResult verifyLoopCleanup(LoopOpTy op)
static LogicalResult verifyOpenCLCXXVersion(ModuleOp module, cir::OpenCLVersionAttr cxxVersion)
static LogicalResult verifyCatchParamPairing(mlir::Region &handlerRegion, cir::ConstructCatchParamOp constructOp)
Verify that each cir.init_catch_param in handlerRegion, outside any nested cir.try,...
static mlir::LogicalResult checkReturnAndFunction(cir::ReturnOp op, cir::FuncOp function)
static LogicalResult verifyOffloadContainer(mlir::Operation *op)
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 LogicalResult verifyCatchParamAddr(mlir::Operation *op, cir::InitCatchKind kind, cir::PointerType paramAddrType)
For the reference_to_pointer and reference_to_record_pointer kinds, emit an error on op unless paramA...
static void printConstant(OpAsmPrinter &p, Attribute value)
static ParseResult checkEffectAttrKinds(mlir::OpAsmParser &parser, llvm::SMLoc loc, const mlir::NamedAttrList &attrs)
Reject an attribute in an explicit attribute dictionary whose value is not the attribute class expect...
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 bool areOpenCLVersionsCompatible(cir::OpenCLVersionAttr openCLVersion, cir::OpenCLVersionAttr cxxVersion)
static LogicalResult verifyOpenCLVersionAttrPlacement(Operation *op, NamedAttribute attr)
static bool isInVarCtorRegion(mlir::Operation *op)
Returns true if op is nested in the ctor region of a cir.global or cir.local_init without crossing a ...
ParseResult parseInlineKindAttr(OpAsmParser &parser, cir::InlineKindAttr &inlineKindAttr)
void printInlineKindAttr(OpAsmPrinter &p, cir::InlineKindAttr inlineKindAttr)
static LogicalResult verifyOpenCLVersionAttr(Operation *op, NamedAttribute attr)
static LogicalResult verifyCallCommInSymbolUses(mlir::Operation *op, SymbolTableCollection &symbolTable)
static bool isOpenCLVersionAttrName(StringRef attrName)
static LogicalResult ensureRegionTerm(OpAsmParser &parser, Region ®ion, SMLoc errLoc)
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 LogicalResult verifyProducedBy(Operation *op, Value operand, StringRef operandName)
static mlir::ParseResult parseTryCallDestinations(mlir::OpAsmParser &parser, mlir::OperationState &result)
static void printComdatName(OpAsmPrinter &p, StringAttr comdat)
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 bool omitRegionTerm(mlir::Region &r)
static ParseResult parseConstantValue(OpAsmParser &parser, mlir::Attribute &valueAttr)
static LogicalResult verifyArrayCtorDtor(Op op)
static bool isFuncAttrInDict(llvm::StringRef name)
Declared cir.func attributes with no dedicated syntax, which print in and parse from the attribute di...
static bool isRedundantBeforeReturn(mlir::Region &cleanupRegion)
static mlir::LogicalResult verifyThrowOpImpl(ThrowOpTy op)
static LogicalResult checkConstantTypes(mlir::Operation *op, mlir::Type opType, mlir::Attribute attrType)
#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
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
unsigned getProgramAddressSpace() const
C++ view class that accepts both !cir.struct and !cir.union types.
llvm::ArrayRef< mlir::Type > getMembers() const
static bool isSupportedCXXABI(const llvm::Triple &T, Kind Kind)
static bool isABI(StringRef Name)
Kind
The basic C++ ABI kind.
void addBytecodeInterface(CIRDialect *dialect)
Add the interfaces necessary for encoding the CIR dialect components in bytecode.
mlir::ParseResult parseEhDispatchDestinations(mlir::OpAsmParser &parser, mlir::ArrayAttr &catchTypes, llvm::SmallVectorImpl< mlir::Block * > &catchDestinations, mlir::Block *&defaultDestination, mlir::UnitAttr &defaultIsCatchAll)
mlir::ParseResult parseOmittedTerminatorRegion(mlir::OpAsmParser &parser, mlir::Region ®ion)
void printCopyTypes(mlir::OpAsmPrinter &printer, mlir::Operation *, mlir::Type srcType, mlir::Type dstType)
mlir::ParseResult parseCopyTypes(mlir::OpAsmParser &parser, mlir::Type &srcType, mlir::Type &dstType)
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...
void printComdatName(mlir::OpAsmPrinter &p, cir::GlobalOp op, mlir::StringAttr comdat)
mlir::ParseResult parseGlobalOpTypeAndInitialValue(mlir::OpAsmParser &parser, mlir::TypeAttr &typeAttr, mlir::Attribute &initialValueAttr, mlir::Region &ctorRegion, mlir::Region &dtorRegion)
mlir::ParseResult parseSwitchFlatOpCases(mlir::OpAsmParser &parser, mlir::Type flagType, mlir::ArrayAttr &caseValues, llvm::SmallVectorImpl< mlir::Block * > &caseDestinations, llvm::SmallVectorImpl< llvm::SmallVector< mlir::OpAsmParser::UnresolvedOperand > > &caseOperands, llvm::SmallVectorImpl< llvm::SmallVector< mlir::Type > > &caseOperandTypes)
bool isValidFundamentalIntWidth(unsigned width)
void buildTerminatedBody(mlir::OpBuilder &builder, mlir::Location loc)
mlir::ParseResult parseAssumeBundle(mlir::OpAsmParser &p, cir::AssumeBundleKindAttr &bundleKindAttr, llvm::SmallVector< mlir::OpAsmParser::UnresolvedOperand, 4 > &bundleArgs, llvm::SmallVector< mlir::Type, 1 > &bundleArgTypes)
mlir::ParseResult parseComdatName(mlir::OpAsmParser &parser, mlir::StringAttr &comdatAttr)
AllocaOp getUnderlyingAlloca(mlir::Value addr)
The alloca that defines addr, looking through casts that preserve the underlying storage.
void printOmittedTerminatorRegion(mlir::OpAsmPrinter &printer, cir::ScopeOp &op, mlir::Region ®ion)
void printTryHandlerRegions(mlir::OpAsmPrinter &printer, cir::TryOp op, mlir::MutableArrayRef< mlir::Region > handlerRegions, mlir::ArrayAttr handlerTypes)
mlir::ptr::MemorySpaceAttrInterface normalizeDefaultAddressSpace(mlir::ptr::MemorySpaceAttrInterface addrSpace)
Normalize LangAddressSpace::Default to null (empty attribute).
void printIndirectBrOpSucessors(mlir::OpAsmPrinter &p, cir::IndirectBrOp op, mlir::Type flagType, mlir::SuccessorRange succs, mlir::OperandRangeRange succOperands, const mlir::TypeRangeRange &succOperandsTypes)
mlir::ParseResult parseTryHandlerRegions(mlir::OpAsmParser &parser, llvm::SmallVectorImpl< std::unique_ptr< mlir::Region > > &handlerRegions, mlir::ArrayAttr &handlerTypes)
mlir::ParseResult parseIndirectBrOpSucessors(mlir::OpAsmParser &parser, mlir::Type &flagType, llvm::SmallVectorImpl< mlir::Block * > &succOperandBlocks, llvm::SmallVectorImpl< llvm::SmallVector< mlir::OpAsmParser::UnresolvedOperand > > &succOperands, llvm::SmallVectorImpl< llvm::SmallVector< mlir::Type > > &succOperandsTypes)
void printGlobalOpTypeAndInitialValue(mlir::OpAsmPrinter &p, cir::GlobalOp op, mlir::TypeAttr type, mlir::Attribute initAttr, mlir::Region &ctorRegion, mlir::Region &dtorRegion)
std::optional< llvm::Triple > getTripleFromModule(mlir::ModuleOp mod)
Attempts to construct an llvm::Triple from a module's cir.triple attribute.
void printEhDispatchDestinations(mlir::OpAsmPrinter &p, cir::EhDispatchOp op, mlir::ArrayAttr catchTypes, mlir::SuccessorRange catchDestinations, mlir::Block *defaultDestination, mlir::UnitAttr defaultIsCatchAll)
void printAssumeBundle(mlir::OpAsmPrinter &p, cir::AssumeOp op, cir::AssumeBundleKindAttr kindAttr, mlir::OperandRange bundleArgs, mlir::TypeRange bundleArgTypes)
void printSwitchFlatOpCases(mlir::OpAsmPrinter &p, cir::SwitchFlatOp op, mlir::Type flagType, mlir::ArrayAttr caseValues, mlir::SuccessorRange caseDestinations, mlir::OperandRangeRange caseOperands, const mlir::TypeRangeRange &caseOperandTypes)
const AstTypeMatcher< BuiltinType > builtinType
const internal::VariadicAllOfMatcher< Attr > attr
const internal::VariadicAllOfMatcher< TypeLoc > typeLoc
Matches TypeLocs in the clang AST.
const AstTypeMatcher< RecordType > recordType
StringRef getName(const HeaderType T)
void info(bool Verbose, unsigned Level, const char *Fmt, Ts &&...Args)
Prints an indented note to stderr when Verbose is set.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
__builtin_bitreverse32 uint32_t __builtin_riscv_aaddu_u32 __builtin_riscv_asubu_u32 __builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t uint32_t uint32_t __builtin_riscv_mhacc_i32 __builtin_riscv_mhaccu_u32 __builtin_riscv_mhaccsu_i32 __builtin_riscv_mulq_i32 int64_t
static bool memberFuncPtrCast()
static bool opCallCallConv()
static bool opScopeCleanupRegion()
static bool supportIFuncAttr()