19#include "mlir/IR/Attributes.h"
20#include "mlir/IR/BuiltinTypes.h"
21#include "mlir/IR/DialectImplementation.h"
22#include "mlir/IR/PatternMatch.h"
23#include "mlir/IR/Value.h"
24#include "mlir/Interfaces/ControlFlowInterfaces.h"
25#include "mlir/Interfaces/FunctionImplementation.h"
26#include "mlir/Support/LLVM.h"
28#include "clang/CIR/Dialect/IR/CIROpsDialect.cpp.inc"
29#include "clang/CIR/Dialect/IR/CIROpsEnums.cpp.inc"
31#include "llvm/ADT/SetOperations.h"
32#include "llvm/ADT/SmallSet.h"
33#include "llvm/ADT/TypeSwitch.h"
34#include "llvm/Support/LogicalResult.h"
43struct CIROpAsmDialectInterface :
public OpAsmDialectInterface {
44 using OpAsmDialectInterface::OpAsmDialectInterface;
46 AliasResult getAlias(Type type, raw_ostream &os)
const final {
47 if (
auto recordType = dyn_cast<cir::RecordType>(type)) {
50 os <<
"rec_anon_" <<
recordType.getKindAsStr();
52 os <<
"rec_" << nameAttr.getValue();
53 return AliasResult::OverridableAlias;
55 if (
auto intType = dyn_cast<cir::IntType>(type)) {
58 unsigned width = intType.getWidth();
59 if (width < 8 || !llvm::isPowerOf2_32(width))
60 return AliasResult::NoAlias;
61 os << intType.getAlias();
62 return AliasResult::OverridableAlias;
64 if (
auto voidType = dyn_cast<cir::VoidType>(type)) {
65 os << voidType.getAlias();
66 return AliasResult::OverridableAlias;
69 return AliasResult::NoAlias;
72 AliasResult getAlias(Attribute attr, raw_ostream &os)
const final {
73 if (
auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr)) {
74 os << (boolAttr.getValue() ?
"true" :
"false");
75 return AliasResult::FinalAlias;
77 if (
auto bitfield = mlir::dyn_cast<cir::BitfieldInfoAttr>(attr)) {
78 os <<
"bfi_" << bitfield.getName().str();
79 return AliasResult::FinalAlias;
81 if (
auto dynCastInfoAttr = mlir::dyn_cast<cir::DynamicCastInfoAttr>(attr)) {
82 os << dynCastInfoAttr.getAlias();
83 return AliasResult::FinalAlias;
85 if (
auto cmpThreeWayInfoAttr =
86 mlir::dyn_cast<cir::CmpThreeWayInfoAttr>(attr)) {
87 os << cmpThreeWayInfoAttr.getAlias();
88 return AliasResult::FinalAlias;
90 return AliasResult::NoAlias;
95void cir::CIRDialect::initialize() {
100#include "clang/CIR/Dialect/IR/CIROps.cpp.inc"
102 addInterfaces<CIROpAsmDialectInterface>();
105Operation *cir::CIRDialect::materializeConstant(mlir::OpBuilder &builder,
106 mlir::Attribute value,
108 mlir::Location loc) {
109 return cir::ConstantOp::create(builder, loc, type,
110 mlir::cast<mlir::TypedAttr>(value));
122 for (
auto en : llvm::enumerate(keywords)) {
123 if (succeeded(parser.parseOptionalKeyword(en.value())))
130template <
typename Ty>
struct EnumTraits {};
132#define REGISTER_ENUM_TYPE(Ty) \
133 template <> struct EnumTraits<cir::Ty> { \
134 static llvm::StringRef stringify(cir::Ty value) { \
135 return stringify##Ty(value); \
137 static unsigned getMaxEnumVal() { return cir::getMaxEnumValFor##Ty(); } \
149template <
typename EnumTy,
typename RetTy = EnumTy>
152 for (
unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
153 names.push_back(EnumTraits<EnumTy>::stringify(
static_cast<EnumTy
>(i)));
157 return static_cast<RetTy
>(defaultValue);
158 return static_cast<RetTy
>(index);
162template <
typename EnumTy,
typename RetTy = EnumTy>
165 for (
unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
166 names.push_back(EnumTraits<EnumTy>::stringify(
static_cast<EnumTy
>(i)));
171 result =
static_cast<RetTy
>(index);
179 Location eLoc = parser.getEncodedSourceLoc(parser.getCurrentLocation());
180 OpBuilder builder(parser.getBuilder().getContext());
185 builder.createBlock(®ion);
187 Block &block = region.back();
189 if (!block.empty() && block.back().hasTrait<OpTrait::IsTerminator>())
193 if (!region.hasOneBlock())
194 return parser.emitError(errLoc,
195 "multi-block region must not omit terminator");
198 builder.setInsertionPointToEnd(&block);
199 cir::YieldOp::create(builder, eLoc);
205 const auto singleNonEmptyBlock = r.hasOneBlock() && !r.back().empty();
206 const auto yieldsNothing = [&r]() {
207 auto y = dyn_cast<cir::YieldOp>(r.back().getTerminator());
208 return y && y.getArgs().empty();
210 return singleNonEmptyBlock && yieldsNothing();
215template <
typename ExpectedProducerOp>
217 StringRef operandName) {
218 Operation *producer = operand.getDefiningOp();
219 if (!producer || !isa<ExpectedProducerOp>(producer))
220 return op->emitOpError()
221 <<
"operand '" << operandName <<
"' must be produced by '"
222 << ExpectedProducerOp::getOperationName() <<
"'";
231 cir::InlineKindAttr &inlineKindAttr) {
233 static constexpr llvm::StringRef keywords[] = {
"no_inline",
"always_inline",
237 llvm::StringRef keyword;
238 if (parser.parseOptionalKeyword(&keyword, keywords).failed()) {
244 auto inlineKindResult = ::cir::symbolizeEnum<::cir::InlineKind>(keyword);
245 if (!inlineKindResult) {
246 return parser.emitError(parser.getCurrentLocation(),
"expected one of [")
248 <<
"] for inlineKind, got: " << keyword;
252 ::cir::InlineKindAttr::get(parser.getContext(), *inlineKindResult);
257 if (inlineKindAttr) {
258 p <<
" " << stringifyInlineKind(inlineKindAttr.getValue());
266 mlir::Region ®ion) {
267 auto regionLoc = parser.getCurrentLocation();
268 if (parser.parseRegion(region))
277 mlir::Region ®ion) {
278 printer.printRegion(region,
283mlir::OptionalParseResult
285 mlir::ptr::MemorySpaceAttrInterface &attr);
288 mlir::ptr::MemorySpaceAttrInterface attr);
294void cir::AllocaOp::build(mlir::OpBuilder &odsBuilder,
295 mlir::OperationState &odsState, mlir::Type addr,
296 llvm::StringRef name, mlir::IntegerAttr alignment) {
297 odsState.addAttribute(getNameAttrName(odsState.name),
298 odsBuilder.getStringAttr(name));
300 odsState.addAttribute(getAlignmentAttrName(odsState.name), alignment);
302 odsState.addTypes(addr);
310 auto ptrTy = mlir::cast<cir::PointerType>(op.getAddr().getType());
311 mlir::Type pointeeTy = ptrTy.getPointee();
313 mlir::Block &body = op.getBody().front();
314 if (body.getNumArguments() != 1)
315 return op.emitOpError(
"body must have exactly one block argument");
317 auto expectedEltPtrTy =
318 mlir::dyn_cast<cir::PointerType>(body.getArgument(0).getType());
319 if (!expectedEltPtrTy)
320 return op.emitOpError(
"block argument must be a !cir.ptr type");
322 if (op.getNumElements()) {
323 auto recTy = mlir::dyn_cast<cir::RecordType>(pointeeTy);
325 return op.emitOpError(
326 "when 'num_elements' is present, 'addr' must be a pointer to a "
327 "!cir.struct or !cir.union type");
329 if (expectedEltPtrTy != ptrTy)
330 return op.emitOpError(
"when 'num_elements' is present, 'addr' type must "
331 "match the block argument type");
333 auto arrayTy = mlir::dyn_cast<cir::ArrayType>(pointeeTy);
335 return op.emitOpError(
336 "when 'num_elements' is absent, 'addr' must be a pointer to a "
339 mlir::Type innerEltTy = arrayTy.getElementType();
340 while (
auto nested = mlir::dyn_cast<cir::ArrayType>(innerEltTy))
341 innerEltTy = nested.getElementType();
343 auto recTy = mlir::dyn_cast<cir::RecordType>(innerEltTy);
345 return op.emitOpError(
"the block argument type must be a pointer to a "
346 "!cir.struct or !cir.union type");
348 if (expectedEltPtrTy.getPointee() != innerEltTy)
349 return op.emitOpError(
350 "block argument pointee type must match the innermost array "
357LogicalResult cir::ArrayCtor::verify() {
361 mlir::Region &partialDtor = getPartialDtor();
362 if (!partialDtor.empty()) {
363 mlir::Block &dtorBlock = partialDtor.front();
364 if (dtorBlock.getNumArguments() != 1)
365 return emitOpError(
"partial_dtor must have exactly one block argument");
367 auto bodyArgTy = getBody().front().getArgument(0).getType();
368 if (dtorBlock.getArgument(0).getType() != bodyArgTy)
369 return emitOpError(
"partial_dtor block argument type must match "
370 "the body block argument type");
380LogicalResult cir::DeleteArrayOp::verify() {
381 if (getDtorMayThrow() && !getElementDtorAttr())
383 "'dtor_may_throw' requires an 'element_dtor' to be present");
392 cir::AssumeBundleKindAttr kindAttr,
393 OperandRange bundleArgs,
394 TypeRange bundleArgTypes) {
395 cir::AssumeBundleKind
kind = kindAttr.getValue();
396 if (
kind == cir::AssumeBundleKind::None)
399 p <<
" " << cir::stringifyAssumeBundleKind(
kind);
400 if (bundleArgs.empty())
404 p.printOperands(bundleArgs);
406 llvm::interleaveComma(bundleArgTypes, p);
411 OpAsmParser &p, cir::AssumeBundleKindAttr &bundleKindAttr,
415 auto loc = p.getCurrentLocation();
416 if (failed(p.parseOptionalKeyword(&keyword))) {
417 bundleKindAttr = cir::AssumeBundleKindAttr::get(
418 p.getContext(), cir::AssumeBundleKind::None);
422 std::optional<cir::AssumeBundleKind> parsedKind =
423 cir::symbolizeAssumeBundleKind(keyword);
425 return p.emitError(loc,
"unknown assume bundle kind '") << keyword <<
"'";
427 bundleKindAttr = cir::AssumeBundleKindAttr::get(p.getContext(), *parsedKind);
429 if (p.parseOptionalLParen())
432 if (p.parseOperandList(bundleArgs) || p.parseColon() ||
433 p.parseTypeList(bundleArgTypes) || p.parseRParen())
439LogicalResult cir::AssumeOp::verify() {
440 cir::AssumeBundleKind
kind = getBundleKind();
441 size_t numArgs = getBundleArgs().size();
443 if (
kind == cir::AssumeBundleKind::None) {
445 return emitOpError(
"unexpected bundle operands for kind 'none'");
450 return emitOpError(
"expected bundle operands for kind '")
451 << cir::stringifyAssumeBundleKind(
kind) <<
"'";
454 case cir::AssumeBundleKind::Align:
455 if (numArgs != 2 && numArgs != 3)
456 return emitOpError(
"align bundle expects 2 or 3 operands");
458 case cir::AssumeBundleKind::SeparateStorage:
460 return emitOpError(
"separate_storage bundle expects 2 operands");
462 case cir::AssumeBundleKind::Dereferenceable:
464 return emitOpError(
"dereferenceable bundle expects 2 operands");
477cir::LocalInitOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
478 cir::GlobalOp global = getReferencedGlobal(symbolTable);
480 return emitOpError(
"'")
481 << getGlobalName() <<
"' does not reference a valid cir.global";
483 if (getTls() && !global.getTlsModel())
484 return emitOpError(
"access to global not marked thread local");
486 if (!global.getStaticLocalGuard().has_value())
487 return emitOpError(
"static_local attribute mismatch");
500void cir::ConditionOp::getSuccessorRegions(
506 if (
auto loopOp = dyn_cast<LoopOpInterface>(getOperation()->getParentOp())) {
507 regions.emplace_back(&loopOp.getBody());
508 regions.emplace_back(getOperation());
513 auto await = cast<AwaitOp>(getOperation()->getParentOp());
514 regions.emplace_back(&await.getResume());
515 regions.emplace_back(&await.getSuspend());
519cir::ConditionOp::getMutableSuccessorOperands(RegionSuccessor point) {
521 return MutableOperandRange(getOperation(), 0, 0);
525cir::ResumeOp::getMutableSuccessorOperands(RegionSuccessor point) {
527 return MutableOperandRange(getOperation(), 0, 0);
530LogicalResult cir::ConditionOp::verify() {
531 if (!isa<LoopOpInterface, AwaitOp>(getOperation()->getParentOp()))
532 return emitOpError(
"condition must be within a conditional region");
541 mlir::Attribute attrType) {
542 if (isa<cir::ConstPtrAttr>(attrType)) {
543 if (!mlir::isa<cir::PointerType>(opType))
544 return op->emitOpError(
545 "pointer constant initializing a non-pointer type");
549 if (isa<cir::DataMemberAttr, cir::MethodAttr>(attrType)) {
555 if (isa<cir::ZeroAttr>(attrType)) {
556 if (isa<cir::RecordType, cir::ArrayType, cir::VectorType, cir::ComplexType>(
559 return op->emitOpError(
560 "zero expects struct, array, vector, or complex type");
563 if (mlir::isa<cir::UndefAttr>(attrType)) {
564 if (!mlir::isa<cir::VoidType>(opType))
566 return op->emitOpError(
"undef expects non-void type");
569 if (mlir::isa<cir::BoolAttr>(attrType)) {
570 if (!mlir::isa<cir::BoolType>(opType))
571 return op->emitOpError(
"result type (")
572 << opType <<
") must be '!cir.bool' for '" << attrType <<
"'";
576 if (mlir::isa<cir::IntAttr, cir::FPAttr>(attrType)) {
577 auto at = cast<TypedAttr>(attrType);
578 if (at.getType() != opType) {
579 return op->emitOpError(
"result type (")
580 << opType <<
") does not match value type (" << at.getType()
586 if (mlir::isa<cir::BlockAddrInfoAttr, cir::ConstArrayAttr,
587 cir::ConstVectorAttr, cir::ConstComplexAttr,
588 cir::ConstRecordAttr, cir::GlobalViewAttr, cir::PoisonAttr,
589 cir::TypeInfoAttr, cir::VTableAttr>(attrType))
592 assert(isa<TypedAttr>(attrType) &&
"What else could we be looking at here?");
593 return op->emitOpError(
"global with type ")
594 << cast<TypedAttr>(attrType).getType() <<
" not yet supported";
597LogicalResult cir::ConstantOp::verify() {
604OpFoldResult cir::ConstantOp::fold(FoldAdaptor ) {
612LogicalResult cir::CastOp::verify() {
613 mlir::Type resType =
getType();
614 mlir::Type srcType = getSrc().getType();
618 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
619 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
620 if (srcPtrTy && resPtrTy && (
getKind() != cir::CastKind::address_space))
621 if (srcPtrTy.getAddrSpace() != resPtrTy.getAddrSpace()) {
622 return emitOpError() <<
"result type address space does not match the "
623 "address space of the operand";
627 auto srcVTy = mlir::dyn_cast<cir::VectorType>(srcType);
628 auto resVTy = mlir::dyn_cast<cir::VectorType>(resType);
629 if (srcVTy && resVTy) {
630 if ((
kind == cir::CastKind::int_to_float ||
631 kind == cir::CastKind::float_to_int) &&
632 srcVTy.getSize() != resVTy.getSize()) {
634 <<
"vector float-to-int and int-to-float casts require "
635 "source and destination vectors to have the same number of "
640 srcType = srcVTy.getElementType();
641 resType = resVTy.getElementType();
645 case cir::CastKind::int_to_bool: {
646 if (!mlir::isa<cir::BoolType>(resType))
647 return emitOpError() <<
"requires !cir.bool type for result";
648 if (!mlir::isa<cir::IntType>(srcType))
649 return emitOpError() <<
"requires !cir.int type for source";
652 case cir::CastKind::ptr_to_bool: {
653 if (!mlir::isa<cir::BoolType>(resType))
654 return emitOpError() <<
"requires !cir.bool type for result";
655 if (!mlir::isa<cir::PointerType>(srcType))
656 return emitOpError() <<
"requires !cir.ptr type for source";
659 case cir::CastKind::integral: {
660 if (!mlir::isa<cir::IntType>(resType))
661 return emitOpError() <<
"requires !cir.int type for result";
662 if (!mlir::isa<cir::IntType>(srcType))
663 return emitOpError() <<
"requires !cir.int type for source";
666 case cir::CastKind::array_to_ptrdecay: {
667 const auto arrayPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
668 const auto flatPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
669 if (!arrayPtrTy || !flatPtrTy)
670 return emitOpError() <<
"requires !cir.ptr type for source and result";
675 case cir::CastKind::bitcast: {
677 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
678 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
680 if (srcPtrTy && resPtrTy) {
686 case cir::CastKind::floating: {
687 if (!mlir::isa<cir::FPTypeInterface>(srcType) ||
688 !mlir::isa<cir::FPTypeInterface>(resType))
689 return emitOpError() <<
"requires !cir.float type for source and result";
692 case cir::CastKind::float_to_int: {
693 if (!mlir::isa<cir::FPTypeInterface>(srcType))
694 return emitOpError() <<
"requires !cir.float type for source";
695 if (!mlir::dyn_cast<cir::IntType>(resType))
696 return emitOpError() <<
"requires !cir.int type for result";
699 case cir::CastKind::int_to_ptr: {
700 if (!mlir::dyn_cast<cir::IntType>(srcType))
701 return emitOpError() <<
"requires !cir.int type for source";
702 if (!mlir::dyn_cast<cir::PointerType>(resType))
703 return emitOpError() <<
"requires !cir.ptr type for result";
706 case cir::CastKind::ptr_to_int: {
707 if (!mlir::dyn_cast<cir::PointerType>(srcType))
708 return emitOpError() <<
"requires !cir.ptr type for source";
709 if (!mlir::dyn_cast<cir::IntType>(resType))
710 return emitOpError() <<
"requires !cir.int type for result";
713 case cir::CastKind::float_to_bool: {
714 if (!mlir::isa<cir::FPTypeInterface>(srcType))
715 return emitOpError() <<
"requires !cir.float type for source";
716 if (!mlir::isa<cir::BoolType>(resType))
717 return emitOpError() <<
"requires !cir.bool type for result";
720 case cir::CastKind::bool_to_int: {
721 if (!mlir::isa<cir::BoolType>(srcType))
722 return emitOpError() <<
"requires !cir.bool type for source";
723 if (!mlir::isa<cir::IntType>(resType))
724 return emitOpError() <<
"requires !cir.int type for result";
727 case cir::CastKind::int_to_float: {
728 if (!mlir::isa<cir::IntType>(srcType))
729 return emitOpError() <<
"requires !cir.int type for source";
730 if (!mlir::isa<cir::FPTypeInterface>(resType))
731 return emitOpError() <<
"requires !cir.float type for result";
734 case cir::CastKind::bool_to_float: {
735 if (!mlir::isa<cir::BoolType>(srcType))
736 return emitOpError() <<
"requires !cir.bool type for source";
737 if (!mlir::isa<cir::FPTypeInterface>(resType))
738 return emitOpError() <<
"requires !cir.float type for result";
741 case cir::CastKind::address_space: {
742 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
743 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
744 if (!srcPtrTy || !resPtrTy)
745 return emitOpError() <<
"requires !cir.ptr type for source and result";
746 if (srcPtrTy.getPointee() != resPtrTy.getPointee())
747 return emitOpError() <<
"requires two types differ in addrspace only";
750 case cir::CastKind::float_to_complex: {
751 if (!mlir::isa<cir::FPTypeInterface>(srcType))
752 return emitOpError() <<
"requires !cir.float type for source";
753 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
755 return emitOpError() <<
"requires !cir.complex type for result";
756 if (srcType != resComplexTy.getElementType())
757 return emitOpError() <<
"requires source type match result element type";
760 case cir::CastKind::int_to_complex: {
761 if (!mlir::isa<cir::IntType>(srcType))
762 return emitOpError() <<
"requires !cir.int type for source";
763 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
765 return emitOpError() <<
"requires !cir.complex type for result";
766 if (srcType != resComplexTy.getElementType())
767 return emitOpError() <<
"requires source type match result element type";
770 case cir::CastKind::float_complex_to_real: {
771 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
773 return emitOpError() <<
"requires !cir.complex type for source";
774 if (!mlir::isa<cir::FPTypeInterface>(resType))
775 return emitOpError() <<
"requires !cir.float type for result";
776 if (srcComplexTy.getElementType() != resType)
777 return emitOpError() <<
"requires source element type match result type";
780 case cir::CastKind::int_complex_to_real: {
781 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
783 return emitOpError() <<
"requires !cir.complex type for source";
784 if (!mlir::isa<cir::IntType>(resType))
785 return emitOpError() <<
"requires !cir.int type for result";
786 if (srcComplexTy.getElementType() != resType)
787 return emitOpError() <<
"requires source element type match result type";
790 case cir::CastKind::float_complex_to_bool: {
791 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
792 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
794 <<
"requires floating point !cir.complex type for source";
795 if (!mlir::isa<cir::BoolType>(resType))
796 return emitOpError() <<
"requires !cir.bool type for result";
799 case cir::CastKind::int_complex_to_bool: {
800 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
801 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
803 <<
"requires floating point !cir.complex type for source";
804 if (!mlir::isa<cir::BoolType>(resType))
805 return emitOpError() <<
"requires !cir.bool type for result";
808 case cir::CastKind::float_complex: {
809 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
810 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
812 <<
"requires floating point !cir.complex type for source";
813 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
814 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
816 <<
"requires floating point !cir.complex type for result";
819 case cir::CastKind::float_complex_to_int_complex: {
820 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
821 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
823 <<
"requires floating point !cir.complex type for source";
824 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
825 if (!resComplexTy || !resComplexTy.isIntegerComplex())
826 return emitOpError() <<
"requires integer !cir.complex type for result";
829 case cir::CastKind::int_complex: {
830 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
831 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
832 return emitOpError() <<
"requires integer !cir.complex type for source";
833 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
834 if (!resComplexTy || !resComplexTy.isIntegerComplex())
835 return emitOpError() <<
"requires integer !cir.complex type for result";
838 case cir::CastKind::int_complex_to_float_complex: {
839 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
840 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
841 return emitOpError() <<
"requires integer !cir.complex type for source";
842 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
843 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
845 <<
"requires floating point !cir.complex type for result";
848 case cir::CastKind::member_ptr_to_bool: {
849 if (!mlir::isa<cir::DataMemberType, cir::MethodType>(srcType))
851 <<
"requires !cir.data_member or !cir.method type for source";
852 if (!mlir::isa<cir::BoolType>(resType))
853 return emitOpError() <<
"requires !cir.bool type for result";
857 llvm_unreachable(
"Unknown CastOp kind?");
861 auto kind = op.getKind();
862 return kind == cir::CastKind::bool_to_int ||
863 kind == cir::CastKind::int_to_bool ||
kind == cir::CastKind::integral;
867 const auto ptrTy = mlir::dyn_cast<cir::PointerType>(ty);
868 return ptrTy && mlir::isa<cir::FuncType>(ptrTy.getPointee());
872 cir::CastOp head = op, tail = op;
878 op = head.getSrc().getDefiningOp<cir::CastOp>();
884 if (head.getKind() == cir::CastKind::bool_to_int &&
885 tail.getKind() == cir::CastKind::int_to_bool)
886 return head.getSrc();
891 if (head.getKind() == cir::CastKind::int_to_bool &&
892 tail.getKind() == cir::CastKind::int_to_bool)
893 return head.getResult();
901 if (tail.getKind() == cir::CastKind::bitcast) {
902 auto *inner = tail.getSrc().getDefiningOp();
904 auto innerCast = mlir::dyn_cast<cir::CastOp>(inner);
905 if (innerCast && innerCast.getKind() == cir::CastKind::bitcast &&
906 innerCast.getSrc().getType() == tail.getType() &&
907 innerCast.getType() == tail.getSrc().getType()) {
908 return innerCast.getSrc();
916OpFoldResult cir::CastOp::fold(FoldAdaptor adaptor) {
917 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getSrc())) {
919 return cir::PoisonAttr::get(getContext(),
getType());
924 case cir::CastKind::integral: {
926 auto foldOrder = getSrc().getDefiningOp()->fold(foldResults);
927 if (foldOrder.succeeded() && mlir::isa<mlir::Attribute>(foldResults[0]))
928 return mlir::cast<mlir::Attribute>(foldResults[0]);
931 case cir::CastKind::bitcast:
932 case cir::CastKind::address_space:
933 case cir::CastKind::float_complex:
934 case cir::CastKind::int_complex: {
948 if (
auto srcConst = getSrc().getDefiningOp<cir::ConstantOp>()) {
950 case cir::CastKind::integral: {
951 mlir::Type srcTy = getSrc().getType();
953 assert(mlir::isa<cir::VectorType>(srcTy) ==
954 mlir::isa<cir::VectorType>(
getType()));
955 if (mlir::isa<cir::VectorType>(srcTy))
958 auto srcIntTy = mlir::cast<cir::IntType>(srcTy);
959 auto dstIntTy = mlir::cast<cir::IntType>(
getType());
962 ? srcConst.getIntValue().sextOrTrunc(dstIntTy.getWidth())
963 : srcConst.getIntValue().zextOrTrunc(dstIntTy.getWidth());
964 return cir::IntAttr::get(dstIntTy, newVal);
977LogicalResult cir::BuiltinIntCastOp::verify() {
978 mlir::Type srcType = getSrc().getType();
979 mlir::Type resType =
getType();
981 auto srcCirInt = mlir::dyn_cast<cir::IntType>(srcType);
982 auto resCirInt = mlir::dyn_cast<cir::IntType>(resType);
986 if (
static_cast<bool>(srcCirInt) ==
static_cast<bool>(resCirInt))
988 <<
"requires exactly one '!cir.int' operand or result; the other "
989 "must be a builtin integer or 'index' type";
991 mlir::Type
builtinType = srcCirInt ? resType : srcType;
992 if (!mlir::isa<mlir::IntegerType, mlir::IndexType>(builtinType))
993 return emitOpError() <<
"requires a builtin integer or 'index' type on the "
998 if (
auto builtinInt = mlir::dyn_cast<mlir::IntegerType>(builtinType)) {
999 cir::IntType cirInt = srcCirInt ? srcCirInt : resCirInt;
1000 if (cirInt.getWidth() != builtinInt.getWidth())
1001 return emitOpError()
1002 <<
"requires the CIR and builtin integer types to have the same "
1003 "width; use 'cir.cast' for width conversions";
1009OpFoldResult cir::BuiltinIntCastOp::fold(FoldAdaptor adaptor) {
1012 if (
auto inner = getSrc().getDefiningOp<cir::BuiltinIntCastOp>())
1013 if (inner.getSrc().getType() ==
getType())
1014 return inner.getSrc();
1022mlir::OperandRange cir::CallOp::getArgOperands() {
1024 return getArgs().drop_front(1);
1028mlir::MutableOperandRange cir::CallOp::getArgOperandsMutable() {
1029 mlir::MutableOperandRange args = getArgsMutable();
1031 return args.slice(1, args.size() - 1);
1035mlir::Value cir::CallOp::getIndirectCall() {
1036 assert(isIndirect());
1037 return getOperand(0);
1041Value cir::CallOp::getArgOperand(
unsigned i) {
1044 return getOperand(i);
1048unsigned cir::CallOp::getNumArgOperands() {
1050 return this->getOperation()->getNumOperands() - 1;
1051 return this->getOperation()->getNumOperands();
1054static mlir::ParseResult
1056 mlir::OperationState &result) {
1057 mlir::Block *normalDestSuccessor;
1058 if (parser.parseSuccessor(normalDestSuccessor))
1059 return mlir::failure();
1061 if (parser.parseComma())
1062 return mlir::failure();
1064 mlir::Block *unwindDestSuccessor;
1065 if (parser.parseSuccessor(unwindDestSuccessor))
1066 return mlir::failure();
1068 result.addSuccessors(normalDestSuccessor);
1069 result.addSuccessors(unwindDestSuccessor);
1070 return mlir::success();
1074 mlir::OperationState &result,
1075 bool hasDestinationBlocks =
false) {
1078 mlir::FlatSymbolRefAttr calleeAttr;
1082 .parseOptionalAttribute(calleeAttr, CIRDialect::getCalleeAttrName(),
1085 OpAsmParser::UnresolvedOperand indirectVal;
1087 if (parser.parseOperand(indirectVal).failed())
1089 ops.push_back(indirectVal);
1092 if (parser.parseLParen())
1093 return mlir::failure();
1095 opsLoc = parser.getCurrentLocation();
1096 if (parser.parseOperandList(ops))
1097 return mlir::failure();
1098 if (parser.parseRParen())
1099 return mlir::failure();
1101 if (hasDestinationBlocks &&
1103 return ::mlir::failure();
1106 if (parser.parseOptionalKeyword(
"musttail").succeeded())
1107 result.addAttribute(CIRDialect::getMustTailAttrName(),
1108 mlir::UnitAttr::get(parser.getContext()));
1110 if (parser.parseOptionalKeyword(
"nothrow").succeeded())
1111 result.addAttribute(CIRDialect::getNoThrowAttrName(),
1112 mlir::UnitAttr::get(parser.getContext()));
1114 if (parser.parseOptionalKeyword(
"side_effect").succeeded()) {
1115 if (parser.parseLParen().failed())
1117 cir::SideEffect sideEffect;
1120 if (parser.parseRParen().failed())
1122 auto attr = cir::SideEffectAttr::get(parser.getContext(), sideEffect);
1123 result.addAttribute(CIRDialect::getSideEffectAttrName(), attr);
1126 if (parser.parseOptionalAttrDict(result.attributes))
1127 return ::mlir::failure();
1129 if (parser.parseColon())
1130 return ::mlir::failure();
1136 if (call_interface_impl::parseFunctionSignature(parser, argTypes, argAttrs,
1137 resultTypes, resultAttrs))
1138 return mlir::failure();
1140 if (resultTypes.size() > 1 || resultAttrs.size() > 1)
1141 return parser.emitError(
1142 parser.getCurrentLocation(),
1143 "functions with multiple return types are not supported");
1145 result.addTypes(resultTypes);
1147 if (parser.resolveOperands(ops, argTypes, opsLoc, result.operands))
1148 return mlir::failure();
1150 if (!resultAttrs.empty() && resultAttrs[0])
1151 result.addAttribute(
1152 CIRDialect::getResAttrsAttrName(),
1153 mlir::ArrayAttr::get(parser.getContext(), {resultAttrs[0]}));
1158 bool argAttrsEmpty =
true;
1160 llvm::transform(argAttrs, std::back_inserter(convertedArgAttrs),
1161 [&](DictionaryAttr da) -> mlir::Attribute {
1163 argAttrsEmpty =
false;
1167 if (!argAttrsEmpty) {
1172 argAttrsRef = argAttrsRef.drop_front();
1174 result.addAttribute(CIRDialect::getArgAttrsAttrName(),
1175 mlir::ArrayAttr::get(parser.getContext(), argAttrsRef));
1178 return mlir::success();
1183 mlir::Value indirectCallee, mlir::OpAsmPrinter &printer,
1184 bool isNothrow, cir::SideEffect sideEffect, ArrayAttr argAttrs,
1185 ArrayAttr resAttrs, mlir::Block *normalDest =
nullptr,
1186 mlir::Block *unwindDest =
nullptr) {
1189 auto callLikeOp = mlir::cast<cir::CIRCallOpInterface>(op);
1190 auto ops = callLikeOp.getArgOperands();
1194 printer.printAttributeWithoutType(calleeSym);
1197 assert(indirectCallee);
1198 printer << indirectCallee;
1201 printer <<
"(" << ops <<
")";
1204 assert(unwindDest &&
"expected two successors");
1205 auto tryCall = cast<cir::TryCallOp>(op);
1206 printer <<
' ' << tryCall.getNormalDest();
1209 printer << tryCall.getUnwindDest();
1212 if (op->hasAttr(CIRDialect::getMustTailAttrName()))
1213 printer <<
" musttail";
1216 printer <<
" nothrow";
1218 if (sideEffect != cir::SideEffect::All) {
1219 printer <<
" side_effect(";
1220 printer << stringifySideEffect(sideEffect);
1225 CIRDialect::getCalleeAttrName(),
1226 CIRDialect::getMustTailAttrName(),
1227 CIRDialect::getNoThrowAttrName(),
1228 CIRDialect::getSideEffectAttrName(),
1229 CIRDialect::getOperandSegmentSizesAttrName(),
1230 llvm::StringRef(
"res_attrs"),
1231 llvm::StringRef(
"arg_attrs")};
1232 printer.printOptionalAttrDict(op->getAttrs(), elidedAttrs);
1234 if (calleeSym || !argAttrs) {
1235 call_interface_impl::printFunctionSignature(
1236 printer, op->getOperands().getTypes(), argAttrs,
1237 false, op->getResultTypes(), resAttrs);
1245 shimmedArgAttrs.push_back(mlir::DictionaryAttr::get(op->getContext(), {}));
1246 shimmedArgAttrs.append(argAttrs.begin(), argAttrs.end());
1247 call_interface_impl::printFunctionSignature(
1248 printer, op->getOperands().getTypes(),
1249 mlir::ArrayAttr::get(op->getContext(), shimmedArgAttrs),
1250 false, op->getResultTypes(), resAttrs);
1254mlir::ParseResult cir::CallOp::parse(mlir::OpAsmParser &parser,
1255 mlir::OperationState &result) {
1259void cir::CallOp::print(mlir::OpAsmPrinter &p) {
1260 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() :
nullptr;
1261 cir::SideEffect sideEffect = getSideEffect();
1262 printCallCommon(*
this, getCalleeAttr(), indirectCallee, p, getNothrow(),
1263 sideEffect, getArgAttrsAttr(), getResAttrsAttr());
1268 SymbolTableCollection &symbolTable) {
1270 op->getAttrOfType<FlatSymbolRefAttr>(CIRDialect::getCalleeAttrName());
1273 return mlir::success();
1276 auto fn = symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(op, fnAttr);
1278 return op->emitOpError() <<
"'" << fnAttr.getValue()
1279 <<
"' does not reference a valid function";
1281 auto callIf = dyn_cast<cir::CIRCallOpInterface>(op);
1282 assert(callIf &&
"expected CIR call interface to be always available");
1286 auto fnType = fn.getFunctionType();
1287 if (!fn.getNoProto()) {
1288 unsigned numCallOperands = callIf.getNumArgOperands();
1289 unsigned numFnOpOperands = fnType.getNumInputs();
1291 if (!fnType.isVarArg() && numCallOperands != numFnOpOperands)
1292 return op->emitOpError(
"incorrect number of operands for callee");
1293 if (fnType.isVarArg() && numCallOperands < numFnOpOperands)
1294 return op->emitOpError(
"too few operands for callee");
1296 for (
unsigned i = 0, e = numFnOpOperands; i != e; ++i)
1297 if (callIf.getArgOperand(i).getType() != fnType.getInput(i))
1298 return op->emitOpError(
"operand type mismatch: expected operand type ")
1299 << fnType.getInput(i) <<
", but provided "
1300 << op->getOperand(i).getType() <<
" for operand number " << i;
1306 if (fnType.hasVoidReturn() && op->getNumResults() != 0)
1307 return op->emitOpError(
"callee returns void but call has results");
1310 if (!fnType.hasVoidReturn() && op->getNumResults() != 1)
1311 return op->emitOpError(
"incorrect number of results for callee");
1314 if (!fnType.hasVoidReturn() &&
1315 op->getResultTypes().front() != fnType.getReturnType()) {
1316 return op->emitOpError(
"result type mismatch: expected ")
1317 << fnType.getReturnType() <<
", but provided "
1318 << op->getResult(0).getType();
1321 return mlir::success();
1325cir::CallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1333mlir::OperandRange cir::TryCallOp::getArgOperands() {
1335 return getArgs().drop_front(1);
1339mlir::MutableOperandRange cir::TryCallOp::getArgOperandsMutable() {
1340 mlir::MutableOperandRange args = getArgsMutable();
1342 return args.slice(1, args.size() - 1);
1346mlir::Value cir::TryCallOp::getIndirectCall() {
1347 assert(isIndirect());
1348 return getOperand(0);
1352Value cir::TryCallOp::getArgOperand(
unsigned i) {
1355 return getOperand(i);
1359unsigned cir::TryCallOp::getNumArgOperands() {
1361 return this->getOperation()->getNumOperands() - 1;
1362 return this->getOperation()->getNumOperands();
1366cir::TryCallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1370mlir::ParseResult cir::TryCallOp::parse(mlir::OpAsmParser &parser,
1371 mlir::OperationState &result) {
1375void cir::TryCallOp::print(::mlir::OpAsmPrinter &p) {
1376 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() :
nullptr;
1377 cir::SideEffect sideEffect = getSideEffect();
1378 printCallCommon(*
this, getCalleeAttr(), indirectCallee, p, getNothrow(),
1379 sideEffect, getArgAttrsAttr(), getResAttrsAttr(),
1380 getNormalDest(), getUnwindDest());
1388 cir::FuncOp function) {
1390 if (op.getNumOperands() > 1)
1391 return op.emitOpError() <<
"expects at most 1 return operand";
1394 auto expectedTy = function.getFunctionType().getReturnType();
1396 (op.getNumOperands() == 0 ? cir::VoidType::get(op.getContext())
1397 : op.getOperand(0).getType());
1398 if (actualTy != expectedTy)
1399 return op.emitOpError() <<
"returns " << actualTy
1400 <<
" but enclosing function returns " << expectedTy;
1402 return mlir::success();
1405mlir::LogicalResult cir::ReturnOp::verify() {
1408 auto *fnOp = getOperation()->getParentOp();
1409 while (!isa<cir::FuncOp>(fnOp))
1410 fnOp = fnOp->getParentOp();
1423ParseResult cir::IfOp::parse(OpAsmParser &parser, OperationState &result) {
1425 result.regions.reserve(2);
1426 Region *thenRegion = result.addRegion();
1427 Region *elseRegion = result.addRegion();
1429 mlir::Builder &builder = parser.getBuilder();
1430 OpAsmParser::UnresolvedOperand cond;
1431 Type boolType = cir::BoolType::get(builder.getContext());
1433 if (parser.parseOperand(cond) ||
1434 parser.resolveOperand(cond, boolType, result.operands))
1438 mlir::SMLoc parseThenLoc = parser.getCurrentLocation();
1439 if (parser.parseRegion(*thenRegion, {}, {}))
1446 if (!parser.parseOptionalKeyword(
"else")) {
1447 mlir::SMLoc parseElseLoc = parser.getCurrentLocation();
1448 if (parser.parseRegion(*elseRegion, {}, {}))
1455 if (parser.parseOptionalAttrDict(result.attributes))
1460void cir::IfOp::print(OpAsmPrinter &p) {
1461 p <<
" " << getCondition() <<
" ";
1462 mlir::Region &thenRegion = this->getThenRegion();
1463 p.printRegion(thenRegion,
1468 mlir::Region &elseRegion = this->getElseRegion();
1469 if (!elseRegion.empty()) {
1471 p.printRegion(elseRegion,
1476 p.printOptionalAttrDict(getOperation()->getAttrs());
1482 cir::YieldOp::create(builder, loc);
1490void cir::IfOp::getSuccessorRegions(mlir::RegionBranchPoint point,
1491 SmallVectorImpl<RegionSuccessor> ®ions) {
1493 if (!point.isParent()) {
1494 regions.emplace_back(getOperation());
1499 Region *elseRegion = &this->getElseRegion();
1500 if (elseRegion->empty())
1501 elseRegion =
nullptr;
1504 regions.push_back(RegionSuccessor(&getThenRegion()));
1506 regions.push_back(RegionSuccessor(elseRegion));
1508 regions.emplace_back(getOperation());
1511mlir::ValueRange cir::IfOp::getSuccessorInputs(RegionSuccessor successor) {
1512 return successor.isOperation() ? ValueRange(getOperation()->getResults())
1516void cir::IfOp::build(OpBuilder &builder, OperationState &result,
Value cond,
1519 assert(thenBuilder &&
"the builder callback for 'then' must be present");
1520 result.addOperands(cond);
1522 OpBuilder::InsertionGuard guard(builder);
1523 Region *thenRegion = result.addRegion();
1524 builder.createBlock(thenRegion);
1525 thenBuilder(builder, result.location);
1527 Region *elseRegion = result.addRegion();
1528 if (!withElseRegion)
1531 builder.createBlock(elseRegion);
1532 elseBuilder(builder, result.location);
1544void cir::ScopeOp::getSuccessorRegions(
1545 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1547 if (!point.isParent()) {
1548 regions.emplace_back(getOperation());
1553 regions.push_back(RegionSuccessor(&getScopeRegion()));
1556mlir::ValueRange cir::ScopeOp::getSuccessorInputs(RegionSuccessor successor) {
1557 return successor.isOperation() ? ValueRange(getOperation()->getResults())
1561void cir::ScopeOp::build(
1562 OpBuilder &builder, OperationState &result,
1563 function_ref<
void(OpBuilder &, Type &, Location)> scopeBuilder) {
1564 assert(scopeBuilder &&
"the builder callback for 'then' must be present");
1566 OpBuilder::InsertionGuard guard(builder);
1567 Region *scopeRegion = result.addRegion();
1568 builder.createBlock(scopeRegion);
1572 scopeBuilder(builder, yieldTy, result.location);
1575 result.addTypes(TypeRange{yieldTy});
1578void cir::ScopeOp::build(
1579 OpBuilder &builder, OperationState &result,
1580 function_ref<
void(OpBuilder &, Location)> scopeBuilder) {
1581 assert(scopeBuilder &&
"the builder callback for 'then' must be present");
1582 OpBuilder::InsertionGuard guard(builder);
1583 Region *scopeRegion = result.addRegion();
1584 builder.createBlock(scopeRegion);
1586 scopeBuilder(builder, result.location);
1589LogicalResult cir::ScopeOp::verify() {
1591 return emitOpError() <<
"cir.scope must not be empty since it should "
1592 "include at least an implicit cir.yield ";
1595 mlir::Block &lastBlock =
getRegion().back();
1596 if (lastBlock.empty() || !lastBlock.mightHaveTerminator() ||
1597 !lastBlock.getTerminator()->hasTrait<OpTrait::IsTerminator>())
1598 return emitOpError() <<
"last block of cir.scope must be terminated";
1602LogicalResult cir::ScopeOp::fold(FoldAdaptor ,
1603 SmallVectorImpl<OpFoldResult> &results) {
1608 if (block.getOperations().size() != 1)
1611 auto yield = dyn_cast<cir::YieldOp>(block.front());
1616 if (getNumResults() != 1 || yield.getNumOperands() != 1)
1619 results.push_back(yield.getOperand(0));
1627void cir::CleanupScopeOp::getSuccessorRegions(
1628 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1629 if (!point.isParent()) {
1630 regions.emplace_back(getOperation());
1635 regions.push_back(RegionSuccessor(&getBodyRegion()));
1636 regions.push_back(RegionSuccessor(&getCleanupRegion()));
1640cir::CleanupScopeOp::getSuccessorInputs(RegionSuccessor successor) {
1641 return ValueRange();
1644LogicalResult cir::CleanupScopeOp::canonicalize(CleanupScopeOp op,
1645 PatternRewriter &rewriter) {
1646 auto isRegionTrivial = [](Region ®ion) {
1647 assert(!region.empty() &&
"CleanupScopeOp regions must not be empty");
1648 if (!region.hasOneBlock())
1650 Block &block = llvm::getSingleElement(region);
1651 return llvm::hasSingleElement(block) &&
1652 isa<cir::YieldOp>(llvm::getSingleElement(block));
1655 Region &body = op.getBodyRegion();
1656 Region &
cleanup = op.getCleanupRegion();
1660 if (op.getCleanupKind() == CleanupKind::EH && isRegionTrivial(body)) {
1661 rewriter.eraseOp(op);
1667 if (!isRegionTrivial(
cleanup) || !body.hasOneBlock())
1670 Block &bodyBlock = body.front();
1671 if (!isa<cir::YieldOp>(bodyBlock.getTerminator()))
1674 Operation *yield = bodyBlock.getTerminator();
1675 rewriter.inlineBlockBefore(&bodyBlock, op);
1676 rewriter.eraseOp(yield);
1677 rewriter.eraseOp(op);
1681void cir::CleanupScopeOp::build(
1682 OpBuilder &builder, OperationState &result, CleanupKind cleanupKind,
1683 function_ref<
void(OpBuilder &, Location)> bodyBuilder,
1684 function_ref<
void(OpBuilder &, Location)> cleanupBuilder) {
1685 result.addAttribute(getCleanupKindAttrName(result.name),
1686 CleanupKindAttr::get(builder.getContext(), cleanupKind));
1688 OpBuilder::InsertionGuard guard(builder);
1691 Region *bodyRegion = result.addRegion();
1692 builder.createBlock(bodyRegion);
1694 bodyBuilder(builder, result.location);
1697 Region *cleanupRegion = result.addRegion();
1698 builder.createBlock(cleanupRegion);
1700 cleanupBuilder(builder, result.location);
1715LogicalResult cir::BrOp::canonicalize(BrOp op, PatternRewriter &rewriter) {
1716 Block *src = op->getBlock();
1717 Block *dst = op.getDest();
1724 if (src->getNumSuccessors() != 1 || dst->getSinglePredecessor() != src)
1729 if (isa<cir::LabelOp, cir::IndirectBrOp>(dst->front()))
1732 auto operands = op.getDestOperands();
1733 rewriter.eraseOp(op);
1734 rewriter.mergeBlocks(dst, src, operands);
1738mlir::SuccessorOperands cir::BrOp::getSuccessorOperands(
unsigned index) {
1739 assert(index == 0 &&
"invalid successor index");
1740 return mlir::SuccessorOperands(getDestOperandsMutable());
1751mlir::SuccessorOperands
1752cir::IndirectBrOp::getSuccessorOperands(
unsigned index) {
1753 assert(index < getNumSuccessors() &&
"invalid successor index");
1754 return mlir::SuccessorOperands(getSuccOperandsMutable()[index]);
1758 OpAsmParser &parser, Type &flagType,
1759 SmallVectorImpl<Block *> &succOperandBlocks,
1762 if (failed(parser.parseCommaSeparatedList(
1763 OpAsmParser::Delimiter::Square,
1765 Block *destination = nullptr;
1766 SmallVector<OpAsmParser::UnresolvedOperand> operands;
1767 SmallVector<Type> operandTypes;
1769 if (parser.parseSuccessor(destination).failed())
1772 if (succeeded(parser.parseOptionalLParen())) {
1773 if (failed(parser.parseOperandList(
1774 operands, OpAsmParser::Delimiter::None)) ||
1775 failed(parser.parseColonTypeList(operandTypes)) ||
1776 failed(parser.parseRParen()))
1779 succOperandBlocks.push_back(destination);
1780 succOperands.emplace_back(operands);
1781 succOperandsTypes.emplace_back(operandTypes);
1784 "successor blocks")))
1790 Type flagType, SuccessorRange succs,
1791 OperandRangeRange succOperands,
1792 const TypeRangeRange &succOperandsTypes) {
1795 llvm::zip(succs, succOperands),
1798 p.printSuccessorAndUseList(std::get<0>(i), std::get<1>(i));
1801 if (!succOperands.empty())
1810mlir::SuccessorOperands cir::BrCondOp::getSuccessorOperands(
unsigned index) {
1811 assert(index < getNumSuccessors() &&
"invalid successor index");
1812 return SuccessorOperands(index == 0 ? getDestOperandsTrueMutable()
1813 : getDestOperandsFalseMutable());
1817 if (IntegerAttr condAttr = dyn_cast_if_present<IntegerAttr>(operands.front()))
1818 return condAttr.getValue().isOne() ? getDestTrue() : getDestFalse();
1826void cir::CaseOp::getSuccessorRegions(
1827 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1828 if (!point.isParent()) {
1829 regions.emplace_back(getOperation());
1832 regions.push_back(RegionSuccessor(&getCaseRegion()));
1835mlir::ValueRange cir::CaseOp::getSuccessorInputs(RegionSuccessor successor) {
1836 return successor.isOperation() ? ValueRange(getOperation()->getResults())
1840void cir::CaseOp::build(OpBuilder &builder, OperationState &result,
1841 ArrayAttr value, CaseOpKind
kind,
1842 OpBuilder::InsertPoint &insertPoint) {
1843 OpBuilder::InsertionGuard guardSwitch(builder);
1844 result.addAttribute(
"value", value);
1845 result.getOrAddProperties<Properties>().
kind =
1846 cir::CaseOpKindAttr::get(builder.getContext(),
kind);
1847 Region *caseRegion = result.addRegion();
1848 builder.createBlock(caseRegion);
1850 insertPoint = builder.saveInsertionPoint();
1857void cir::SwitchOp::getSuccessorRegions(
1858 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ion) {
1859 if (!point.isParent()) {
1860 region.emplace_back(getOperation());
1864 region.push_back(RegionSuccessor(&getBody()));
1867mlir::ValueRange cir::SwitchOp::getSuccessorInputs(RegionSuccessor successor) {
1868 return successor.isOperation() ? ValueRange(getOperation()->getResults())
1872void cir::SwitchOp::build(OpBuilder &builder, OperationState &result,
1874 assert(switchBuilder &&
"the builder callback for regions must be present");
1875 OpBuilder::InsertionGuard guardSwitch(builder);
1876 Region *switchRegion = result.addRegion();
1877 builder.createBlock(switchRegion);
1878 result.addOperands({cond});
1879 switchBuilder(builder, result.location, result);
1883 walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
1885 if (isa<cir::SwitchOp>(op) && op != *
this)
1886 return WalkResult::skip();
1888 if (
auto caseOp = dyn_cast<cir::CaseOp>(op))
1889 cases.push_back(caseOp);
1891 return WalkResult::advance();
1896 collectCases(cases);
1898 if (getBody().empty())
1901 if (!isa<YieldOp>(getBody().front().back()))
1904 if (!llvm::all_of(getBody().front(),
1905 [](Operation &op) {
return isa<CaseOp, YieldOp>(op); }))
1908 return llvm::all_of(cases, [
this](CaseOp op) {
1909 return op->getParentOfType<SwitchOp>() == *
this;
1917void cir::SwitchFlatOp::build(OpBuilder &builder, OperationState &result,
1918 Value value, Block *defaultDestination,
1919 ValueRange defaultOperands,
1921 BlockRange caseDestinations,
1924 std::vector<mlir::Attribute> caseValuesAttrs;
1925 for (
const APInt &val : caseValues)
1926 caseValuesAttrs.push_back(cir::IntAttr::get(value.getType(), val));
1927 mlir::ArrayAttr attrs = ArrayAttr::get(builder.getContext(), caseValuesAttrs);
1929 build(builder, result, value, defaultOperands, caseOperands, attrs,
1930 defaultDestination, caseDestinations);
1936 OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues,
1937 SmallVectorImpl<Block *> &caseDestinations,
1941 if (failed(parser.parseLSquare()))
1943 if (succeeded(parser.parseOptionalRSquare()))
1947 auto parseCase = [&]() {
1949 if (failed(parser.parseInteger(value)))
1952 values.push_back(cir::IntAttr::get(flagType, value));
1957 if (parser.parseColon() || parser.parseSuccessor(destination))
1959 if (!parser.parseOptionalLParen()) {
1960 if (parser.parseOperandList(operands, OpAsmParser::Delimiter::None,
1962 parser.parseColonTypeList(operandTypes) || parser.parseRParen())
1965 caseDestinations.push_back(destination);
1966 caseOperands.emplace_back(operands);
1967 caseOperandTypes.emplace_back(operandTypes);
1970 if (failed(parser.parseCommaSeparatedList(parseCase)))
1973 caseValues = ArrayAttr::get(flagType.getContext(), values);
1975 return parser.parseRSquare();
1979 Type flagType, mlir::ArrayAttr caseValues,
1980 SuccessorRange caseDestinations,
1981 OperandRangeRange caseOperands,
1982 const TypeRangeRange &caseOperandTypes) {
1992 llvm::zip(caseValues, caseDestinations),
1995 mlir::Attribute a = std::get<0>(i);
1996 p << mlir::cast<cir::IntAttr>(a).getValue();
1998 p.printSuccessorAndUseList(std::get<1>(i), caseOperands[index++]);
2013 mlir::Attribute &valueAttr) {
2015 return parser.parseAttribute(valueAttr,
"value", attr);
2019 p.printAttribute(value);
2022mlir::LogicalResult cir::GlobalOp::verify() {
2025 if (getInitialValue().has_value()) {
2031 if ((getStaticLocalGuard().has_value()) &&
2032 (!getCtorRegion().empty() || !getDtorRegion().empty()))
2034 "Cannot have a static-local global-op with a constructor or "
2035 "destructor, they require in-function initialization via LocalInitOp");
2037 if (getDynTlsRefs()) {
2038 if (getStaticLocalGuard().has_value())
2040 "cannot have both static local and dynamic tls references");
2041 if (!getTlsModel() || getTlsModel() != TLS_Model::GeneralDynamic)
2042 return emitOpError(
"'dyn_tls_refs' only valid for dynamic tls");
2045 if (getAliasee().has_value()) {
2046 if (getInitialValue().has_value() || !getCtorRegion().empty() ||
2047 !getDtorRegion().empty())
2048 return emitOpError(
"global alias shall not have an initializer or "
2049 "constructor/destructor regions");
2058void cir::GlobalOp::build(
2059 OpBuilder &odsBuilder, OperationState &odsState, llvm::StringRef sym_name,
2060 mlir::Type sym_type,
bool isConstant,
2061 mlir::ptr::MemorySpaceAttrInterface addrSpace,
2062 cir::GlobalLinkageKind linkage,
2063 function_ref<
void(OpBuilder &, Location)> ctorBuilder,
2064 function_ref<
void(OpBuilder &, Location)> dtorBuilder) {
2065 odsState.addAttribute(getSymNameAttrName(odsState.name),
2066 odsBuilder.getStringAttr(sym_name));
2067 odsState.addAttribute(getSymTypeAttrName(odsState.name),
2068 mlir::TypeAttr::get(sym_type));
2069 auto &properties = odsState.getOrAddProperties<cir::GlobalOp::Properties>();
2070 properties.setConstant(isConstant);
2074 odsState.addAttribute(getAddrSpaceAttrName(odsState.name), addrSpace);
2076 cir::GlobalLinkageKindAttr linkageAttr =
2077 cir::GlobalLinkageKindAttr::get(odsBuilder.getContext(), linkage);
2078 odsState.addAttribute(getLinkageAttrName(odsState.name), linkageAttr);
2080 Region *ctorRegion = odsState.addRegion();
2082 odsBuilder.createBlock(ctorRegion);
2083 ctorBuilder(odsBuilder, odsState.location);
2086 Region *dtorRegion = odsState.addRegion();
2088 odsBuilder.createBlock(dtorRegion);
2089 dtorBuilder(odsBuilder, odsState.location);
2098void cir::GlobalOp::getSuccessorRegions(
2099 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
2101 if (!point.isParent()) {
2102 regions.emplace_back(getOperation());
2107 Region *ctorRegion = &this->getCtorRegion();
2108 if (ctorRegion->empty())
2109 ctorRegion =
nullptr;
2112 Region *dtorRegion = &this->getDtorRegion();
2113 if (dtorRegion->empty())
2114 dtorRegion =
nullptr;
2118 regions.push_back(RegionSuccessor(ctorRegion));
2120 regions.push_back(RegionSuccessor(dtorRegion));
2123mlir::ValueRange cir::GlobalOp::getSuccessorInputs(RegionSuccessor successor) {
2124 return successor.isOperation() ? ValueRange(getOperation()->getResults())
2129 TypeAttr type, Attribute initAttr,
2130 mlir::Region &ctorRegion,
2131 mlir::Region &dtorRegion) {
2132 auto printType = [&]() { p <<
": " << type; };
2135 if (op.isDeclaration() || op.getAliasee()) {
2141 if (!ctorRegion.empty()) {
2145 p.printRegion(ctorRegion,
2154 if (!dtorRegion.empty()) {
2156 p.printRegion(dtorRegion,
2164 Attribute &initialValueAttr,
2165 mlir::Region &ctorRegion,
2166 mlir::Region &dtorRegion) {
2168 if (parser.parseOptionalEqual().failed()) {
2171 if (parser.parseColonType(opTy))
2176 if (!parser.parseOptionalKeyword(
"ctor")) {
2177 if (parser.parseColonType(opTy))
2179 auto parseLoc = parser.getCurrentLocation();
2180 if (parser.parseRegion(ctorRegion, {}, {}))
2191 assert(mlir::isa<mlir::TypedAttr>(initialValueAttr) &&
2192 "Non-typed attrs shouldn't appear here.");
2193 opTy = mlir::cast<mlir::TypedAttr>(initialValueAttr).getType();
2198 if (!parser.parseOptionalKeyword(
"dtor")) {
2199 auto parseLoc = parser.getCurrentLocation();
2200 if (parser.parseRegion(dtorRegion, {}, {}))
2207 typeAttr = TypeAttr::get(opTy);
2216cir::GetGlobalOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2219 mlir::Operation *op =
2220 symbolTable.lookupNearestSymbolFrom(*
this, getNameAttr());
2221 if (op ==
nullptr || !(isa<GlobalOp>(op) || isa<FuncOp>(op)))
2222 return emitOpError(
"'")
2224 <<
"' does not reference a valid cir.global or cir.func";
2227 mlir::ptr::MemorySpaceAttrInterface symAddrSpaceAttr{};
2228 if (
auto g = dyn_cast<GlobalOp>(op)) {
2229 symTy = g.getSymType();
2230 symAddrSpaceAttr = g.getAddrSpaceAttr();
2233 if (getTls() && !g.getTlsModel())
2234 return emitOpError(
"access to global not marked thread local");
2239 bool getGlobalIsStaticLocal = getStaticLocal();
2240 bool globalIsStaticLocal = g.getStaticLocalGuard().has_value();
2241 if (getGlobalIsStaticLocal != globalIsStaticLocal &&
2242 !getOperation()->getParentOfType<cir::GlobalOp>())
2243 return emitOpError(
"static_local attribute mismatch");
2244 }
else if (
auto f = dyn_cast<FuncOp>(op)) {
2245 symTy = f.getFunctionType();
2247 llvm_unreachable(
"Unexpected operation for GetGlobalOp");
2250 auto resultType = dyn_cast<PointerType>(getAddr().
getType());
2251 if (!resultType || symTy != resultType.getPointee())
2252 return emitOpError(
"result type pointee type '")
2253 << resultType.getPointee() <<
"' does not match type " << symTy
2254 <<
" of the global @" <<
getName();
2256 if (symAddrSpaceAttr != resultType.getAddrSpace()) {
2257 return emitOpError()
2258 <<
"result type address space does not match the address "
2259 "space of the global @"
2271cir::VTableAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2277 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*
this, getNameAttr());
2279 return emitOpError(
"'")
2280 <<
name <<
"' does not reference a valid cir.global";
2281 std::optional<mlir::Attribute> init = op.getInitialValue();
2284 if (!isa<cir::VTableAttr>(*init))
2285 return emitOpError(
"Expected #cir.vtable in initializer for global '")
2295cir::VTTAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2304 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*
this, getNameAttr());
2306 return emitOpError(
"'")
2307 <<
name <<
"' does not reference a valid cir.global";
2308 std::optional<mlir::Attribute> init = op.getInitialValue();
2311 if (!isa<cir::ConstArrayAttr>(*init))
2313 "Expected constant array in initializer for global VTT '")
2318LogicalResult cir::VTTAddrPointOp::verify() {
2320 if (
getName() && getSymAddr())
2321 return emitOpError(
"should use either a symbol or value, but not both");
2327 mlir::Type resultType = getAddr().getType();
2328 mlir::Type resTy = cir::PointerType::get(
2329 cir::PointerType::get(cir::VoidType::get(getContext())));
2331 if (resultType != resTy)
2332 return emitOpError(
"result type must be ")
2333 << resTy <<
", but provided result type is " << resultType;
2345void cir::FuncOp::build(OpBuilder &builder, OperationState &result,
2346 StringRef name, FuncType type,
2347 GlobalLinkageKind linkage, CallingConv callingConv) {
2349 result.addAttribute(SymbolTable::getSymbolAttrName(),
2350 builder.getStringAttr(name));
2351 result.addAttribute(getFunctionTypeAttrName(result.name),
2352 TypeAttr::get(type));
2353 result.addAttribute(
2355 GlobalLinkageKindAttr::get(builder.getContext(), linkage));
2356 result.addAttribute(getCallingConvAttrName(result.name),
2357 CallingConvAttr::get(builder.getContext(), callingConv));
2365cir::AnnotationAttr::verify(function_ref<InFlightDiagnostic()> emitError,
2366 mlir::StringAttr name, mlir::ArrayAttr args) {
2369 for (mlir::Attribute arg : args) {
2370 if (!isa<mlir::StringAttr, mlir::IntegerAttr>(arg))
2371 return emitError() <<
"annotation args must be StringAttr or IntegerAttr,"
2377ParseResult cir::FuncOp::parse(OpAsmParser &parser, OperationState &state) {
2378 llvm::SMLoc loc = parser.getCurrentLocation();
2379 mlir::Builder &builder = parser.getBuilder();
2381 mlir::StringAttr builtinNameAttr = getBuiltinAttrName(state.name);
2382 mlir::StringAttr coroutineNameAttr = getCoroutineAttrName(state.name);
2383 mlir::StringAttr inlineKindNameAttr = getInlineKindAttrName(state.name);
2384 mlir::StringAttr lambdaNameAttr = getLambdaAttrName(state.name);
2385 mlir::StringAttr noProtoNameAttr = getNoProtoAttrName(state.name);
2386 mlir::StringAttr comdatNameAttr = getComdatAttrName(state.name);
2387 mlir::StringAttr visNameAttr = getSymVisibilityAttrName(state.name);
2388 mlir::StringAttr dsoLocalNameAttr = getDsoLocalAttrName(state.name);
2389 mlir::StringAttr specialMemberAttr = getCxxSpecialMemberAttrName(state.name);
2391 if (::mlir::succeeded(parser.parseOptionalKeyword(builtinNameAttr.strref())))
2392 state.addAttribute(builtinNameAttr, parser.getBuilder().getUnitAttr());
2393 if (::mlir::succeeded(
2394 parser.parseOptionalKeyword(coroutineNameAttr.strref())))
2395 state.addAttribute(coroutineNameAttr, parser.getBuilder().getUnitAttr());
2398 cir::InlineKindAttr inlineKindAttr;
2402 state.addAttribute(inlineKindNameAttr, inlineKindAttr);
2404 if (::mlir::succeeded(parser.parseOptionalKeyword(lambdaNameAttr.strref())))
2405 state.addAttribute(lambdaNameAttr, parser.getBuilder().getUnitAttr());
2406 if (parser.parseOptionalKeyword(noProtoNameAttr).succeeded())
2407 state.addAttribute(noProtoNameAttr, parser.getBuilder().getUnitAttr());
2409 if (parser.parseOptionalKeyword(comdatNameAttr).succeeded())
2410 state.addAttribute(comdatNameAttr, parser.getBuilder().getUnitAttr());
2414 GlobalLinkageKindAttr::get(
2415 parser.getContext(),
2417 parser, GlobalLinkageKind::ExternalLinkage)));
2419 ::llvm::StringRef visAttrStr;
2420 if (parser.parseOptionalKeyword(&visAttrStr, {
"private",
"public",
"nested"})
2422 state.addAttribute(visNameAttr,
2423 parser.getBuilder().getStringAttr(visAttrStr));
2426 state.getOrAddProperties<cir::FuncOp::Properties>().global_visibility =
2429 if (parser.parseOptionalKeyword(dsoLocalNameAttr).succeeded())
2430 state.addAttribute(dsoLocalNameAttr, parser.getBuilder().getUnitAttr());
2432 StringAttr nameAttr;
2433 if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
2439 bool isVariadic =
false;
2440 if (function_interface_impl::parseFunctionSignatureWithArguments(
2441 parser,
true, arguments, isVariadic, resultTypes,
2446 bool argAttrsEmpty =
true;
2447 for (OpAsmParser::Argument &arg : arguments) {
2448 argTypes.push_back(
arg.type);
2452 argAttrs.push_back(
arg.attrs);
2454 argAttrsEmpty =
false;
2458 if (resultTypes.size() > 1 || resultAttrs.size() > 1)
2459 return parser.emitError(
2460 loc,
"functions with multiple return types are not supported");
2462 mlir::Type returnType =
2463 (resultTypes.empty() ? cir::VoidType::get(builder.getContext())
2464 : resultTypes.front());
2466 cir::FuncType fnType = cir::FuncType::get(argTypes, returnType, isVariadic);
2470 state.addAttribute(getFunctionTypeAttrName(state.name),
2471 TypeAttr::get(fnType));
2473 if (!resultAttrs.empty() && resultAttrs[0])
2475 getResAttrsAttrName(state.name),
2476 mlir::ArrayAttr::get(parser.getContext(), {resultAttrs[0]}));
2479 state.addAttribute(getArgAttrsAttrName(state.name),
2480 mlir::ArrayAttr::get(parser.getContext(), argAttrs));
2482 bool hasAlias =
false;
2483 mlir::StringAttr aliaseeNameAttr = getAliaseeAttrName(state.name);
2484 if (parser.parseOptionalKeyword(
"alias").succeeded()) {
2485 if (parser.parseLParen().failed())
2487 mlir::StringAttr aliaseeAttr;
2488 if (parser.parseOptionalSymbolName(aliaseeAttr).failed())
2490 state.addAttribute(aliaseeNameAttr, FlatSymbolRefAttr::get(aliaseeAttr));
2491 if (parser.parseRParen().failed())
2496 mlir::StringAttr personalityNameAttr = getPersonalityAttrName(state.name);
2497 if (parser.parseOptionalKeyword(
"personality").succeeded()) {
2498 if (parser.parseLParen().failed())
2500 mlir::StringAttr personalityAttr;
2501 if (parser.parseOptionalSymbolName(personalityAttr).failed())
2503 state.addAttribute(personalityNameAttr,
2504 FlatSymbolRefAttr::get(personalityAttr));
2505 if (parser.parseRParen().failed())
2510 mlir::StringAttr callConvNameAttr = getCallingConvAttrName(state.name);
2511 cir::CallingConv callConv = cir::CallingConv::C;
2512 if (parser.parseOptionalKeyword(
"cc").succeeded()) {
2513 if (parser.parseLParen().failed())
2516 return parser.emitError(loc) <<
"unknown calling convention";
2517 if (parser.parseRParen().failed())
2520 state.addAttribute(callConvNameAttr,
2521 cir::CallingConvAttr::get(parser.getContext(), callConv));
2523 auto parseGlobalDtorCtor =
2524 [&](StringRef keyword,
2525 llvm::function_ref<void(std::optional<int> prio)> createAttr)
2526 -> mlir::LogicalResult {
2527 if (mlir::succeeded(parser.parseOptionalKeyword(keyword))) {
2528 std::optional<int> priority;
2529 if (mlir::succeeded(parser.parseOptionalLParen())) {
2530 auto parsedPriority = mlir::FieldParser<int>::parse(parser);
2531 if (mlir::failed(parsedPriority))
2532 return parser.emitError(parser.getCurrentLocation(),
2533 "failed to parse 'priority', of type 'int'");
2534 priority = parsedPriority.value_or(
int());
2536 if (parser.parseRParen())
2539 createAttr(priority);
2545 if (parser.parseOptionalKeyword(
"special_member").succeeded()) {
2546 if (parser.parseLess().failed())
2549 mlir::Attribute
attr;
2550 if (parser.parseAttribute(attr).failed())
2552 if (!mlir::isa<cir::CXXCtorAttr, cir::CXXDtorAttr, cir::CXXAssignAttr>(
2554 return parser.emitError(parser.getCurrentLocation(),
2555 "expected a C++ special member attribute");
2556 state.addAttribute(specialMemberAttr, attr);
2558 if (parser.parseGreater().failed())
2562 if (parseGlobalDtorCtor(
"global_ctor", [&](std::optional<int> priority) {
2563 mlir::IntegerAttr globalCtorPriorityAttr =
2564 builder.getI32IntegerAttr(priority.value_or(65535));
2565 state.addAttribute(getGlobalCtorPriorityAttrName(state.name),
2566 globalCtorPriorityAttr);
2570 if (parseGlobalDtorCtor(
"global_dtor", [&](std::optional<int> priority) {
2571 mlir::IntegerAttr globalDtorPriorityAttr =
2572 builder.getI32IntegerAttr(priority.value_or(65535));
2573 state.addAttribute(getGlobalDtorPriorityAttrName(state.name),
2574 globalDtorPriorityAttr);
2578 if (parser.parseOptionalKeyword(
"side_effect").succeeded()) {
2579 cir::SideEffect sideEffect;
2581 if (parser.parseLParen().failed() ||
2583 parser.parseRParen().failed())
2586 auto attr = cir::SideEffectAttr::get(parser.getContext(), sideEffect);
2587 state.addAttribute(CIRDialect::getSideEffectAttrName(), attr);
2591 mlir::StringAttr annotationsNameAttr = getAnnotationsAttrName(state.name);
2592 mlir::ArrayAttr annotationsAttr;
2593 if (parser.parseOptionalAttribute(annotationsAttr).has_value() &&
2595 state.addAttribute(annotationsNameAttr, annotationsAttr);
2598 NamedAttrList parsedAttrs;
2599 if (parser.parseOptionalAttrDictWithKeyword(parsedAttrs))
2602 for (StringRef disallowed : cir::FuncOp::getAttributeNames()) {
2603 if (parsedAttrs.get(disallowed))
2604 return parser.emitError(loc,
"attribute '")
2606 <<
"' should not be specified in the explicit attribute list";
2609 state.attributes.append(parsedAttrs);
2612 auto *body = state.addRegion();
2613 OptionalParseResult parseResult = parser.parseOptionalRegion(
2614 *body, arguments,
false);
2615 if (parseResult.has_value()) {
2617 return parser.emitError(loc,
"function alias shall not have a body");
2618 if (failed(*parseResult))
2622 return parser.emitError(loc,
"expected non-empty function body");
2631bool cir::FuncOp::isDeclaration() {
2634 std::optional<StringRef> aliasee = getAliasee();
2636 return getFunctionBody().empty();
2642bool cir::FuncOp::isCXXSpecialMemberFunction() {
2643 return getCxxSpecialMemberAttr() !=
nullptr;
2646bool cir::FuncOp::isCxxConstructor() {
2647 auto attr = getCxxSpecialMemberAttr();
2648 return attr && dyn_cast<CXXCtorAttr>(attr);
2651bool cir::FuncOp::isCxxDestructor() {
2652 auto attr = getCxxSpecialMemberAttr();
2653 return attr && dyn_cast<CXXDtorAttr>(attr);
2656bool cir::FuncOp::isCxxSpecialAssignment() {
2657 auto attr = getCxxSpecialMemberAttr();
2658 return attr && dyn_cast<CXXAssignAttr>(attr);
2661std::optional<CtorKind> cir::FuncOp::getCxxConstructorKind() {
2662 mlir::Attribute
attr = getCxxSpecialMemberAttr();
2664 if (
auto ctor = dyn_cast<CXXCtorAttr>(attr))
2665 return ctor.getCtorKind();
2667 return std::nullopt;
2670std::optional<AssignKind> cir::FuncOp::getCxxSpecialAssignKind() {
2671 mlir::Attribute
attr = getCxxSpecialMemberAttr();
2673 if (
auto assign = dyn_cast<CXXAssignAttr>(attr))
2674 return assign.getAssignKind();
2676 return std::nullopt;
2679bool cir::FuncOp::isCxxTrivialMemberFunction() {
2680 mlir::Attribute
attr = getCxxSpecialMemberAttr();
2682 if (
auto ctor = dyn_cast<CXXCtorAttr>(attr))
2683 return ctor.getIsTrivial();
2684 if (
auto dtor = dyn_cast<CXXDtorAttr>(attr))
2685 return dtor.getIsTrivial();
2686 if (
auto assign = dyn_cast<CXXAssignAttr>(attr))
2687 return assign.getIsTrivial();
2692mlir::Region *cir::FuncOp::getCallableRegion() {
2698void cir::FuncOp::print(OpAsmPrinter &p) {
2716 if (getLinkage() != GlobalLinkageKind::ExternalLinkage)
2717 p <<
' ' << stringifyGlobalLinkageKind(getLinkage());
2719 mlir::SymbolTable::Visibility vis = getVisibility();
2720 if (vis != mlir::SymbolTable::Visibility::Public)
2723 if (getGlobalVisibility() != cir::VisibilityKind::Default)
2724 p <<
' ' << stringifyVisibilityKind(getGlobalVisibility());
2730 p.printSymbolName(getSymName());
2731 cir::FuncType fnType = getFunctionType();
2732 function_interface_impl::printFunctionSignature(
2733 p, *
this, fnType.getInputs(), fnType.isVarArg(), fnType.getReturnTypes());
2735 if (std::optional<StringRef> aliaseeName = getAliasee()) {
2737 p.printSymbolName(*aliaseeName);
2741 if (getCallingConv() != cir::CallingConv::C) {
2743 p << stringifyCallingConv(getCallingConv());
2747 if (std::optional<StringRef> personalityName = getPersonality()) {
2748 p <<
" personality(";
2749 p.printSymbolName(*personalityName);
2753 if (
auto specialMemberAttr = getCxxSpecialMember()) {
2754 p <<
" special_member<";
2755 p.printAttribute(*specialMemberAttr);
2759 if (
auto globalCtorPriority = getGlobalCtorPriority()) {
2760 p <<
" global_ctor";
2761 if (globalCtorPriority.value() != 65535)
2762 p <<
"(" << globalCtorPriority.value() <<
")";
2765 if (
auto globalDtorPriority = getGlobalDtorPriority()) {
2766 p <<
" global_dtor";
2767 if (globalDtorPriority.value() != 65535)
2768 p <<
"(" << globalDtorPriority.value() <<
")";
2771 if (std::optional<cir::SideEffect> sideEffect = getSideEffect();
2772 sideEffect && *sideEffect != cir::SideEffect::All) {
2773 p <<
" side_effect(";
2774 p << stringifySideEffect(*sideEffect);
2778 if (mlir::ArrayAttr annotations = getAnnotationsAttr()) {
2780 p.printAttribute(annotations);
2783 function_interface_impl::printFunctionAttributes(
2784 p, *
this, cir::FuncOp::getAttributeNames());
2787 Region &body = getOperation()->getRegion(0);
2788 if (!body.empty()) {
2790 p.printRegion(body,
false,
2795mlir::LogicalResult cir::FuncOp::verify() {
2797 if (!isDeclaration() && getCoroutine()) {
2798 bool foundAwait =
false;
2799 int coroBodyCount = 0;
2800 this->walk([&](Operation *op) {
2801 if (
auto await = dyn_cast<AwaitOp>(op)) {
2803 }
else if (isa<CoroBodyOp>(op)) {
2805 if (coroBodyCount > 1) {
2806 return mlir::WalkResult::interrupt();
2809 return mlir::WalkResult::advance();
2812 return emitOpError()
2813 <<
"coroutine body must use at least one cir.await op";
2814 if (coroBodyCount != 1)
2815 return emitOpError()
2816 <<
"coroutine function must have exactly one cir.body op";
2819 llvm::SmallSet<llvm::StringRef, 16> labels;
2820 llvm::SmallSet<llvm::StringRef, 16> gotos;
2821 llvm::SmallSet<llvm::StringRef, 16> blockAddresses;
2822 bool invalidBlockAddress =
false;
2823 getOperation()->walk([&](mlir::Operation *op) {
2824 if (
auto lab = dyn_cast<cir::LabelOp>(op)) {
2825 labels.insert(lab.getLabel());
2826 }
else if (
auto goTo = dyn_cast<cir::GotoOp>(op)) {
2827 gotos.insert(goTo.getLabel());
2828 }
else if (
auto blkAdd = dyn_cast<cir::BlockAddressOp>(op)) {
2829 if (blkAdd.getBlockAddrInfoAttr().getFunc().getAttr() != getSymName()) {
2831 invalidBlockAddress =
true;
2832 return mlir::WalkResult::interrupt();
2834 blockAddresses.insert(blkAdd.getBlockAddrInfoAttr().getLabel());
2836 return mlir::WalkResult::advance();
2839 if (invalidBlockAddress)
2840 return emitOpError() <<
"blockaddress references a different function";
2842 llvm::SmallSet<llvm::StringRef, 16> mismatched;
2843 if (!labels.empty() || !gotos.empty()) {
2844 mismatched = llvm::set_difference(gotos, labels);
2846 if (!mismatched.empty())
2847 return emitOpError() <<
"goto/label mismatch";
2852 if (!labels.empty() || !blockAddresses.empty()) {
2853 mismatched = llvm::set_difference(blockAddresses, labels);
2855 if (!mismatched.empty())
2856 return emitOpError()
2857 <<
"expects an existing label target in the referenced function";
2871LogicalResult cir::AddOp::verify() {
2872 if (getSaturated() && (getNoSignedWrap() || getNoUnsignedWrap()))
2873 return emitOpError()
2874 <<
"the nsw/nuw flags and the saturated flag are mutually exclusive";
2875 return mlir::success();
2878LogicalResult cir::SubOp::verify() {
2879 if (getSaturated() && (getNoSignedWrap() || getNoUnsignedWrap()))
2880 return emitOpError()
2881 <<
"the nsw/nuw flags and the saturated flag are mutually exclusive";
2882 return mlir::success();
2894void cir::TernaryOp::getSuccessorRegions(
2895 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
2897 if (!point.isParent()) {
2898 regions.emplace_back(getOperation());
2904 regions.push_back(RegionSuccessor(&getTrueRegion()));
2905 regions.push_back(RegionSuccessor(&getFalseRegion()));
2908mlir::ValueRange cir::TernaryOp::getSuccessorInputs(RegionSuccessor successor) {
2909 return successor.isOperation() ? ValueRange(getOperation()->getResults())
2913void cir::TernaryOp::build(
2914 OpBuilder &builder, OperationState &result,
Value cond,
2915 function_ref<
void(OpBuilder &, Location)> trueBuilder,
2916 function_ref<
void(OpBuilder &, Location)> falseBuilder) {
2917 result.addOperands(cond);
2918 OpBuilder::InsertionGuard guard(builder);
2919 Region *trueRegion = result.addRegion();
2920 builder.createBlock(trueRegion);
2921 trueBuilder(builder, result.location);
2922 Region *falseRegion = result.addRegion();
2923 builder.createBlock(falseRegion);
2924 falseBuilder(builder, result.location);
2929 if (trueRegion->back().mightHaveTerminator())
2930 yield = dyn_cast_or_null<cir::YieldOp>(trueRegion->back().getTerminator());
2931 if (!yield && falseRegion->back().mightHaveTerminator())
2932 yield = dyn_cast_or_null<cir::YieldOp>(falseRegion->back().getTerminator());
2934 assert((!yield || yield.getNumOperands() <= 1) &&
2935 "expected zero or one result type");
2936 if (yield && yield.getNumOperands() == 1)
2937 result.addTypes(TypeRange{yield.getOperandTypes().front()});
2944OpFoldResult cir::SelectOp::fold(FoldAdaptor adaptor) {
2945 mlir::Attribute
condition = adaptor.getCondition();
2947 bool conditionValue = mlir::cast<cir::BoolAttr>(
condition).getValue();
2948 return conditionValue ? getTrueValue() : getFalseValue();
2952 mlir::Attribute trueValue = adaptor.getTrueValue();
2953 mlir::Attribute falseValue = adaptor.getFalseValue();
2954 if (trueValue == falseValue)
2956 if (getTrueValue() == getFalseValue())
2957 return getTrueValue();
2962LogicalResult cir::SelectOp::verify() {
2964 auto condTy = dyn_cast<cir::VectorType>(getCondition().
getType());
2971 if (!isa<cir::VectorType>(getTrueValue().
getType()) ||
2972 !isa<cir::VectorType>(getFalseValue().
getType())) {
2973 return emitOpError()
2974 <<
"expected both true and false operands to be vector types "
2975 "when the condition is a vector boolean type";
2984LogicalResult cir::ShiftOp::verify() {
2985 mlir::Operation *op = getOperation();
2986 auto op0VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(0).getType());
2987 auto op1VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(1).getType());
2988 if (!op0VecTy ^ !op1VecTy)
2989 return emitOpError() <<
"input types cannot be one vector and one scalar";
2992 if (op0VecTy.getSize() != op1VecTy.getSize())
2993 return emitOpError() <<
"input vector types must have the same size";
2995 auto opResultTy = mlir::dyn_cast<cir::VectorType>(
getType());
2997 return emitOpError() <<
"the type of the result must be a vector "
2998 <<
"if it is vector shift";
3000 auto op0VecEleTy = mlir::cast<cir::IntType>(op0VecTy.getElementType());
3001 auto op1VecEleTy = mlir::cast<cir::IntType>(op1VecTy.getElementType());
3002 if (op0VecEleTy.getWidth() != op1VecEleTy.getWidth())
3003 return emitOpError()
3004 <<
"vector operands do not have the same elements sizes";
3006 auto resVecEleTy = mlir::cast<cir::IntType>(opResultTy.getElementType());
3007 if (op0VecEleTy.getWidth() != resVecEleTy.getWidth())
3008 return emitOpError() <<
"vector operands and result type do not have the "
3009 "same elements sizes";
3012 return mlir::success();
3019LogicalResult cir::LabelOp::verify() {
3020 mlir::Operation *op = getOperation();
3021 mlir::Block *blk = op->getBlock();
3022 if (&blk->front() != op)
3023 return emitError() <<
"must be the first operation in a block";
3025 return mlir::success();
3032OpFoldResult cir::IncOp::fold(FoldAdaptor adaptor) {
3033 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3034 return adaptor.getInput();
3042OpFoldResult cir::DecOp::fold(FoldAdaptor adaptor) {
3043 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3044 return adaptor.getInput();
3052OpFoldResult cir::MinusOp::fold(FoldAdaptor adaptor) {
3053 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3054 return adaptor.getInput();
3059 mlir::dyn_cast_if_present<cir::IntAttr>(adaptor.getInput())) {
3060 APInt val = intAttr.getValue();
3062 return cir::IntAttr::get(
getType(), val);
3072OpFoldResult cir::FNegOp::fold(FoldAdaptor adaptor) {
3073 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3074 return adaptor.getInput();
3078 mlir::dyn_cast_if_present<cir::FPAttr>(adaptor.getInput())) {
3079 APFloat val = fpAttr.getValue();
3081 return cir::FPAttr::get(
getType(), val);
3091OpFoldResult cir::NotOp::fold(FoldAdaptor adaptor) {
3092 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3093 return adaptor.getInput();
3098 if (mlir::Attribute attr = adaptor.getInput()) {
3099 if (
auto intAttr = mlir::dyn_cast<cir::IntAttr>(attr)) {
3100 APInt val = intAttr.getValue();
3102 return cir::IntAttr::get(
getType(), val);
3104 if (
auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr))
3105 return cir::BoolAttr::get(getContext(), !boolAttr.getValue());
3116 mlir::Type resultTy) {
3119 mlir::Type inputMemberTy;
3120 mlir::Type resultMemberTy;
3121 if (mlir::isa<cir::DataMemberType>(src.getType())) {
3123 mlir::cast<cir::DataMemberType>(src.getType()).getMemberTy();
3124 resultMemberTy = mlir::cast<cir::DataMemberType>(resultTy).getMemberTy();
3127 if (inputMemberTy != resultMemberTy)
3128 return op->emitOpError()
3129 <<
"member types of the operand and the result do not match";
3131 return mlir::success();
3134LogicalResult cir::BaseDataMemberOp::verify() {
3138LogicalResult cir::DerivedDataMemberOp::verify() {
3146LogicalResult cir::BaseMethodOp::verify() {
3150LogicalResult cir::DerivedMethodOp::verify() {
3158void cir::AwaitOp::build(OpBuilder &builder, OperationState &result,
3162 result.addAttribute(getKindAttrName(result.name),
3163 cir::AwaitKindAttr::get(builder.getContext(),
kind));
3165 OpBuilder::InsertionGuard guard(builder);
3166 Region *readyRegion = result.addRegion();
3167 builder.createBlock(readyRegion);
3168 readyBuilder(builder, result.location);
3172 OpBuilder::InsertionGuard guard(builder);
3173 Region *suspendRegion = result.addRegion();
3174 builder.createBlock(suspendRegion);
3175 suspendBuilder(builder, result.location);
3179 OpBuilder::InsertionGuard guard(builder);
3180 Region *resumeRegion = result.addRegion();
3181 builder.createBlock(resumeRegion);
3182 resumeBuilder(builder, result.location);
3186void cir::AwaitOp::getSuccessorRegions(
3187 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
3190 if (!point.isParent()) {
3191 regions.emplace_back(getOperation());
3198 regions.push_back(RegionSuccessor(&this->getReady()));
3199 regions.push_back(RegionSuccessor(&this->getSuspend()));
3200 regions.push_back(RegionSuccessor(&this->getResume()));
3203mlir::ValueRange cir::AwaitOp::getSuccessorInputs(RegionSuccessor successor) {
3204 if (successor.isOperation())
3205 return getOperation()->getResults();
3206 if (successor == &getReady())
3207 return getReady().getArguments();
3208 if (successor == &getSuspend())
3209 return getSuspend().getArguments();
3210 if (successor == &getResume())
3211 return getResume().getArguments();
3212 llvm_unreachable(
"invalid region successor");
3215LogicalResult cir::AwaitOp::verify() {
3216 if (!isa<ConditionOp>(this->getReady().back().getTerminator()))
3217 return emitOpError(
"ready region must end with cir.condition");
3225void cir::CoroBodyOp::getSuccessorRegions(
3226 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
3227 if (!point.isParent()) {
3228 regions.emplace_back(getOperation());
3232 regions.push_back(RegionSuccessor(&getBody()));
3236cir::CoroBodyOp::getSuccessorInputs(RegionSuccessor successor) {
3237 return ValueRange();
3240LogicalResult cir::CoroBodyOp::verify() {
3241 if (!getOperation()->getParentOfType<FuncOp>().getCoroutine())
3242 return emitOpError(
"enclosing function must be a coroutine");
3246void cir::CoroBodyOp::build(OpBuilder &builder, OperationState &result,
3248 assert(bodyBuilder &&
3249 "the builder callback for 'CoroBodyOp' must be present");
3250 OpBuilder::InsertionGuard guard(builder);
3252 Region *bodyRegion = result.addRegion();
3253 builder.createBlock(bodyRegion);
3254 bodyBuilder(builder, result.location);
3261LogicalResult cir::CopyOp::verify() {
3263 if (!
getType().getPointee().hasTrait<DataLayoutTypeInterface::Trait>())
3264 return emitError() <<
"missing data layout for pointee type";
3266 if (getSkipTailPadding() &&
3267 !mlir::isa<cir::RecordType>(
getType().getPointee()))
3269 <<
"skip_tail_padding is only valid for record pointee types";
3271 return mlir::success();
3278LogicalResult cir::GetRuntimeMemberOp::verify() {
3279 cir::DataMemberType memberPtrTy = getMember().getType();
3281 if (getAddr().
getType().getPointee() != memberPtrTy.getClassTy())
3282 return emitError() <<
"record type does not match the member pointer type";
3283 if (
getType().getPointee() != memberPtrTy.getMemberTy())
3284 return emitError() <<
"result type does not match the member pointer type";
3285 return mlir::success();
3292LogicalResult cir::GetMethodOp::verify() {
3293 cir::MethodType methodTy = getMethod().getType();
3296 cir::PointerType objectPtrTy = getObject().getType();
3297 mlir::Type objectTy = objectPtrTy.getPointee();
3299 if (methodTy.getClassTy() != objectTy)
3300 return emitError() <<
"method class type and object type do not match";
3303 auto calleeTy = mlir::cast<cir::FuncType>(getCallee().
getType().getPointee());
3304 cir::FuncType methodFuncTy = methodTy.getMemberFuncTy();
3311 if (methodFuncTy.getReturnType() != calleeTy.getReturnType())
3313 <<
"method return type and callee return type do not match";
3318 if (calleeArgsTy.empty())
3319 return emitError() <<
"callee parameter list lacks receiver object ptr";
3321 auto calleeThisArgPtrTy = mlir::dyn_cast<cir::PointerType>(calleeArgsTy[0]);
3322 if (!calleeThisArgPtrTy ||
3323 !mlir::isa<cir::VoidType>(calleeThisArgPtrTy.getPointee())) {
3325 <<
"the first parameter of callee must be a void pointer";
3328 if (calleeArgsTy.size() != methodFuncArgsTy.size())
3329 return emitError() <<
"callee and method parameter counts do not match";
3331 if (calleeArgsTy.size() > 1 &&
3332 calleeArgsTy.slice(1) != methodFuncArgsTy.slice(1))
3334 <<
"callee parameters and method parameters do not match";
3336 return mlir::success();
3343LogicalResult cir::GetMemberOp::verify() {
3344 const auto recordTy = dyn_cast<RecordType>(getAddrTy().getPointee());
3346 return emitError() <<
"expected pointer to a record type";
3348 if (recordTy.getMembers().size() <=
getIndex())
3349 return emitError() <<
"member index out of bounds";
3352 return emitError() <<
"member type mismatch";
3354 return mlir::success();
3361LogicalResult cir::ExtractMemberOp::verify() {
3362 if (mlir::isa<cir::UnionType>(getRecord().
getType()))
3364 <<
"cir.extract_member currently does not support unions";
3365 auto structTy = mlir::cast<cir::StructType>(getRecord().
getType());
3366 if (structTy.getMembers().size() <=
getIndex())
3367 return emitError() <<
"member index out of bounds";
3369 return emitError() <<
"member type mismatch";
3370 return mlir::success();
3377LogicalResult cir::InsertMemberOp::verify() {
3378 if (mlir::isa<cir::UnionType>(getRecord().
getType()))
3379 return emitError() <<
"cir.insert_member currently does not support unions";
3380 auto structTy = mlir::cast<cir::StructType>(getRecord().
getType());
3381 if (structTy.getMembers().size() <=
getIndex())
3382 return emitError() <<
"member index out of bounds";
3384 return emitError() <<
"member type mismatch";
3386 return mlir::success();
3393OpFoldResult cir::VecCreateOp::fold(FoldAdaptor adaptor) {
3394 if (llvm::any_of(getElements(), [](mlir::Value value) {
3395 return !value.getDefiningOp<cir::ConstantOp>();
3399 return cir::ConstVectorAttr::get(
3400 getType(), mlir::ArrayAttr::get(getContext(), adaptor.getElements()));
3403LogicalResult cir::VecCreateOp::verify() {
3407 const cir::VectorType vecTy =
getType();
3408 if (getElements().size() != vecTy.getSize()) {
3409 return emitOpError() <<
"operand count of " << getElements().size()
3410 <<
" doesn't match vector type " << vecTy
3411 <<
" element count of " << vecTy.getSize();
3414 const mlir::Type elementType = vecTy.getElementType();
3415 for (
const mlir::Value element : getElements()) {
3416 if (element.getType() != elementType) {
3417 return emitOpError() <<
"operand type " << element.getType()
3418 <<
" doesn't match vector element type "
3430OpFoldResult cir::VecExtractOp::fold(FoldAdaptor adaptor) {
3431 const auto vectorAttr =
3432 llvm::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec());
3436 const auto indexAttr =
3437 llvm::dyn_cast_if_present<cir::IntAttr>(adaptor.getIndex());
3441 const mlir::ArrayAttr elements = vectorAttr.getElts();
3442 const uint64_t index = indexAttr.getUInt();
3443 if (index >= elements.size())
3446 return elements[index];
3453OpFoldResult cir::VecCmpOp::fold(FoldAdaptor adaptor) {
3455 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getLhs());
3457 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getRhs());
3458 if (!lhsVecAttr || !rhsVecAttr)
3461 mlir::Type inputElemTy =
3462 mlir::cast<cir::VectorType>(lhsVecAttr.getType()).getElementType();
3463 if (!isAnyIntegerOrFloatingPointType(inputElemTy))
3466 cir::CmpOpKind opKind = adaptor.getKind();
3467 mlir::ArrayAttr lhsVecElhs = lhsVecAttr.getElts();
3468 mlir::ArrayAttr rhsVecElhs = rhsVecAttr.getElts();
3469 uint64_t vecSize = lhsVecElhs.size();
3472 bool isIntAttr = vecSize && mlir::isa<cir::IntAttr>(lhsVecElhs[0]);
3473 bool isUnsignedInt =
3474 isIntAttr && mlir::cast<cir::IntType>(inputElemTy).isUnsigned();
3475 for (uint64_t i = 0; i < vecSize; i++) {
3476 mlir::Attribute lhsAttr = lhsVecElhs[i];
3477 mlir::Attribute rhsAttr = rhsVecElhs[i];
3478 bool cmpResult =
false;
3480 case cir::CmpOpKind::lt: {
3483 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() <
3484 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
3486 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <
3487 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3489 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <
3490 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3494 case cir::CmpOpKind::le: {
3497 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() <=
3498 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
3500 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <=
3501 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3503 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <=
3504 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3508 case cir::CmpOpKind::gt: {
3511 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() >
3512 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
3514 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >
3515 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3517 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >
3518 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3522 case cir::CmpOpKind::ge: {
3525 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() >=
3526 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
3528 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >=
3529 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3531 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >=
3532 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3536 case cir::CmpOpKind::eq: {
3538 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() ==
3539 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3541 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() ==
3542 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3546 case cir::CmpOpKind::ne: {
3548 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() !=
3549 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3551 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() !=
3552 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3556 case cir::CmpOpKind::one: {
3557 llvm::APFloat::cmpResult cr =
3558 mlir::cast<cir::FPAttr>(lhsAttr).getValue().compare(
3559 mlir::cast<cir::FPAttr>(rhsAttr).getValue());
3561 cr != llvm::APFloat::cmpUnordered && cr != llvm::APFloat::cmpEqual;
3564 case cir::CmpOpKind::uno: {
3565 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue().compare(
3566 mlir::cast<cir::FPAttr>(rhsAttr).getValue()) ==
3567 llvm::APFloat::cmpUnordered;
3576 cir::IntAttr::get(
getType().getElementType(), cmpResult ? -1LL : 0LL);
3579 return cir::ConstVectorAttr::get(
3580 getType(), mlir::ArrayAttr::get(getContext(), elements));
3587OpFoldResult cir::VecShuffleOp::fold(FoldAdaptor adaptor) {
3589 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec1());
3591 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec2());
3592 if (!vec1Attr || !vec2Attr)
3595 mlir::Type vec1ElemTy =
3596 mlir::cast<cir::VectorType>(vec1Attr.getType()).getElementType();
3598 mlir::ArrayAttr vec1Elts = vec1Attr.getElts();
3599 mlir::ArrayAttr vec2Elts = vec2Attr.getElts();
3600 mlir::ArrayAttr indicesElts = adaptor.getIndices();
3603 elements.reserve(indicesElts.size());
3605 uint64_t vec1Size = vec1Elts.size();
3606 for (
const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
3607 if (idxAttr.getSInt() == -1) {
3608 elements.push_back(cir::UndefAttr::get(vec1ElemTy));
3612 uint64_t idxValue = idxAttr.getUInt();
3613 elements.push_back(idxValue < vec1Size ? vec1Elts[idxValue]
3614 : vec2Elts[idxValue - vec1Size]);
3617 return cir::ConstVectorAttr::get(
3618 getType(), mlir::ArrayAttr::get(getContext(), elements));
3621LogicalResult cir::VecShuffleOp::verify() {
3624 if (getIndices().size() != getResult().
getType().getSize()) {
3625 return emitOpError() <<
": the number of elements in " << getIndices()
3626 <<
" and " << getResult().getType() <<
" don't match";
3631 if (getVec1().
getType().getElementType() !=
3632 getResult().
getType().getElementType()) {
3633 return emitOpError() <<
": element types of " << getVec1().getType()
3634 <<
" and " << getResult().getType() <<
" don't match";
3637 const uint64_t maxValidIndex =
3638 getVec1().getType().getSize() + getVec2().getType().getSize() - 1;
3640 getIndices().getAsRange<cir::IntAttr>(), [&](cir::IntAttr idxAttr) {
3641 return idxAttr.getSInt() != -1 && idxAttr.getUInt() > maxValidIndex;
3643 return emitOpError() <<
": index for __builtin_shufflevector must be "
3644 "less than the total number of vector elements";
3653OpFoldResult cir::VecShuffleDynamicOp::fold(FoldAdaptor adaptor) {
3654 mlir::Attribute vec = adaptor.getVec();
3655 mlir::Attribute indices = adaptor.getIndices();
3656 if (mlir::isa_and_nonnull<cir::ConstVectorAttr>(vec) &&
3657 mlir::isa_and_nonnull<cir::ConstVectorAttr>(indices)) {
3658 auto vecAttr = mlir::cast<cir::ConstVectorAttr>(vec);
3659 auto indicesAttr = mlir::cast<cir::ConstVectorAttr>(indices);
3661 mlir::ArrayAttr vecElts = vecAttr.getElts();
3662 mlir::ArrayAttr indicesElts = indicesAttr.getElts();
3664 const uint64_t numElements = vecElts.size();
3667 elements.reserve(numElements);
3669 const uint64_t maskBits = llvm::NextPowerOf2(numElements - 1) - 1;
3670 for (
const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
3671 uint64_t idxValue = idxAttr.getUInt();
3672 uint64_t newIdx = idxValue & maskBits;
3673 elements.push_back(vecElts[newIdx]);
3676 return cir::ConstVectorAttr::get(
3677 getType(), mlir::ArrayAttr::get(getContext(), elements));
3683LogicalResult cir::VecShuffleDynamicOp::verify() {
3685 if (getVec().
getType().getSize() !=
3686 mlir::cast<cir::VectorType>(getIndices().
getType()).getSize()) {
3687 return emitOpError() <<
": the number of elements in " << getVec().getType()
3688 <<
" and " << getIndices().getType() <<
" don't match";
3697LogicalResult cir::VecTernaryOp::verify() {
3702 if (getCond().
getType().getSize() != getLhs().
getType().getSize()) {
3703 return emitOpError() <<
": the number of elements in "
3704 << getCond().getType() <<
" and " << getLhs().getType()
3710OpFoldResult cir::VecTernaryOp::fold(FoldAdaptor adaptor) {
3711 mlir::Attribute cond = adaptor.getCond();
3712 mlir::Attribute lhs = adaptor.getLhs();
3713 mlir::Attribute rhs = adaptor.getRhs();
3715 if (!mlir::isa_and_nonnull<cir::ConstVectorAttr>(cond) ||
3716 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(lhs) ||
3717 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(rhs))
3719 auto condVec = mlir::cast<cir::ConstVectorAttr>(cond);
3720 auto lhsVec = mlir::cast<cir::ConstVectorAttr>(lhs);
3721 auto rhsVec = mlir::cast<cir::ConstVectorAttr>(rhs);
3723 mlir::ArrayAttr condElts = condVec.getElts();
3726 elements.reserve(condElts.size());
3728 for (
const auto &[idx, condAttr] :
3729 llvm::enumerate(condElts.getAsRange<cir::IntAttr>())) {
3730 if (condAttr.getSInt()) {
3731 elements.push_back(lhsVec.getElts()[idx]);
3733 elements.push_back(rhsVec.getElts()[idx]);
3737 cir::VectorType vecTy = getLhs().getType();
3738 return cir::ConstVectorAttr::get(
3739 vecTy, mlir::ArrayAttr::get(getContext(), elements));
3746LogicalResult cir::ComplexCreateOp::verify() {
3749 <<
"operand type of cir.complex.create does not match its result type";
3756OpFoldResult cir::ComplexCreateOp::fold(FoldAdaptor adaptor) {
3757 mlir::Attribute real = adaptor.getReal();
3758 mlir::Attribute imag = adaptor.getImag();
3764 auto realAttr = mlir::cast<mlir::TypedAttr>(real);
3765 auto imagAttr = mlir::cast<mlir::TypedAttr>(imag);
3766 return cir::ConstComplexAttr::get(realAttr, imagAttr);
3773LogicalResult cir::ComplexRealOp::verify() {
3774 mlir::Type operandTy = getOperand().getType();
3775 if (
auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
3776 operandTy = complexOperandTy.getElementType();
3779 emitOpError() <<
": result type does not match operand type";
3786OpFoldResult cir::ComplexRealOp::fold(FoldAdaptor adaptor) {
3787 if (!mlir::isa<cir::ComplexType>(getOperand().
getType()))
3790 if (
auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
3791 return complexCreateOp.getOperand(0);
3794 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
3795 return complex ? complex.getReal() :
nullptr;
3802LogicalResult cir::ComplexImagOp::verify() {
3803 mlir::Type operandTy = getOperand().getType();
3804 if (
auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
3805 operandTy = complexOperandTy.getElementType();
3808 emitOpError() <<
": result type does not match operand type";
3815OpFoldResult cir::ComplexImagOp::fold(FoldAdaptor adaptor) {
3816 if (!mlir::isa<cir::ComplexType>(getOperand().
getType()))
3819 if (
auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
3820 return complexCreateOp.getOperand(1);
3823 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
3824 return complex ? complex.getImag() :
nullptr;
3831LogicalResult cir::ComplexRealPtrOp::verify() {
3832 mlir::Type resultPointeeTy =
getType().getPointee();
3833 cir::PointerType operandPtrTy = getOperand().getType();
3834 auto operandPointeeTy =
3835 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
3837 if (resultPointeeTy != operandPointeeTy.getElementType()) {
3838 return emitOpError() <<
": result type does not match operand type";
3848LogicalResult cir::ComplexImagPtrOp::verify() {
3849 mlir::Type resultPointeeTy =
getType().getPointee();
3850 cir::PointerType operandPtrTy = getOperand().getType();
3851 auto operandPointeeTy =
3852 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
3854 if (resultPointeeTy != operandPointeeTy.getElementType()) {
3855 return emitOpError()
3856 <<
"cir.complex.imag_ptr result type does not match operand type";
3867 llvm::function_ref<llvm::APInt(
const llvm::APInt &)> func,
3868 bool poisonZero =
false) {
3869 if (mlir::isa_and_present<cir::PoisonAttr>(inputAttr)) {
3874 auto input = mlir::dyn_cast_if_present<IntAttr>(inputAttr);
3878 llvm::APInt inputValue = input.getValue();
3879 if (poisonZero && inputValue.isZero())
3880 return cir::PoisonAttr::get(input.getType());
3882 llvm::APInt resultValue = func(inputValue);
3883 return IntAttr::get(input.getType(), resultValue);
3886OpFoldResult BitClrsbOp::fold(FoldAdaptor adaptor) {
3887 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3888 unsigned resultValue =
3889 inputValue.getBitWidth() - inputValue.getSignificantBits();
3890 return llvm::APInt(inputValue.getBitWidth(), resultValue);
3894OpFoldResult BitClzOp::fold(FoldAdaptor adaptor) {
3897 [](
const llvm::APInt &inputValue) {
3898 unsigned resultValue = inputValue.countLeadingZeros();
3899 return llvm::APInt(inputValue.getBitWidth(), resultValue);
3904OpFoldResult BitCtzOp::fold(FoldAdaptor adaptor) {
3907 [](
const llvm::APInt &inputValue) {
3908 return llvm::APInt(inputValue.getBitWidth(),
3909 inputValue.countTrailingZeros());
3914OpFoldResult BitFfsOp::fold(FoldAdaptor adaptor) {
3915 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3916 unsigned trailingZeros = inputValue.countTrailingZeros();
3918 trailingZeros == inputValue.getBitWidth() ? 0 : trailingZeros + 1;
3919 return llvm::APInt(inputValue.getBitWidth(), result);
3923OpFoldResult BitParityOp::fold(FoldAdaptor adaptor) {
3924 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3925 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount() % 2);
3929OpFoldResult BitPopcountOp::fold(FoldAdaptor adaptor) {
3930 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3931 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount());
3935OpFoldResult BitReverseOp::fold(FoldAdaptor adaptor) {
3936 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3937 return inputValue.reverseBits();
3941OpFoldResult ByteSwapOp::fold(FoldAdaptor adaptor) {
3942 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3943 return inputValue.byteSwap();
3947OpFoldResult RotateOp::fold(FoldAdaptor adaptor) {
3948 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()) ||
3949 mlir::isa_and_present<cir::PoisonAttr>(adaptor.getAmount())) {
3951 return cir::PoisonAttr::get(
getType());
3954 auto input = mlir::dyn_cast_if_present<IntAttr>(adaptor.getInput());
3955 auto amount = mlir::dyn_cast_if_present<IntAttr>(adaptor.getAmount());
3956 if (!input && !amount)
3965 llvm::APInt inputValue;
3967 inputValue = input.getValue();
3968 if (inputValue.isZero() || inputValue.isAllOnes()) {
3974 uint64_t amountValue;
3976 amountValue = amount.getValue().urem(getInput().
getType().getWidth());
3977 if (amountValue == 0) {
3983 if (!input || !amount)
3986 assert(inputValue.getBitWidth() == getInput().
getType().getWidth() &&
3987 "input value must have the same bit width as the input type");
3989 llvm::APInt resultValue;
3991 resultValue = inputValue.rotl(amountValue);
3993 resultValue = inputValue.rotr(amountValue);
3995 return IntAttr::get(input.getContext(), input.getType(), resultValue);
4002void cir::InlineAsmOp::print(OpAsmPrinter &p) {
4003 p <<
'(' << getAsmFlavor() <<
", ";
4008 auto *nameIt = names.begin();
4009 auto *attrIt = getOperandAttrs().begin();
4011 for (mlir::OperandRange ops : getAsmOperands()) {
4012 p << *nameIt <<
" = ";
4015 llvm::interleaveComma(llvm::make_range(ops.begin(), ops.end()), p,
4017 p.printOperand(value);
4018 p <<
" : " << value.getType();
4019 if (mlir::isa<mlir::UnitAttr>(*attrIt))
4020 p <<
" (maybe_memory)";
4029 p.printString(getAsmString());
4031 p.printString(getConstraints());
4035 if (getSideEffects())
4036 p <<
" side_effects";
4038 std::array elidedAttrs{
4039 llvm::StringRef(
"asm_flavor"), llvm::StringRef(
"asm_string"),
4040 llvm::StringRef(
"constraints"), llvm::StringRef(
"operand_attrs"),
4041 llvm::StringRef(
"operands_segments"), llvm::StringRef(
"side_effects")};
4042 p.printOptionalAttrDict(getOperation()->getAttrs(), elidedAttrs);
4044 if (
auto v = getRes())
4045 p <<
" -> " << v.getType();
4048void cir::InlineAsmOp::build(OpBuilder &odsBuilder, OperationState &odsState,
4050 StringRef asmString, StringRef constraints,
4051 bool sideEffects, cir::AsmFlavor asmFlavor,
4055 for (
auto operandRange : asmOperands) {
4056 segments.push_back(operandRange.size());
4057 odsState.addOperands(operandRange);
4060 odsState.addAttribute(
4061 "operands_segments",
4062 DenseI32ArrayAttr::get(odsBuilder.getContext(), segments));
4063 odsState.addAttribute(
"asm_string", odsBuilder.getStringAttr(asmString));
4064 odsState.addAttribute(
"constraints", odsBuilder.getStringAttr(constraints));
4065 odsState.addAttribute(
"asm_flavor",
4066 AsmFlavorAttr::get(odsBuilder.getContext(), asmFlavor));
4069 odsState.addAttribute(
"side_effects", odsBuilder.getUnitAttr());
4071 odsState.addAttribute(
"operand_attrs", odsBuilder.getArrayAttr(operandAttrs));
4074ParseResult cir::InlineAsmOp::parse(OpAsmParser &parser,
4075 OperationState &result) {
4078 std::string asmString, constraints;
4080 MLIRContext *ctxt = parser.getBuilder().getContext();
4082 auto error = [&](
const Twine &msg) -> LogicalResult {
4083 return parser.emitError(parser.getCurrentLocation(), msg);
4086 auto expected = [&](
const std::string &c) {
4087 return error(
"expected '" + c +
"'");
4090 if (parser.parseLParen().failed())
4091 return expected(
"(");
4093 auto flavor = FieldParser<AsmFlavor, AsmFlavor>::parse(parser);
4095 return error(
"Unknown AsmFlavor");
4097 if (parser.parseComma().failed())
4098 return expected(
",");
4100 auto parseValue = [&](
Value &v) {
4101 OpAsmParser::UnresolvedOperand op;
4103 if (parser.parseOperand(op) || parser.parseColon())
4104 return error(
"can't parse operand");
4107 if (parser.parseType(typ).failed())
4108 return error(
"can't parse operand type");
4110 if (parser.resolveOperand(op, typ, tmp))
4111 return error(
"can't resolve operand");
4113 return mlir::success();
4116 auto parseOperands = [&](llvm::StringRef
name) {
4117 if (parser.parseKeyword(name).failed())
4118 return error(
"expected " + name +
" operands here");
4119 if (parser.parseEqual().failed())
4120 return expected(
"=");
4121 if (parser.parseLSquare().failed())
4122 return expected(
"[");
4125 if (parser.parseOptionalRSquare().succeeded()) {
4126 operandsGroupSizes.push_back(size);
4127 if (parser.parseComma())
4128 return expected(
",");
4129 return mlir::success();
4132 auto parseOperand = [&]() {
4134 if (parseValue(val).succeeded()) {
4135 result.operands.push_back(val);
4138 if (parser.parseOptionalLParen().failed()) {
4139 operandAttrs.push_back(mlir::DictionaryAttr::get(ctxt));
4140 return mlir::success();
4143 if (parser.parseKeyword(
"maybe_memory").succeeded()) {
4144 operandAttrs.push_back(mlir::UnitAttr::get(ctxt));
4145 if (parser.parseRParen())
4146 return expected(
")");
4147 return mlir::success();
4149 return expected(
"maybe_memory");
4152 return mlir::failure();
4155 if (parser.parseCommaSeparatedList(parseOperand).failed())
4156 return mlir::failure();
4158 if (parser.parseRSquare().failed() || parser.parseComma().failed())
4159 return expected(
"]");
4160 operandsGroupSizes.push_back(size);
4161 return mlir::success();
4164 if (parseOperands(
"out").failed() || parseOperands(
"in").failed() ||
4165 parseOperands(
"in_out").failed())
4166 return error(
"failed to parse operands");
4168 if (parser.parseLBrace())
4169 return expected(
"{");
4170 if (parser.parseString(&asmString))
4171 return error(
"asm string parsing failed");
4172 if (parser.parseString(&constraints))
4173 return error(
"constraints string parsing failed");
4174 if (parser.parseRBrace())
4175 return expected(
"}");
4176 if (parser.parseRParen())
4177 return expected(
")");
4179 if (parser.parseOptionalKeyword(
"side_effects").succeeded())
4180 result.attributes.set(
"side_effects", UnitAttr::get(ctxt));
4182 if (parser.parseOptionalAttrDict(result.attributes).failed())
4183 return mlir::failure();
4185 if (parser.parseOptionalArrow().succeeded() &&
4186 parser.parseType(resType).failed())
4187 return mlir::failure();
4189 result.attributes.set(
"asm_flavor", AsmFlavorAttr::get(ctxt, *flavor));
4190 result.attributes.set(
"asm_string", StringAttr::get(ctxt, asmString));
4191 result.attributes.set(
"constraints", StringAttr::get(ctxt, constraints));
4192 result.attributes.set(
"operand_attrs", ArrayAttr::get(ctxt, operandAttrs));
4193 result.getOrAddProperties<InlineAsmOp::Properties>().operands_segments =
4194 parser.getBuilder().getDenseI32ArrayAttr(operandsGroupSizes);
4196 result.addTypes(TypeRange{resType});
4198 return mlir::success();
4205template <
typename ThrowOpTy>
4208 return mlir::success();
4210 if (op.getNumOperands() != 0) {
4211 if (op.getTypeInfo())
4212 return mlir::success();
4213 return op.emitOpError() <<
"'type_info' symbol attribute missing";
4216 return mlir::failure();
4221mlir::LogicalResult cir::TryThrowOp::verify() {
4229LogicalResult cir::AtomicFetchOp::verify() {
4230 if (getBinop() != cir::AtomicFetchKind::Add &&
4231 getBinop() != cir::AtomicFetchKind::Sub &&
4232 getBinop() != cir::AtomicFetchKind::Max &&
4233 getBinop() != cir::AtomicFetchKind::Min &&
4234 !mlir::isa<cir::IntType>(getVal().
getType()))
4235 return emitError(
"only atomic add, sub, max, and min operation could "
4236 "operate on floating-point values");
4244LogicalResult cir::TypeInfoAttr::verify(
4245 ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError,
4246 ::mlir::Type type, ::mlir::ArrayAttr typeInfoData) {
4248 if (cir::ConstRecordAttr::verify(emitError, type, typeInfoData).failed())
4258void cir::TryOp::getSuccessorRegions(
4259 mlir::RegionBranchPoint point,
4262 if (!point.isParent()) {
4263 regions.emplace_back(getOperation());
4267 regions.push_back(mlir::RegionSuccessor(&getTryRegion()));
4271 for (mlir::Region &handlerRegion : this->getHandlerRegions())
4272 regions.push_back(mlir::RegionSuccessor(&handlerRegion));
4275mlir::ValueRange cir::TryOp::getSuccessorInputs(RegionSuccessor successor) {
4276 return successor.isOperation() ? ValueRange(getOperation()->getResults())
4280LogicalResult cir::TryOp::verify() {
4281 mlir::ArrayAttr handlerTypes = getHandlerTypes();
4282 if (!handlerTypes) {
4283 if (!getHandlerRegions().empty())
4285 "handler regions must be empty when no handler types are present");
4289 mlir::MutableArrayRef<mlir::Region> handlerRegions = getHandlerRegions();
4293 if (handlerRegions.size() != handlerTypes.size())
4295 "number of handler regions and handler types must match");
4297 for (
const auto &[typeAttr, handlerRegion] :
4298 llvm::zip(handlerTypes, handlerRegions)) {
4300 mlir::Block &entryBlock = handlerRegion.front();
4301 if (entryBlock.getNumArguments() != 1 ||
4302 !mlir::isa<cir::EhTokenType>(entryBlock.getArgument(0).getType()))
4304 "handler region must have a single '!cir.eh_token' argument");
4307 if (mlir::isa<cir::UnwindAttr>(typeAttr))
4313 if (entryBlock.empty())
4314 return emitOpError(
"catch handler region must not be empty");
4315 mlir::Operation *firstOp = &entryBlock.front();
4316 if (mlir::isa_and_present<cir::ConstructCatchParamOp>(firstOp))
4317 firstOp = firstOp->getNextNode();
4318 if (!firstOp || !mlir::isa<cir::BeginCatchOp>(firstOp))
4320 "catch handler region must start with 'cir.begin_catch'");
4328 mlir::MutableArrayRef<mlir::Region> handlerRegions,
4329 mlir::ArrayAttr handlerTypes) {
4333 for (
const auto [typeIdx, typeAttr] : llvm::enumerate(handlerTypes)) {
4337 if (mlir::isa<cir::CatchAllAttr>(typeAttr)) {
4338 printer <<
"catch all ";
4339 }
else if (mlir::isa<cir::UnwindAttr>(typeAttr)) {
4340 printer <<
"unwind ";
4342 printer <<
"catch [type ";
4343 printer.printAttribute(typeAttr);
4348 mlir::Region ®ion = handlerRegions[typeIdx];
4349 if (!region.empty() && region.front().getNumArguments() > 0) {
4351 printer.printRegionArgument(region.front().getArgument(0));
4355 printer.printRegion(region,
4362 mlir::OpAsmParser &parser,
4364 mlir::ArrayAttr &handlerTypes) {
4366 auto parseCheckedCatcherRegion = [&]() -> mlir::ParseResult {
4367 handlerRegions.emplace_back(
new mlir::Region);
4369 mlir::Region &currRegion = *handlerRegions.back();
4373 if (parser.parseLParen())
4375 mlir::OpAsmParser::Argument arg;
4376 if (parser.parseArgument(arg,
true))
4378 regionArgs.push_back(arg);
4379 if (parser.parseRParen())
4382 mlir::SMLoc regionLoc = parser.getCurrentLocation();
4383 if (parser.parseRegion(currRegion, regionArgs)) {
4384 handlerRegions.clear();
4388 if (currRegion.empty())
4389 return parser.emitError(regionLoc,
"handler region shall not be empty");
4391 if (!(currRegion.back().mightHaveTerminator() &&
4392 currRegion.back().getTerminator()))
4393 return parser.emitError(
4394 regionLoc,
"blocks are expected to be explicitly terminated");
4399 bool hasCatchAll =
false;
4401 while (parser.parseOptionalKeyword(
"catch").succeeded()) {
4402 bool hasLSquare = parser.parseOptionalLSquare().succeeded();
4404 llvm::StringRef attrStr;
4405 if (parser.parseOptionalKeyword(&attrStr, {
"all",
"type"}).failed())
4406 return parser.emitError(parser.getCurrentLocation(),
4407 "expected 'all' or 'type' keyword");
4409 bool isCatchAll = attrStr ==
"all";
4412 return parser.emitError(parser.getCurrentLocation(),
4413 "can't have more than one catch all");
4417 mlir::Attribute exceptionRTTIAttr;
4418 if (!isCatchAll && parser.parseAttribute(exceptionRTTIAttr).failed())
4419 return parser.emitError(parser.getCurrentLocation(),
4420 "expected valid RTTI info attribute");
4422 catcherAttrs.push_back(isCatchAll
4423 ? cir::CatchAllAttr::get(parser.getContext())
4424 : exceptionRTTIAttr);
4426 if (hasLSquare && isCatchAll)
4427 return parser.emitError(parser.getCurrentLocation(),
4428 "catch all dosen't need RTTI info attribute");
4430 if (hasLSquare && parser.parseRSquare().failed())
4431 return parser.emitError(parser.getCurrentLocation(),
4432 "expected `]` after RTTI info attribute");
4434 if (parseCheckedCatcherRegion().failed())
4435 return mlir::failure();
4438 if (parser.parseOptionalKeyword(
"unwind").succeeded()) {
4440 return parser.emitError(parser.getCurrentLocation(),
4441 "unwind can't be used with catch all");
4443 catcherAttrs.push_back(cir::UnwindAttr::get(parser.getContext()));
4444 if (parseCheckedCatcherRegion().failed())
4445 return mlir::failure();
4448 handlerTypes = parser.getBuilder().getArrayAttr(catcherAttrs);
4449 return mlir::success();
4457cir::EhTypeIdOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
4458 Operation *op = symbolTable.lookupNearestSymbolFrom(*
this, getTypeSymAttr());
4459 if (!isa_and_nonnull<GlobalOp>(op))
4460 return emitOpError(
"'")
4461 << getTypeSym() <<
"' does not reference a valid cir.global";
4469LogicalResult cir::LifetimeStartOp::verify() {
4473LogicalResult cir::LifetimeEndOp::verify() {
4481LogicalResult cir::ConstructCatchParamOp::verifySymbolUses(
4482 SymbolTableCollection &symbolTable) {
4483 auto copyFnAttr = getCopyFnAttr();
4487 symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(*
this, getCopyFnAttr());
4489 return emitOpError(
"'")
4490 << *getCopyFn() <<
"' does not reference a valid cir.func";
4492 if (!fn->hasAttr(cir::CIRDialect::getCatchCopyThunkAttrName()))
4493 return emitOpError(
"catch-init copy_fn must be tagged with the ")
4494 << cir::CIRDialect::getCatchCopyThunkAttrName() <<
" attribute";
4496 cir::FuncType fnType = fn.getFunctionType();
4497 if (fnType.getNumInputs() != 2 || !fnType.hasVoidReturn())
4498 return emitOpError(
"catch-init copy_fn must take two pointer arguments and "
4501 if (fnType.getInput(0) != getParamAddr().
getType())
4502 return emitOpError(
"first argument of catch-init copy_fn must match the "
4503 "type of 'param_addr'");
4505 if (fnType.getInput(1) != getParamAddr().
getType())
4507 "second argument of catch-init copy_fn must be a pointer "
4508 "to the catch type");
4519 SmallVectorImpl<Block *> &catchDestinations,
4520 Block *&defaultDestination,
4521 mlir::UnitAttr &defaultIsCatchAll) {
4523 if (parser.parseLSquare())
4527 bool hasCatchAll =
false;
4528 bool hasUnwind =
false;
4531 auto parseHandler = [&]() -> ParseResult {
4533 if (succeeded(parser.parseOptionalKeyword(
"catch_all"))) {
4535 return parser.emitError(parser.getCurrentLocation(),
4536 "duplicate 'catch_all' handler");
4538 return parser.emitError(parser.getCurrentLocation(),
4539 "cannot have both 'catch_all' and 'unwind'");
4542 if (parser.parseColon().failed())
4545 if (parser.parseSuccessor(defaultDestination).failed())
4551 if (succeeded(parser.parseOptionalKeyword(
"unwind"))) {
4553 return parser.emitError(parser.getCurrentLocation(),
4554 "duplicate 'unwind' handler");
4556 return parser.emitError(parser.getCurrentLocation(),
4557 "cannot have both 'catch_all' and 'unwind'");
4560 if (parser.parseColon().failed())
4563 if (parser.parseSuccessor(defaultDestination).failed())
4571 if (parser.parseKeyword(
"catch").failed())
4574 if (parser.parseLParen().failed())
4577 mlir::Attribute catchTypeAttr;
4578 if (parser.parseAttribute(catchTypeAttr).failed())
4580 handlerTypes.push_back(catchTypeAttr);
4582 if (parser.parseRParen().failed())
4585 if (parser.parseColon().failed())
4589 if (parser.parseSuccessor(dest).failed())
4591 catchDestinations.push_back(dest);
4595 if (parser.parseCommaSeparatedList(parseHandler).failed())
4598 if (parser.parseRSquare().failed())
4602 if (!hasCatchAll && !hasUnwind)
4603 return parser.emitError(parser.getCurrentLocation(),
4604 "must have either 'catch_all' or 'unwind' handler");
4607 if (!handlerTypes.empty())
4608 catchTypes = parser.getBuilder().getArrayAttr(handlerTypes);
4611 defaultIsCatchAll = parser.getBuilder().getUnitAttr();
4617 mlir::ArrayAttr catchTypes,
4618 SuccessorRange catchDestinations,
4619 Block *defaultDestination,
4620 mlir::UnitAttr defaultIsCatchAll) {
4628 llvm::zip(catchTypes, catchDestinations),
4631 p.printAttribute(std::get<0>(i));
4633 p.printSuccessor(std::get<1>(i));
4645 if (defaultIsCatchAll)
4646 p <<
" catch_all : ";
4649 p.printSuccessor(defaultDestination);
4659#define GET_OP_CLASSES
4660#include "clang/CIR/Dialect/IR/CIROps.cpp.inc"
static const MemRegion * getRegion(const CallEvent &Call, const MutexDescriptor &Descriptor, bool IsLock)
static void printEhDispatchDestinations(OpAsmPrinter &p, cir::EhDispatchOp op, mlir::ArrayAttr catchTypes, SuccessorRange catchDestinations, Block *defaultDestination, mlir::UnitAttr defaultIsCatchAll)
static mlir::LogicalResult checkReturnAndFunction(cir::ReturnOp op, cir::FuncOp function)
static bool isCirFunctionPointerType(mlir::Type ty)
static LogicalResult verifyMemberPtrCast(Operation *op, mlir::Value src, mlir::Type resultTy)
static mlir::ParseResult parseCallCommon(mlir::OpAsmParser &parser, mlir::OperationState &result, bool hasDestinationBlocks=false)
static bool isIntOrBoolCast(cir::CastOp op)
static ParseResult parseAssumeBundle(OpAsmParser &p, cir::AssumeBundleKindAttr &bundleKindAttr, llvm::SmallVector< mlir::OpAsmParser::UnresolvedOperand, 4 > &bundleArgs, llvm::SmallVector< mlir::Type, 1 > &bundleArgTypes)
static ParseResult parseEhDispatchDestinations(OpAsmParser &parser, mlir::ArrayAttr &catchTypes, SmallVectorImpl< Block * > &catchDestinations, Block *&defaultDestination, mlir::UnitAttr &defaultIsCatchAll)
static void printConstant(OpAsmPrinter &p, Attribute value)
static mlir::ParseResult parseOmittedTerminatorRegion(mlir::OpAsmParser &parser, mlir::Region ®ion)
static void printAssumeBundle(OpAsmPrinter &p, cir::AssumeOp op, cir::AssumeBundleKindAttr kindAttr, OperandRange bundleArgs, TypeRange bundleArgTypes)
ParseResult parseInlineKindAttr(OpAsmParser &parser, cir::InlineKindAttr &inlineKindAttr)
void printInlineKindAttr(OpAsmPrinter &p, cir::InlineKindAttr inlineKindAttr)
static ParseResult parseSwitchFlatOpCases(OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues, SmallVectorImpl< Block * > &caseDestinations, SmallVectorImpl< llvm::SmallVector< OpAsmParser::UnresolvedOperand > > &caseOperands, SmallVectorImpl< llvm::SmallVector< Type > > &caseOperandTypes)
<cases> ::= [ (case (, case )* )?
void printGlobalAddressSpaceValue(mlir::AsmPrinter &printer, cir::GlobalOp op, mlir::ptr::MemorySpaceAttrInterface attr)
static void printCallCommon(mlir::Operation *op, mlir::FlatSymbolRefAttr calleeSym, mlir::Value indirectCallee, mlir::OpAsmPrinter &printer, bool isNothrow, cir::SideEffect sideEffect, ArrayAttr argAttrs, ArrayAttr resAttrs, mlir::Block *normalDest=nullptr, mlir::Block *unwindDest=nullptr)
static LogicalResult verifyCallCommInSymbolUses(mlir::Operation *op, SymbolTableCollection &symbolTable)
static LogicalResult ensureRegionTerm(OpAsmParser &parser, Region ®ion, SMLoc errLoc)
static ParseResult parseGlobalOpTypeAndInitialValue(OpAsmParser &parser, TypeAttr &typeAttr, Attribute &initialValueAttr, mlir::Region &ctorRegion, mlir::Region &dtorRegion)
void printIndirectBrOpSucessors(OpAsmPrinter &p, cir::IndirectBrOp op, Type flagType, SuccessorRange succs, OperandRangeRange succOperands, const TypeRangeRange &succOperandsTypes)
static OpFoldResult foldUnaryBitOp(mlir::Attribute inputAttr, llvm::function_ref< llvm::APInt(const llvm::APInt &)> func, bool poisonZero=false)
static llvm::StringRef getLinkageAttrNameString()
Returns the name used for the linkage attribute.
static RetTy parseOptionalCIRKeyword(AsmParser &parser, EnumTy defaultValue)
Parse an enum from the keyword, or default to the provided default value.
mlir::OptionalParseResult parseGlobalAddressSpaceValue(mlir::AsmParser &p, mlir::ptr::MemorySpaceAttrInterface &attr)
static void printSwitchFlatOpCases(OpAsmPrinter &p, cir::SwitchFlatOp op, Type flagType, mlir::ArrayAttr caseValues, SuccessorRange caseDestinations, OperandRangeRange caseOperands, const TypeRangeRange &caseOperandTypes)
static LogicalResult verifyProducedBy(Operation *op, Value operand, StringRef operandName)
static mlir::ParseResult parseTryCallDestinations(mlir::OpAsmParser &parser, mlir::OperationState &result)
static void printGlobalOpTypeAndInitialValue(OpAsmPrinter &p, cir::GlobalOp op, TypeAttr type, Attribute initAttr, mlir::Region &ctorRegion, mlir::Region &dtorRegion)
static ParseResult parseCIRKeyword(AsmParser &parser, RetTy &result)
Parse an enum from the keyword, return failure if the keyword is not found.
static Value tryFoldCastChain(cir::CastOp op)
static void printTryHandlerRegions(mlir::OpAsmPrinter &printer, cir::TryOp op, mlir::MutableArrayRef< mlir::Region > handlerRegions, mlir::ArrayAttr handlerTypes)
ParseResult parseIndirectBrOpSucessors(OpAsmParser &parser, Type &flagType, SmallVectorImpl< Block * > &succOperandBlocks, SmallVectorImpl< SmallVector< OpAsmParser::UnresolvedOperand > > &succOperands, SmallVectorImpl< SmallVector< Type > > &succOperandsTypes)
static bool omitRegionTerm(mlir::Region &r)
static void printOmittedTerminatorRegion(mlir::OpAsmPrinter &printer, cir::ScopeOp &op, mlir::Region ®ion)
static ParseResult parseConstantValue(OpAsmParser &parser, mlir::Attribute &valueAttr)
static LogicalResult verifyArrayCtorDtor(Op op)
static mlir::LogicalResult verifyThrowOpImpl(ThrowOpTy op)
static LogicalResult checkConstantTypes(mlir::Operation *op, mlir::Type opType, mlir::Attribute attrType)
static mlir::ParseResult parseTryHandlerRegions(mlir::OpAsmParser &parser, llvm::SmallVectorImpl< std::unique_ptr< mlir::Region > > &handlerRegions, mlir::ArrayAttr &handlerTypes)
#define REGISTER_ENUM_TYPE(Ty)
static int parseOptionalKeywordAlternative(AsmParser &parser, ArrayRef< llvm::StringRef > keywords)
llvm::function_ref< void(mlir::OpBuilder &, mlir::Location)> BuilderCallbackRef
llvm::function_ref< void( mlir::OpBuilder &, mlir::Location, mlir::OperationState &)> BuilderOpStateCallbackRef
static std::optional< NonLoc > getIndex(ProgramStateRef State, const ElementRegion *ER, CharKind CK)
static Decl::Kind getKind(const Decl *D)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a an optional score condition
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
void buildTerminatedBody(mlir::OpBuilder &builder, mlir::Location loc)
mlir::ptr::MemorySpaceAttrInterface normalizeDefaultAddressSpace(mlir::ptr::MemorySpaceAttrInterface addrSpace)
Normalize LangAddressSpace::Default to null (empty attribute).
const AstTypeMatcher< BuiltinType > builtinType
const internal::VariadicAllOfMatcher< Attr > attr
const AstTypeMatcher< RecordType > recordType
StringRef getName(const HeaderType T)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
static bool memberFuncPtrCast()
static bool opCallCallConv()
static bool opScopeCleanupRegion()
static bool supportIFuncAttr()