19#include "mlir/IR/Attributes.h"
20#include "mlir/IR/DialectImplementation.h"
21#include "mlir/Interfaces/ControlFlowInterfaces.h"
22#include "mlir/Interfaces/FunctionImplementation.h"
23#include "mlir/Support/LLVM.h"
25#include "clang/CIR/Dialect/IR/CIROpsDialect.cpp.inc"
26#include "clang/CIR/Dialect/IR/CIROpsEnums.cpp.inc"
28#include "llvm/ADT/SetOperations.h"
29#include "llvm/ADT/SmallSet.h"
30#include "llvm/Support/LogicalResult.h"
39struct CIROpAsmDialectInterface :
public OpAsmDialectInterface {
40 using OpAsmDialectInterface::OpAsmDialectInterface;
42 AliasResult getAlias(Type type, raw_ostream &os)
const final {
43 if (
auto recordType = dyn_cast<cir::RecordType>(type)) {
46 os <<
"rec_anon_" <<
recordType.getKindAsStr();
48 os <<
"rec_" << nameAttr.getValue();
49 return AliasResult::OverridableAlias;
51 if (
auto intType = dyn_cast<cir::IntType>(type)) {
54 unsigned width = intType.getWidth();
55 if (width < 8 || !llvm::isPowerOf2_32(width))
56 return AliasResult::NoAlias;
57 os << intType.getAlias();
58 return AliasResult::OverridableAlias;
60 if (
auto voidType = dyn_cast<cir::VoidType>(type)) {
61 os << voidType.getAlias();
62 return AliasResult::OverridableAlias;
65 return AliasResult::NoAlias;
68 AliasResult getAlias(Attribute attr, raw_ostream &os)
const final {
69 if (
auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr)) {
70 os << (boolAttr.getValue() ?
"true" :
"false");
71 return AliasResult::FinalAlias;
73 if (
auto bitfield = mlir::dyn_cast<cir::BitfieldInfoAttr>(attr)) {
74 os <<
"bfi_" << bitfield.getName().str();
75 return AliasResult::FinalAlias;
77 if (
auto dynCastInfoAttr = mlir::dyn_cast<cir::DynamicCastInfoAttr>(attr)) {
78 os << dynCastInfoAttr.getAlias();
79 return AliasResult::FinalAlias;
81 return AliasResult::NoAlias;
86void cir::CIRDialect::initialize() {
91#include "clang/CIR/Dialect/IR/CIROps.cpp.inc"
93 addInterfaces<CIROpAsmDialectInterface>();
96Operation *cir::CIRDialect::materializeConstant(mlir::OpBuilder &builder,
97 mlir::Attribute value,
100 return cir::ConstantOp::create(builder, loc, type,
101 mlir::cast<mlir::TypedAttr>(value));
113 for (
auto en : llvm::enumerate(keywords)) {
114 if (succeeded(parser.parseOptionalKeyword(en.value())))
121template <
typename Ty>
struct EnumTraits {};
123#define REGISTER_ENUM_TYPE(Ty) \
124 template <> struct EnumTraits<cir::Ty> { \
125 static llvm::StringRef stringify(cir::Ty value) { \
126 return stringify##Ty(value); \
128 static unsigned getMaxEnumVal() { return cir::getMaxEnumValFor##Ty(); } \
139template <
typename EnumTy,
typename RetTy = EnumTy>
142 for (
unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
143 names.push_back(EnumTraits<EnumTy>::stringify(
static_cast<EnumTy
>(i)));
147 return static_cast<RetTy
>(defaultValue);
148 return static_cast<RetTy
>(index);
152template <
typename EnumTy,
typename RetTy = EnumTy>
155 for (
unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
156 names.push_back(EnumTraits<EnumTy>::stringify(
static_cast<EnumTy
>(i)));
161 result =
static_cast<RetTy
>(index);
169 Location eLoc = parser.getEncodedSourceLoc(parser.getCurrentLocation());
170 OpBuilder builder(parser.getBuilder().getContext());
175 builder.createBlock(®ion);
177 Block &block = region.back();
179 if (!block.empty() && block.back().hasTrait<OpTrait::IsTerminator>())
183 if (!region.hasOneBlock())
184 return parser.emitError(errLoc,
185 "multi-block region must not omit terminator");
188 builder.setInsertionPointToEnd(&block);
189 cir::YieldOp::create(builder, eLoc);
195 const auto singleNonEmptyBlock = r.hasOneBlock() && !r.back().empty();
196 const auto yieldsNothing = [&r]() {
197 auto y = dyn_cast<cir::YieldOp>(r.back().getTerminator());
198 return y && y.getArgs().empty();
200 return singleNonEmptyBlock && yieldsNothing();
204 cir::VisibilityAttr &visibility) {
205 switch (visibility.getValue()) {
206 case cir::VisibilityKind::Hidden:
209 case cir::VisibilityKind::Protected:
210 printer <<
"protected";
212 case cir::VisibilityKind::Default:
218 cir::VisibilityKind visibilityKind =
220 visibility = cir::VisibilityAttr::get(parser.getContext(), visibilityKind);
228 cir::InlineKindAttr &inlineKindAttr) {
230 static constexpr llvm::StringRef keywords[] = {
"no_inline",
"always_inline",
234 llvm::StringRef keyword;
235 if (parser.parseOptionalKeyword(&keyword, keywords).failed()) {
241 auto inlineKindResult = ::cir::symbolizeEnum<::cir::InlineKind>(keyword);
242 if (!inlineKindResult) {
243 return parser.emitError(parser.getCurrentLocation(),
"expected one of [")
245 <<
"] for inlineKind, got: " << keyword;
249 ::cir::InlineKindAttr::get(parser.getContext(), *inlineKindResult);
254 if (inlineKindAttr) {
255 p <<
" " << stringifyInlineKind(inlineKindAttr.getValue());
263 mlir::Region ®ion) {
264 auto regionLoc = parser.getCurrentLocation();
265 if (parser.parseRegion(region))
274 mlir::Region ®ion) {
275 printer.printRegion(region,
284void cir::AllocaOp::build(mlir::OpBuilder &odsBuilder,
285 mlir::OperationState &odsState, mlir::Type addr,
286 mlir::Type allocaType, llvm::StringRef name,
287 mlir::IntegerAttr alignment) {
288 odsState.addAttribute(getAllocaTypeAttrName(odsState.name),
289 mlir::TypeAttr::get(allocaType));
290 odsState.addAttribute(getNameAttrName(odsState.name),
291 odsBuilder.getStringAttr(name));
293 odsState.addAttribute(getAlignmentAttrName(odsState.name), alignment);
295 odsState.addTypes(addr);
302LogicalResult cir::BreakOp::verify() {
304 if (!getOperation()->getParentOfType<LoopOpInterface>() &&
305 !getOperation()->getParentOfType<SwitchOp>())
306 return emitOpError(
"must be within a loop");
318void cir::ConditionOp::getSuccessorRegions(
324 if (
auto loopOp = dyn_cast<LoopOpInterface>(getOperation()->getParentOp())) {
325 regions.emplace_back(&loopOp.getBody(), loopOp.getBody().getArguments());
326 regions.emplace_back(getOperation(), loopOp->getResults());
330 auto await = cast<AwaitOp>(getOperation()->getParentOp());
331 regions.emplace_back(&await.getResume(), await.getResume().getArguments());
332 regions.emplace_back(&await.getSuspend(), await.getSuspend().getArguments());
336cir::ConditionOp::getMutableSuccessorOperands(RegionSuccessor point) {
338 return MutableOperandRange(getOperation(), 0, 0);
341LogicalResult cir::ConditionOp::verify() {
342 if (!isa<LoopOpInterface, AwaitOp>(getOperation()->getParentOp()))
343 return emitOpError(
"condition must be within a conditional region");
352 mlir::Attribute attrType) {
353 if (isa<cir::ConstPtrAttr>(attrType)) {
354 if (!mlir::isa<cir::PointerType>(opType))
355 return op->emitOpError(
356 "pointer constant initializing a non-pointer type");
360 if (isa<cir::DataMemberAttr>(attrType)) {
366 if (isa<cir::ZeroAttr>(attrType)) {
367 if (isa<cir::RecordType, cir::ArrayType, cir::VectorType, cir::ComplexType>(
370 return op->emitOpError(
371 "zero expects struct, array, vector, or complex type");
374 if (mlir::isa<cir::UndefAttr>(attrType)) {
375 if (!mlir::isa<cir::VoidType>(opType))
377 return op->emitOpError(
"undef expects non-void type");
380 if (mlir::isa<cir::BoolAttr>(attrType)) {
381 if (!mlir::isa<cir::BoolType>(opType))
382 return op->emitOpError(
"result type (")
383 << opType <<
") must be '!cir.bool' for '" << attrType <<
"'";
387 if (mlir::isa<cir::IntAttr, cir::FPAttr>(attrType)) {
388 auto at = cast<TypedAttr>(attrType);
389 if (at.getType() != opType) {
390 return op->emitOpError(
"result type (")
391 << opType <<
") does not match value type (" << at.getType()
397 if (mlir::isa<cir::ConstArrayAttr, cir::ConstVectorAttr,
398 cir::ConstComplexAttr, cir::ConstRecordAttr,
399 cir::GlobalViewAttr, cir::PoisonAttr, cir::TypeInfoAttr,
400 cir::VTableAttr>(attrType))
403 assert(isa<TypedAttr>(attrType) &&
"What else could we be looking at here?");
404 return op->emitOpError(
"global with type ")
405 << cast<TypedAttr>(attrType).getType() <<
" not yet supported";
408LogicalResult cir::ConstantOp::verify() {
415OpFoldResult cir::ConstantOp::fold(FoldAdaptor ) {
423LogicalResult cir::ContinueOp::verify() {
424 if (!getOperation()->getParentOfType<LoopOpInterface>())
425 return emitOpError(
"must be within a loop");
433LogicalResult cir::CastOp::verify() {
434 mlir::Type resType =
getType();
435 mlir::Type srcType = getSrc().getType();
439 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
440 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
441 if (srcPtrTy && resPtrTy && (
getKind() != cir::CastKind::address_space))
442 if (srcPtrTy.getAddrSpace() != resPtrTy.getAddrSpace()) {
443 return emitOpError() <<
"result type address space does not match the "
444 "address space of the operand";
447 if (mlir::isa<cir::VectorType>(srcType) &&
448 mlir::isa<cir::VectorType>(resType)) {
451 srcType = mlir::dyn_cast<cir::VectorType>(srcType).getElementType();
452 resType = mlir::dyn_cast<cir::VectorType>(resType).getElementType();
456 case cir::CastKind::int_to_bool: {
457 if (!mlir::isa<cir::BoolType>(resType))
458 return emitOpError() <<
"requires !cir.bool type for result";
459 if (!mlir::isa<cir::IntType>(srcType))
460 return emitOpError() <<
"requires !cir.int type for source";
463 case cir::CastKind::ptr_to_bool: {
464 if (!mlir::isa<cir::BoolType>(resType))
465 return emitOpError() <<
"requires !cir.bool type for result";
466 if (!mlir::isa<cir::PointerType>(srcType))
467 return emitOpError() <<
"requires !cir.ptr type for source";
470 case cir::CastKind::integral: {
471 if (!mlir::isa<cir::IntType>(resType))
472 return emitOpError() <<
"requires !cir.int type for result";
473 if (!mlir::isa<cir::IntType>(srcType))
474 return emitOpError() <<
"requires !cir.int type for source";
477 case cir::CastKind::array_to_ptrdecay: {
478 const auto arrayPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
479 const auto flatPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
480 if (!arrayPtrTy || !flatPtrTy)
481 return emitOpError() <<
"requires !cir.ptr type for source and result";
486 case cir::CastKind::bitcast: {
488 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
489 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
491 if (srcPtrTy && resPtrTy) {
497 case cir::CastKind::floating: {
498 if (!mlir::isa<cir::FPTypeInterface>(srcType) ||
499 !mlir::isa<cir::FPTypeInterface>(resType))
500 return emitOpError() <<
"requires !cir.float type for source and result";
503 case cir::CastKind::float_to_int: {
504 if (!mlir::isa<cir::FPTypeInterface>(srcType))
505 return emitOpError() <<
"requires !cir.float type for source";
506 if (!mlir::dyn_cast<cir::IntType>(resType))
507 return emitOpError() <<
"requires !cir.int type for result";
510 case cir::CastKind::int_to_ptr: {
511 if (!mlir::dyn_cast<cir::IntType>(srcType))
512 return emitOpError() <<
"requires !cir.int type for source";
513 if (!mlir::dyn_cast<cir::PointerType>(resType))
514 return emitOpError() <<
"requires !cir.ptr type for result";
517 case cir::CastKind::ptr_to_int: {
518 if (!mlir::dyn_cast<cir::PointerType>(srcType))
519 return emitOpError() <<
"requires !cir.ptr type for source";
520 if (!mlir::dyn_cast<cir::IntType>(resType))
521 return emitOpError() <<
"requires !cir.int type for result";
524 case cir::CastKind::float_to_bool: {
525 if (!mlir::isa<cir::FPTypeInterface>(srcType))
526 return emitOpError() <<
"requires !cir.float type for source";
527 if (!mlir::isa<cir::BoolType>(resType))
528 return emitOpError() <<
"requires !cir.bool type for result";
531 case cir::CastKind::bool_to_int: {
532 if (!mlir::isa<cir::BoolType>(srcType))
533 return emitOpError() <<
"requires !cir.bool type for source";
534 if (!mlir::isa<cir::IntType>(resType))
535 return emitOpError() <<
"requires !cir.int type for result";
538 case cir::CastKind::int_to_float: {
539 if (!mlir::isa<cir::IntType>(srcType))
540 return emitOpError() <<
"requires !cir.int type for source";
541 if (!mlir::isa<cir::FPTypeInterface>(resType))
542 return emitOpError() <<
"requires !cir.float type for result";
545 case cir::CastKind::bool_to_float: {
546 if (!mlir::isa<cir::BoolType>(srcType))
547 return emitOpError() <<
"requires !cir.bool type for source";
548 if (!mlir::isa<cir::FPTypeInterface>(resType))
549 return emitOpError() <<
"requires !cir.float type for result";
552 case cir::CastKind::address_space: {
553 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
554 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
555 if (!srcPtrTy || !resPtrTy)
556 return emitOpError() <<
"requires !cir.ptr type for source and result";
557 if (srcPtrTy.getPointee() != resPtrTy.getPointee())
558 return emitOpError() <<
"requires two types differ in addrspace only";
561 case cir::CastKind::float_to_complex: {
562 if (!mlir::isa<cir::FPTypeInterface>(srcType))
563 return emitOpError() <<
"requires !cir.float type for source";
564 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
566 return emitOpError() <<
"requires !cir.complex type for result";
567 if (srcType != resComplexTy.getElementType())
568 return emitOpError() <<
"requires source type match result element type";
571 case cir::CastKind::int_to_complex: {
572 if (!mlir::isa<cir::IntType>(srcType))
573 return emitOpError() <<
"requires !cir.int type for source";
574 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
576 return emitOpError() <<
"requires !cir.complex type for result";
577 if (srcType != resComplexTy.getElementType())
578 return emitOpError() <<
"requires source type match result element type";
581 case cir::CastKind::float_complex_to_real: {
582 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
584 return emitOpError() <<
"requires !cir.complex type for source";
585 if (!mlir::isa<cir::FPTypeInterface>(resType))
586 return emitOpError() <<
"requires !cir.float type for result";
587 if (srcComplexTy.getElementType() != resType)
588 return emitOpError() <<
"requires source element type match result type";
591 case cir::CastKind::int_complex_to_real: {
592 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
594 return emitOpError() <<
"requires !cir.complex type for source";
595 if (!mlir::isa<cir::IntType>(resType))
596 return emitOpError() <<
"requires !cir.int type for result";
597 if (srcComplexTy.getElementType() != resType)
598 return emitOpError() <<
"requires source element type match result type";
601 case cir::CastKind::float_complex_to_bool: {
602 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
603 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
605 <<
"requires floating point !cir.complex type for source";
606 if (!mlir::isa<cir::BoolType>(resType))
607 return emitOpError() <<
"requires !cir.bool type for result";
610 case cir::CastKind::int_complex_to_bool: {
611 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
612 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
614 <<
"requires floating point !cir.complex type for source";
615 if (!mlir::isa<cir::BoolType>(resType))
616 return emitOpError() <<
"requires !cir.bool type for result";
619 case cir::CastKind::float_complex: {
620 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
621 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
623 <<
"requires floating point !cir.complex type for source";
624 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
625 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
627 <<
"requires floating point !cir.complex type for result";
630 case cir::CastKind::float_complex_to_int_complex: {
631 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
632 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
634 <<
"requires floating point !cir.complex type for source";
635 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
636 if (!resComplexTy || !resComplexTy.isIntegerComplex())
637 return emitOpError() <<
"requires integer !cir.complex type for result";
640 case cir::CastKind::int_complex: {
641 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
642 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
643 return emitOpError() <<
"requires integer !cir.complex type for source";
644 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
645 if (!resComplexTy || !resComplexTy.isIntegerComplex())
646 return emitOpError() <<
"requires integer !cir.complex type for result";
649 case cir::CastKind::int_complex_to_float_complex: {
650 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
651 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
652 return emitOpError() <<
"requires integer !cir.complex type for source";
653 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
654 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
656 <<
"requires floating point !cir.complex type for result";
660 llvm_unreachable(
"Unknown CastOp kind?");
665 auto kind = op.getKind();
666 return kind == cir::CastKind::bool_to_int ||
667 kind == cir::CastKind::int_to_bool || kind == cir::CastKind::integral;
671 cir::CastOp head = op, tail = op;
677 op = head.getSrc().getDefiningOp<cir::CastOp>();
685 if (head.getKind() == cir::CastKind::bool_to_int &&
686 tail.getKind() == cir::CastKind::int_to_bool)
687 return head.getSrc();
692 if (head.getKind() == cir::CastKind::int_to_bool &&
693 tail.getKind() == cir::CastKind::int_to_bool)
694 return head.getResult();
699OpFoldResult cir::CastOp::fold(FoldAdaptor adaptor) {
700 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getSrc())) {
702 return cir::PoisonAttr::get(getContext(),
getType());
707 case cir::CastKind::integral: {
709 auto foldOrder = getSrc().getDefiningOp()->fold(foldResults);
710 if (foldOrder.succeeded() && mlir::isa<mlir::Attribute>(foldResults[0]))
711 return mlir::cast<mlir::Attribute>(foldResults[0]);
714 case cir::CastKind::bitcast:
715 case cir::CastKind::address_space:
716 case cir::CastKind::float_complex:
717 case cir::CastKind::int_complex: {
731 if (
auto srcConst = getSrc().getDefiningOp<cir::ConstantOp>()) {
733 case cir::CastKind::integral: {
734 mlir::Type srcTy = getSrc().getType();
736 assert(mlir::isa<cir::VectorType>(srcTy) ==
737 mlir::isa<cir::VectorType>(
getType()));
738 if (mlir::isa<cir::VectorType>(srcTy))
741 auto srcIntTy = mlir::cast<cir::IntType>(srcTy);
742 auto dstIntTy = mlir::cast<cir::IntType>(
getType());
745 ? srcConst.getIntValue().sextOrTrunc(dstIntTy.getWidth())
746 : srcConst.getIntValue().zextOrTrunc(dstIntTy.getWidth());
747 return cir::IntAttr::get(dstIntTy, newVal);
760mlir::OperandRange cir::CallOp::getArgOperands() {
762 return getArgs().drop_front(1);
766mlir::MutableOperandRange cir::CallOp::getArgOperandsMutable() {
767 mlir::MutableOperandRange args = getArgsMutable();
769 return args.slice(1, args.size() - 1);
773mlir::Value cir::CallOp::getIndirectCall() {
774 assert(isIndirect());
775 return getOperand(0);
779Value cir::CallOp::getArgOperand(
unsigned i) {
782 return getOperand(i);
786unsigned cir::CallOp::getNumArgOperands() {
788 return this->getOperation()->getNumOperands() - 1;
789 return this->getOperation()->getNumOperands();
792static mlir::ParseResult
794 mlir::OperationState &result) {
795 mlir::Block *normalDestSuccessor;
796 if (parser.parseSuccessor(normalDestSuccessor))
797 return mlir::failure();
799 if (parser.parseComma())
800 return mlir::failure();
802 mlir::Block *unwindDestSuccessor;
803 if (parser.parseSuccessor(unwindDestSuccessor))
804 return mlir::failure();
806 result.addSuccessors(normalDestSuccessor);
807 result.addSuccessors(unwindDestSuccessor);
808 return mlir::success();
812 mlir::OperationState &result,
813 bool hasDestinationBlocks =
false) {
816 mlir::FlatSymbolRefAttr calleeAttr;
821 .parseOptionalAttribute(calleeAttr, CIRDialect::getCalleeAttrName(),
824 OpAsmParser::UnresolvedOperand indirectVal;
826 if (parser.parseOperand(indirectVal).failed())
828 ops.push_back(indirectVal);
831 if (parser.parseLParen())
832 return mlir::failure();
834 opsLoc = parser.getCurrentLocation();
835 if (parser.parseOperandList(ops))
836 return mlir::failure();
837 if (parser.parseRParen())
838 return mlir::failure();
840 if (hasDestinationBlocks &&
842 return ::mlir::failure();
845 if (parser.parseOptionalKeyword(
"nothrow").succeeded())
846 result.addAttribute(CIRDialect::getNoThrowAttrName(),
847 mlir::UnitAttr::get(parser.getContext()));
849 if (parser.parseOptionalKeyword(
"side_effect").succeeded()) {
850 if (parser.parseLParen().failed())
852 cir::SideEffect sideEffect;
855 if (parser.parseRParen().failed())
857 auto attr = cir::SideEffectAttr::get(parser.getContext(), sideEffect);
858 result.addAttribute(CIRDialect::getSideEffectAttrName(), attr);
861 if (parser.parseOptionalAttrDict(result.attributes))
862 return ::mlir::failure();
864 if (parser.parseColon())
865 return ::mlir::failure();
867 mlir::FunctionType opsFnTy;
868 if (parser.parseType(opsFnTy))
869 return mlir::failure();
871 allResultTypes = opsFnTy.getResults();
872 result.addTypes(allResultTypes);
874 if (parser.resolveOperands(ops, opsFnTy.getInputs(), opsLoc, result.operands))
875 return mlir::failure();
877 return mlir::success();
881 mlir::FlatSymbolRefAttr calleeSym,
882 mlir::Value indirectCallee,
883 mlir::OpAsmPrinter &printer,
bool isNothrow,
884 cir::SideEffect sideEffect,
885 mlir::Block *normalDest =
nullptr,
886 mlir::Block *unwindDest =
nullptr) {
889 auto callLikeOp = mlir::cast<cir::CIRCallOpInterface>(op);
890 auto ops = callLikeOp.getArgOperands();
894 printer.printAttributeWithoutType(calleeSym);
897 assert(indirectCallee);
898 printer << indirectCallee;
901 printer <<
"(" << ops <<
")";
904 assert(unwindDest &&
"expected two successors");
905 auto tryCall = cast<cir::TryCallOp>(op);
906 printer <<
' ' << tryCall.getNormalDest();
909 printer << tryCall.getUnwindDest();
913 printer <<
" nothrow";
915 if (sideEffect != cir::SideEffect::All) {
916 printer <<
" side_effect(";
917 printer << stringifySideEffect(sideEffect);
922 CIRDialect::getCalleeAttrName(), CIRDialect::getNoThrowAttrName(),
923 CIRDialect::getSideEffectAttrName(),
924 CIRDialect::getOperandSegmentSizesAttrName()};
925 printer.printOptionalAttrDict(op->getAttrs(), elidedAttrs);
927 printer.printFunctionalType(op->getOperands().getTypes(),
928 op->getResultTypes());
931mlir::ParseResult cir::CallOp::parse(mlir::OpAsmParser &parser,
932 mlir::OperationState &result) {
936void cir::CallOp::print(mlir::OpAsmPrinter &p) {
937 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() :
nullptr;
938 cir::SideEffect sideEffect = getSideEffect();
939 printCallCommon(*
this, getCalleeAttr(), indirectCallee, p, getNothrow(),
945 SymbolTableCollection &symbolTable) {
947 op->getAttrOfType<FlatSymbolRefAttr>(CIRDialect::getCalleeAttrName());
950 return mlir::success();
953 auto fn = symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(op, fnAttr);
955 return op->emitOpError() <<
"'" << fnAttr.getValue()
956 <<
"' does not reference a valid function";
958 auto callIf = dyn_cast<cir::CIRCallOpInterface>(op);
959 assert(callIf &&
"expected CIR call interface to be always available");
963 auto fnType = fn.getFunctionType();
964 if (!fn.getNoProto()) {
965 unsigned numCallOperands = callIf.getNumArgOperands();
966 unsigned numFnOpOperands = fnType.getNumInputs();
968 if (!fnType.isVarArg() && numCallOperands != numFnOpOperands)
969 return op->emitOpError(
"incorrect number of operands for callee");
970 if (fnType.isVarArg() && numCallOperands < numFnOpOperands)
971 return op->emitOpError(
"too few operands for callee");
973 for (
unsigned i = 0, e = numFnOpOperands; i != e; ++i)
974 if (callIf.getArgOperand(i).getType() != fnType.getInput(i))
975 return op->emitOpError(
"operand type mismatch: expected operand type ")
976 << fnType.getInput(i) <<
", but provided "
977 << op->getOperand(i).getType() <<
" for operand number " << i;
983 if (fnType.hasVoidReturn() && op->getNumResults() != 0)
984 return op->emitOpError(
"callee returns void but call has results");
987 if (!fnType.hasVoidReturn() && op->getNumResults() != 1)
988 return op->emitOpError(
"incorrect number of results for callee");
991 if (!fnType.hasVoidReturn() &&
992 op->getResultTypes().front() != fnType.getReturnType()) {
993 return op->emitOpError(
"result type mismatch: expected ")
994 << fnType.getReturnType() <<
", but provided "
995 << op->getResult(0).getType();
998 return mlir::success();
1002cir::CallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1010mlir::OperandRange cir::TryCallOp::getArgOperands() {
1012 return getArgs().drop_front(1);
1016mlir::MutableOperandRange cir::TryCallOp::getArgOperandsMutable() {
1017 mlir::MutableOperandRange args = getArgsMutable();
1019 return args.slice(1, args.size() - 1);
1023mlir::Value cir::TryCallOp::getIndirectCall() {
1024 assert(isIndirect());
1025 return getOperand(0);
1029Value cir::TryCallOp::getArgOperand(
unsigned i) {
1032 return getOperand(i);
1036unsigned cir::TryCallOp::getNumArgOperands() {
1038 return this->getOperation()->getNumOperands() - 1;
1039 return this->getOperation()->getNumOperands();
1043cir::TryCallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1047mlir::ParseResult cir::TryCallOp::parse(mlir::OpAsmParser &parser,
1048 mlir::OperationState &result) {
1052void cir::TryCallOp::print(::mlir::OpAsmPrinter &p) {
1053 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() :
nullptr;
1054 cir::SideEffect sideEffect = getSideEffect();
1055 printCallCommon(*
this, getCalleeAttr(), indirectCallee, p, getNothrow(),
1056 sideEffect, getNormalDest(), getUnwindDest());
1064 cir::FuncOp function) {
1066 if (op.getNumOperands() > 1)
1067 return op.emitOpError() <<
"expects at most 1 return operand";
1070 auto expectedTy = function.getFunctionType().getReturnType();
1072 (op.getNumOperands() == 0 ? cir::VoidType::get(op.getContext())
1073 : op.getOperand(0).getType());
1074 if (actualTy != expectedTy)
1075 return op.emitOpError() <<
"returns " << actualTy
1076 <<
" but enclosing function returns " << expectedTy;
1078 return mlir::success();
1081mlir::LogicalResult cir::ReturnOp::verify() {
1084 auto *fnOp = getOperation()->getParentOp();
1085 while (!isa<cir::FuncOp>(fnOp))
1086 fnOp = fnOp->getParentOp();
1099ParseResult cir::IfOp::parse(OpAsmParser &parser, OperationState &result) {
1101 result.regions.reserve(2);
1102 Region *thenRegion = result.addRegion();
1103 Region *elseRegion = result.addRegion();
1105 mlir::Builder &builder = parser.getBuilder();
1106 OpAsmParser::UnresolvedOperand cond;
1107 Type boolType = cir::BoolType::get(builder.getContext());
1109 if (parser.parseOperand(cond) ||
1110 parser.resolveOperand(cond, boolType, result.operands))
1114 mlir::SMLoc parseThenLoc = parser.getCurrentLocation();
1115 if (parser.parseRegion(*thenRegion, {}, {}))
1122 if (!parser.parseOptionalKeyword(
"else")) {
1123 mlir::SMLoc parseElseLoc = parser.getCurrentLocation();
1124 if (parser.parseRegion(*elseRegion, {}, {}))
1131 if (parser.parseOptionalAttrDict(result.attributes))
1136void cir::IfOp::print(OpAsmPrinter &p) {
1137 p <<
" " << getCondition() <<
" ";
1138 mlir::Region &thenRegion = this->getThenRegion();
1139 p.printRegion(thenRegion,
1144 mlir::Region &elseRegion = this->getElseRegion();
1145 if (!elseRegion.empty()) {
1147 p.printRegion(elseRegion,
1152 p.printOptionalAttrDict(getOperation()->getAttrs());
1158 cir::YieldOp::create(builder, loc);
1166void cir::IfOp::getSuccessorRegions(mlir::RegionBranchPoint point,
1167 SmallVectorImpl<RegionSuccessor> ®ions) {
1169 if (!point.isParent()) {
1171 RegionSuccessor(getOperation(), getOperation()->getResults()));
1176 Region *elseRegion = &this->getElseRegion();
1177 if (elseRegion->empty())
1178 elseRegion =
nullptr;
1181 regions.push_back(RegionSuccessor(&getThenRegion()));
1184 regions.push_back(RegionSuccessor(elseRegion));
1189void cir::IfOp::build(OpBuilder &builder, OperationState &result,
Value cond,
1192 assert(thenBuilder &&
"the builder callback for 'then' must be present");
1193 result.addOperands(cond);
1195 OpBuilder::InsertionGuard guard(builder);
1196 Region *thenRegion = result.addRegion();
1197 builder.createBlock(thenRegion);
1198 thenBuilder(builder, result.location);
1200 Region *elseRegion = result.addRegion();
1201 if (!withElseRegion)
1204 builder.createBlock(elseRegion);
1205 elseBuilder(builder, result.location);
1217void cir::ScopeOp::getSuccessorRegions(
1218 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1220 if (!point.isParent()) {
1221 regions.push_back(RegionSuccessor(getOperation(), getODSResults(0)));
1226 regions.push_back(RegionSuccessor(&getScopeRegion()));
1229void cir::ScopeOp::build(
1230 OpBuilder &builder, OperationState &result,
1231 function_ref<
void(OpBuilder &, Type &, Location)> scopeBuilder) {
1232 assert(scopeBuilder &&
"the builder callback for 'then' must be present");
1234 OpBuilder::InsertionGuard guard(builder);
1235 Region *scopeRegion = result.addRegion();
1236 builder.createBlock(scopeRegion);
1240 scopeBuilder(builder, yieldTy, result.location);
1243 result.addTypes(TypeRange{yieldTy});
1246void cir::ScopeOp::build(
1247 OpBuilder &builder, OperationState &result,
1248 function_ref<
void(OpBuilder &, Location)> scopeBuilder) {
1249 assert(scopeBuilder &&
"the builder callback for 'then' must be present");
1250 OpBuilder::InsertionGuard guard(builder);
1251 Region *scopeRegion = result.addRegion();
1252 builder.createBlock(scopeRegion);
1254 scopeBuilder(builder, result.location);
1257LogicalResult cir::ScopeOp::verify() {
1259 return emitOpError() <<
"cir.scope must not be empty since it should "
1260 "include at least an implicit cir.yield ";
1263 mlir::Block &lastBlock =
getRegion().back();
1264 if (lastBlock.empty() || !lastBlock.mightHaveTerminator() ||
1265 !lastBlock.getTerminator()->hasTrait<OpTrait::IsTerminator>())
1266 return emitOpError() <<
"last block of cir.scope must be terminated";
1270LogicalResult cir::ScopeOp::fold(FoldAdaptor ,
1271 SmallVectorImpl<OpFoldResult> &results) {
1276 if (block.getOperations().size() != 1)
1279 auto yield = dyn_cast<cir::YieldOp>(block.front());
1284 if (getNumResults() != 1 || yield.getNumOperands() != 1)
1287 results.push_back(yield.getOperand(0));
1295mlir::SuccessorOperands cir::BrOp::getSuccessorOperands(
unsigned index) {
1296 assert(index == 0 &&
"invalid successor index");
1297 return mlir::SuccessorOperands(getDestOperandsMutable());
1308mlir::SuccessorOperands
1309cir::IndirectBrOp::getSuccessorOperands(
unsigned index) {
1310 assert(index < getNumSuccessors() &&
"invalid successor index");
1311 return mlir::SuccessorOperands(getSuccOperandsMutable()[index]);
1315 OpAsmParser &parser, Type &flagType,
1316 SmallVectorImpl<Block *> &succOperandBlocks,
1319 if (failed(parser.parseCommaSeparatedList(
1320 OpAsmParser::Delimiter::Square,
1322 Block *destination = nullptr;
1323 SmallVector<OpAsmParser::UnresolvedOperand> operands;
1324 SmallVector<Type> operandTypes;
1326 if (parser.parseSuccessor(destination).failed())
1329 if (succeeded(parser.parseOptionalLParen())) {
1330 if (failed(parser.parseOperandList(
1331 operands, OpAsmParser::Delimiter::None)) ||
1332 failed(parser.parseColonTypeList(operandTypes)) ||
1333 failed(parser.parseRParen()))
1336 succOperandBlocks.push_back(destination);
1337 succOperands.emplace_back(operands);
1338 succOperandsTypes.emplace_back(operandTypes);
1341 "successor blocks")))
1347 Type flagType, SuccessorRange succs,
1348 OperandRangeRange succOperands,
1349 const TypeRangeRange &succOperandsTypes) {
1352 llvm::zip(succs, succOperands),
1355 p.printSuccessorAndUseList(std::get<0>(i), std::get<1>(i));
1358 if (!succOperands.empty())
1367mlir::SuccessorOperands cir::BrCondOp::getSuccessorOperands(
unsigned index) {
1368 assert(index < getNumSuccessors() &&
"invalid successor index");
1369 return SuccessorOperands(index == 0 ? getDestOperandsTrueMutable()
1370 : getDestOperandsFalseMutable());
1374 if (IntegerAttr condAttr = dyn_cast_if_present<IntegerAttr>(operands.front()))
1375 return condAttr.getValue().isOne() ? getDestTrue() : getDestFalse();
1383void cir::CaseOp::getSuccessorRegions(
1384 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1385 if (!point.isParent()) {
1387 RegionSuccessor(getOperation(), getOperation()->getResults()));
1390 regions.push_back(RegionSuccessor(&getCaseRegion()));
1393void cir::CaseOp::build(OpBuilder &builder, OperationState &result,
1394 ArrayAttr value, CaseOpKind kind,
1395 OpBuilder::InsertPoint &insertPoint) {
1396 OpBuilder::InsertionGuard guardSwitch(builder);
1397 result.addAttribute(
"value", value);
1398 result.getOrAddProperties<Properties>().kind =
1399 cir::CaseOpKindAttr::get(builder.getContext(), kind);
1400 Region *caseRegion = result.addRegion();
1401 builder.createBlock(caseRegion);
1403 insertPoint = builder.saveInsertionPoint();
1410void cir::SwitchOp::getSuccessorRegions(
1411 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ion) {
1412 if (!point.isParent()) {
1414 RegionSuccessor(getOperation(), getOperation()->getResults()));
1418 region.push_back(RegionSuccessor(&getBody()));
1421void cir::SwitchOp::build(OpBuilder &builder, OperationState &result,
1423 assert(switchBuilder &&
"the builder callback for regions must be present");
1424 OpBuilder::InsertionGuard guardSwitch(builder);
1425 Region *switchRegion = result.addRegion();
1426 builder.createBlock(switchRegion);
1427 result.addOperands({cond});
1428 switchBuilder(builder, result.location, result);
1432 walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
1434 if (isa<cir::SwitchOp>(op) && op != *
this)
1435 return WalkResult::skip();
1437 if (
auto caseOp = dyn_cast<cir::CaseOp>(op))
1438 cases.push_back(caseOp);
1440 return WalkResult::advance();
1445 collectCases(cases);
1447 if (getBody().empty())
1450 if (!isa<YieldOp>(getBody().front().back()))
1453 if (!llvm::all_of(getBody().front(),
1454 [](Operation &op) {
return isa<CaseOp, YieldOp>(op); }))
1457 return llvm::all_of(cases, [
this](CaseOp op) {
1458 return op->getParentOfType<SwitchOp>() == *
this;
1466void cir::SwitchFlatOp::build(OpBuilder &builder, OperationState &result,
1467 Value value, Block *defaultDestination,
1468 ValueRange defaultOperands,
1470 BlockRange caseDestinations,
1473 std::vector<mlir::Attribute> caseValuesAttrs;
1474 for (
const APInt &val : caseValues)
1475 caseValuesAttrs.push_back(cir::IntAttr::get(value.getType(), val));
1476 mlir::ArrayAttr attrs = ArrayAttr::get(builder.getContext(), caseValuesAttrs);
1478 build(builder, result, value, defaultOperands, caseOperands, attrs,
1479 defaultDestination, caseDestinations);
1485 OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues,
1486 SmallVectorImpl<Block *> &caseDestinations,
1490 if (failed(parser.parseLSquare()))
1492 if (succeeded(parser.parseOptionalRSquare()))
1496 auto parseCase = [&]() {
1498 if (failed(parser.parseInteger(value)))
1501 values.push_back(cir::IntAttr::get(flagType, value));
1506 if (parser.parseColon() || parser.parseSuccessor(destination))
1508 if (!parser.parseOptionalLParen()) {
1509 if (parser.parseOperandList(operands, OpAsmParser::Delimiter::None,
1511 parser.parseColonTypeList(operandTypes) || parser.parseRParen())
1514 caseDestinations.push_back(destination);
1515 caseOperands.emplace_back(operands);
1516 caseOperandTypes.emplace_back(operandTypes);
1519 if (failed(parser.parseCommaSeparatedList(parseCase)))
1522 caseValues = ArrayAttr::get(flagType.getContext(), values);
1524 return parser.parseRSquare();
1528 Type flagType, mlir::ArrayAttr caseValues,
1529 SuccessorRange caseDestinations,
1530 OperandRangeRange caseOperands,
1531 const TypeRangeRange &caseOperandTypes) {
1541 llvm::zip(caseValues, caseDestinations),
1544 mlir::Attribute a = std::get<0>(i);
1545 p << mlir::cast<cir::IntAttr>(a).getValue();
1547 p.printSuccessorAndUseList(std::get<1>(i), caseOperands[index++]);
1562 mlir::Attribute &valueAttr) {
1564 return parser.parseAttribute(valueAttr,
"value", attr);
1568 p.printAttribute(value);
1571mlir::LogicalResult cir::GlobalOp::verify() {
1574 if (getInitialValue().has_value()) {
1586void cir::GlobalOp::build(
1587 OpBuilder &odsBuilder, OperationState &odsState, llvm::StringRef sym_name,
1588 mlir::Type sym_type,
bool isConstant, cir::GlobalLinkageKind linkage,
1589 function_ref<
void(OpBuilder &, Location)> ctorBuilder,
1590 function_ref<
void(OpBuilder &, Location)> dtorBuilder) {
1591 odsState.addAttribute(getSymNameAttrName(odsState.name),
1592 odsBuilder.getStringAttr(sym_name));
1593 odsState.addAttribute(getSymTypeAttrName(odsState.name),
1594 mlir::TypeAttr::get(sym_type));
1596 odsState.addAttribute(getConstantAttrName(odsState.name),
1597 odsBuilder.getUnitAttr());
1599 cir::GlobalLinkageKindAttr linkageAttr =
1600 cir::GlobalLinkageKindAttr::get(odsBuilder.getContext(), linkage);
1601 odsState.addAttribute(getLinkageAttrName(odsState.name), linkageAttr);
1603 Region *ctorRegion = odsState.addRegion();
1605 odsBuilder.createBlock(ctorRegion);
1606 ctorBuilder(odsBuilder, odsState.location);
1609 Region *dtorRegion = odsState.addRegion();
1611 odsBuilder.createBlock(dtorRegion);
1612 dtorBuilder(odsBuilder, odsState.location);
1615 odsState.addAttribute(getGlobalVisibilityAttrName(odsState.name),
1616 cir::VisibilityAttr::get(odsBuilder.getContext()));
1624void cir::GlobalOp::getSuccessorRegions(
1625 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1627 if (!point.isParent()) {
1629 RegionSuccessor(getOperation(), getOperation()->getResults()));
1634 Region *ctorRegion = &this->getCtorRegion();
1635 if (ctorRegion->empty())
1636 ctorRegion =
nullptr;
1639 Region *dtorRegion = &this->getCtorRegion();
1640 if (dtorRegion->empty())
1641 dtorRegion =
nullptr;
1645 regions.push_back(RegionSuccessor(ctorRegion));
1647 regions.push_back(RegionSuccessor(dtorRegion));
1651 TypeAttr type, Attribute initAttr,
1652 mlir::Region &ctorRegion,
1653 mlir::Region &dtorRegion) {
1654 auto printType = [&]() { p <<
": " << type; };
1655 if (!op.isDeclaration()) {
1657 if (!ctorRegion.empty()) {
1661 p.printRegion(ctorRegion,
1670 if (!dtorRegion.empty()) {
1672 p.printRegion(dtorRegion,
1683 Attribute &initialValueAttr,
1684 mlir::Region &ctorRegion,
1685 mlir::Region &dtorRegion) {
1687 if (parser.parseOptionalEqual().failed()) {
1690 if (parser.parseColonType(opTy))
1695 if (!parser.parseOptionalKeyword(
"ctor")) {
1696 if (parser.parseColonType(opTy))
1698 auto parseLoc = parser.getCurrentLocation();
1699 if (parser.parseRegion(ctorRegion, {}, {}))
1710 assert(mlir::isa<mlir::TypedAttr>(initialValueAttr) &&
1711 "Non-typed attrs shouldn't appear here.");
1712 auto typedAttr = mlir::cast<mlir::TypedAttr>(initialValueAttr);
1713 opTy = typedAttr.getType();
1718 if (!parser.parseOptionalKeyword(
"dtor")) {
1719 auto parseLoc = parser.getCurrentLocation();
1720 if (parser.parseRegion(dtorRegion, {}, {}))
1727 typeAttr = TypeAttr::get(opTy);
1736cir::GetGlobalOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1739 mlir::Operation *op =
1740 symbolTable.lookupNearestSymbolFrom(*
this, getNameAttr());
1741 if (op ==
nullptr || !(isa<GlobalOp>(op) || isa<FuncOp>(op)))
1742 return emitOpError(
"'")
1744 <<
"' does not reference a valid cir.global or cir.func";
1747 if (
auto g = dyn_cast<GlobalOp>(op)) {
1748 symTy = g.getSymType();
1752 if (getTls() && !g.getTlsModel())
1753 return emitOpError(
"access to global not marked thread local");
1754 }
else if (
auto f = dyn_cast<FuncOp>(op)) {
1755 symTy = f.getFunctionType();
1757 llvm_unreachable(
"Unexpected operation for GetGlobalOp");
1760 auto resultType = dyn_cast<PointerType>(getAddr().
getType());
1761 if (!resultType || symTy != resultType.getPointee())
1762 return emitOpError(
"result type pointee type '")
1763 << resultType.getPointee() <<
"' does not match type " << symTy
1764 <<
" of the global @" <<
getName();
1774cir::VTableAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1780 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*
this, getNameAttr());
1782 return emitOpError(
"'")
1783 <<
name <<
"' does not reference a valid cir.global";
1784 std::optional<mlir::Attribute> init = op.getInitialValue();
1787 if (!isa<cir::VTableAttr>(*init))
1788 return emitOpError(
"Expected #cir.vtable in initializer for global '")
1798cir::VTTAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1807 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*
this, getNameAttr());
1809 return emitOpError(
"'")
1810 <<
name <<
"' does not reference a valid cir.global";
1811 std::optional<mlir::Attribute> init = op.getInitialValue();
1814 if (!isa<cir::ConstArrayAttr>(*init))
1816 "Expected constant array in initializer for global VTT '")
1821LogicalResult cir::VTTAddrPointOp::verify() {
1823 if (
getName() && getSymAddr())
1824 return emitOpError(
"should use either a symbol or value, but not both");
1830 mlir::Type resultType = getAddr().getType();
1831 mlir::Type resTy = cir::PointerType::get(
1832 cir::PointerType::get(cir::VoidType::get(getContext())));
1834 if (resultType != resTy)
1835 return emitOpError(
"result type must be ")
1836 << resTy <<
", but provided result type is " << resultType;
1848void cir::FuncOp::build(OpBuilder &builder, OperationState &result,
1849 StringRef name, FuncType type,
1850 GlobalLinkageKind linkage) {
1852 result.addAttribute(SymbolTable::getSymbolAttrName(),
1853 builder.getStringAttr(name));
1854 result.addAttribute(getFunctionTypeAttrName(result.name),
1855 TypeAttr::get(type));
1856 result.addAttribute(
1858 GlobalLinkageKindAttr::get(builder.getContext(), linkage));
1859 result.addAttribute(getGlobalVisibilityAttrName(result.name),
1860 cir::VisibilityAttr::get(builder.getContext()));
1863ParseResult cir::FuncOp::parse(OpAsmParser &parser, OperationState &state) {
1864 llvm::SMLoc loc = parser.getCurrentLocation();
1865 mlir::Builder &builder = parser.getBuilder();
1867 mlir::StringAttr builtinNameAttr = getBuiltinAttrName(state.name);
1868 mlir::StringAttr coroutineNameAttr = getCoroutineAttrName(state.name);
1869 mlir::StringAttr inlineKindNameAttr = getInlineKindAttrName(state.name);
1870 mlir::StringAttr lambdaNameAttr = getLambdaAttrName(state.name);
1871 mlir::StringAttr noProtoNameAttr = getNoProtoAttrName(state.name);
1872 mlir::StringAttr visNameAttr = getSymVisibilityAttrName(state.name);
1873 mlir::StringAttr visibilityNameAttr = getGlobalVisibilityAttrName(state.name);
1874 mlir::StringAttr dsoLocalNameAttr = getDsoLocalAttrName(state.name);
1875 mlir::StringAttr specialMemberAttr = getCxxSpecialMemberAttrName(state.name);
1877 if (::mlir::succeeded(parser.parseOptionalKeyword(builtinNameAttr.strref())))
1878 state.addAttribute(builtinNameAttr, parser.getBuilder().getUnitAttr());
1879 if (::mlir::succeeded(
1880 parser.parseOptionalKeyword(coroutineNameAttr.strref())))
1881 state.addAttribute(coroutineNameAttr, parser.getBuilder().getUnitAttr());
1884 cir::InlineKindAttr inlineKindAttr;
1888 state.addAttribute(inlineKindNameAttr, inlineKindAttr);
1890 if (::mlir::succeeded(parser.parseOptionalKeyword(lambdaNameAttr.strref())))
1891 state.addAttribute(lambdaNameAttr, parser.getBuilder().getUnitAttr());
1892 if (parser.parseOptionalKeyword(noProtoNameAttr).succeeded())
1893 state.addAttribute(noProtoNameAttr, parser.getBuilder().getUnitAttr());
1897 GlobalLinkageKindAttr::get(
1898 parser.getContext(),
1900 parser, GlobalLinkageKind::ExternalLinkage)));
1902 ::llvm::StringRef visAttrStr;
1903 if (parser.parseOptionalKeyword(&visAttrStr, {
"private",
"public",
"nested"})
1905 state.addAttribute(visNameAttr,
1906 parser.getBuilder().getStringAttr(visAttrStr));
1909 cir::VisibilityAttr cirVisibilityAttr;
1911 state.addAttribute(visibilityNameAttr, cirVisibilityAttr);
1913 if (parser.parseOptionalKeyword(dsoLocalNameAttr).succeeded())
1914 state.addAttribute(dsoLocalNameAttr, parser.getBuilder().getUnitAttr());
1916 StringAttr nameAttr;
1917 if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
1923 bool isVariadic =
false;
1924 if (function_interface_impl::parseFunctionSignatureWithArguments(
1925 parser,
true, arguments, isVariadic, resultTypes,
1929 for (OpAsmParser::Argument &arg : arguments)
1930 argTypes.push_back(
arg.type);
1932 if (resultTypes.size() > 1) {
1933 return parser.emitError(
1934 loc,
"functions with multiple return types are not supported");
1937 mlir::Type returnType =
1938 (resultTypes.empty() ? cir::VoidType::get(builder.getContext())
1939 : resultTypes.front());
1941 cir::FuncType fnType = cir::FuncType::get(argTypes, returnType, isVariadic);
1944 state.addAttribute(getFunctionTypeAttrName(state.name),
1945 TypeAttr::get(fnType));
1947 bool hasAlias =
false;
1948 mlir::StringAttr aliaseeNameAttr = getAliaseeAttrName(state.name);
1949 if (parser.parseOptionalKeyword(
"alias").succeeded()) {
1950 if (parser.parseLParen().failed())
1952 mlir::StringAttr aliaseeAttr;
1953 if (parser.parseOptionalSymbolName(aliaseeAttr).failed())
1955 state.addAttribute(aliaseeNameAttr, FlatSymbolRefAttr::get(aliaseeAttr));
1956 if (parser.parseRParen().failed())
1961 mlir::StringAttr personalityNameAttr = getPersonalityAttrName(state.name);
1962 if (parser.parseOptionalKeyword(
"personality").succeeded()) {
1963 if (parser.parseLParen().failed())
1965 mlir::StringAttr personalityAttr;
1966 if (parser.parseOptionalSymbolName(personalityAttr).failed())
1968 state.addAttribute(personalityNameAttr,
1969 FlatSymbolRefAttr::get(personalityAttr));
1970 if (parser.parseRParen().failed())
1974 auto parseGlobalDtorCtor =
1975 [&](StringRef keyword,
1976 llvm::function_ref<void(std::optional<int> prio)> createAttr)
1977 -> mlir::LogicalResult {
1978 if (mlir::succeeded(parser.parseOptionalKeyword(keyword))) {
1979 std::optional<int> priority;
1980 if (mlir::succeeded(parser.parseOptionalLParen())) {
1981 auto parsedPriority = mlir::FieldParser<int>::parse(parser);
1982 if (mlir::failed(parsedPriority))
1983 return parser.emitError(parser.getCurrentLocation(),
1984 "failed to parse 'priority', of type 'int'");
1985 priority = parsedPriority.value_or(
int());
1987 if (parser.parseRParen())
1990 createAttr(priority);
1996 if (parser.parseOptionalKeyword(
"special_member").succeeded()) {
1997 cir::CXXCtorAttr ctorAttr;
1998 cir::CXXDtorAttr dtorAttr;
1999 cir::CXXAssignAttr assignAttr;
2000 if (parser.parseLess().failed())
2002 if (parser.parseOptionalAttribute(ctorAttr).has_value())
2003 state.addAttribute(specialMemberAttr, ctorAttr);
2004 else if (parser.parseOptionalAttribute(dtorAttr).has_value())
2005 state.addAttribute(specialMemberAttr, dtorAttr);
2006 else if (parser.parseOptionalAttribute(assignAttr).has_value())
2007 state.addAttribute(specialMemberAttr, assignAttr);
2008 if (parser.parseGreater().failed())
2012 if (parseGlobalDtorCtor(
"global_ctor", [&](std::optional<int> priority) {
2013 mlir::IntegerAttr globalCtorPriorityAttr =
2014 builder.getI32IntegerAttr(priority.value_or(65535));
2015 state.addAttribute(getGlobalCtorPriorityAttrName(state.name),
2016 globalCtorPriorityAttr);
2020 if (parseGlobalDtorCtor(
"global_dtor", [&](std::optional<int> priority) {
2021 mlir::IntegerAttr globalDtorPriorityAttr =
2022 builder.getI32IntegerAttr(priority.value_or(65535));
2023 state.addAttribute(getGlobalDtorPriorityAttrName(state.name),
2024 globalDtorPriorityAttr);
2029 NamedAttrList parsedAttrs;
2030 if (parser.parseOptionalAttrDictWithKeyword(parsedAttrs))
2033 for (StringRef disallowed : cir::FuncOp::getAttributeNames()) {
2034 if (parsedAttrs.get(disallowed))
2035 return parser.emitError(loc,
"attribute '")
2037 <<
"' should not be specified in the explicit attribute list";
2040 state.attributes.append(parsedAttrs);
2043 auto *body = state.addRegion();
2044 OptionalParseResult parseResult = parser.parseOptionalRegion(
2045 *body, arguments,
false);
2046 if (parseResult.has_value()) {
2048 return parser.emitError(loc,
"function alias shall not have a body");
2049 if (failed(*parseResult))
2053 return parser.emitError(loc,
"expected non-empty function body");
2062bool cir::FuncOp::isDeclaration() {
2065 std::optional<StringRef> aliasee = getAliasee();
2067 return getFunctionBody().empty();
2073bool cir::FuncOp::isCXXSpecialMemberFunction() {
2074 return getCxxSpecialMemberAttr() !=
nullptr;
2077bool cir::FuncOp::isCxxConstructor() {
2078 auto attr = getCxxSpecialMemberAttr();
2079 return attr && dyn_cast<CXXCtorAttr>(attr);
2082bool cir::FuncOp::isCxxDestructor() {
2083 auto attr = getCxxSpecialMemberAttr();
2084 return attr && dyn_cast<CXXDtorAttr>(attr);
2087bool cir::FuncOp::isCxxSpecialAssignment() {
2088 auto attr = getCxxSpecialMemberAttr();
2089 return attr && dyn_cast<CXXAssignAttr>(attr);
2092std::optional<CtorKind> cir::FuncOp::getCxxConstructorKind() {
2093 mlir::Attribute
attr = getCxxSpecialMemberAttr();
2095 if (
auto ctor = dyn_cast<CXXCtorAttr>(attr))
2096 return ctor.getCtorKind();
2098 return std::nullopt;
2101std::optional<AssignKind> cir::FuncOp::getCxxSpecialAssignKind() {
2102 mlir::Attribute
attr = getCxxSpecialMemberAttr();
2104 if (
auto assign = dyn_cast<CXXAssignAttr>(attr))
2105 return assign.getAssignKind();
2107 return std::nullopt;
2110bool cir::FuncOp::isCxxTrivialMemberFunction() {
2111 mlir::Attribute
attr = getCxxSpecialMemberAttr();
2113 if (
auto ctor = dyn_cast<CXXCtorAttr>(attr))
2114 return ctor.getIsTrivial();
2115 if (
auto dtor = dyn_cast<CXXDtorAttr>(attr))
2116 return dtor.getIsTrivial();
2117 if (
auto assign = dyn_cast<CXXAssignAttr>(attr))
2118 return assign.getIsTrivial();
2123mlir::Region *cir::FuncOp::getCallableRegion() {
2129void cir::FuncOp::print(OpAsmPrinter &p) {
2147 if (getLinkage() != GlobalLinkageKind::ExternalLinkage)
2148 p <<
' ' << stringifyGlobalLinkageKind(getLinkage());
2150 mlir::SymbolTable::Visibility vis = getVisibility();
2151 if (vis != mlir::SymbolTable::Visibility::Public)
2154 cir::VisibilityAttr cirVisibilityAttr = getGlobalVisibilityAttr();
2155 if (!cirVisibilityAttr.isDefault()) {
2164 p.printSymbolName(getSymName());
2165 cir::FuncType fnType = getFunctionType();
2166 function_interface_impl::printFunctionSignature(
2167 p, *
this, fnType.getInputs(), fnType.isVarArg(), fnType.getReturnTypes());
2169 if (std::optional<StringRef> aliaseeName = getAliasee()) {
2171 p.printSymbolName(*aliaseeName);
2175 if (std::optional<StringRef> personalityName = getPersonality()) {
2176 p <<
" personality(";
2177 p.printSymbolName(*personalityName);
2181 if (
auto specialMemberAttr = getCxxSpecialMember()) {
2182 p <<
" special_member<";
2183 p.printAttribute(*specialMemberAttr);
2187 if (
auto globalCtorPriority = getGlobalCtorPriority()) {
2188 p <<
" global_ctor";
2189 if (globalCtorPriority.value() != 65535)
2190 p <<
"(" << globalCtorPriority.value() <<
")";
2193 if (
auto globalDtorPriority = getGlobalDtorPriority()) {
2194 p <<
" global_dtor";
2195 if (globalDtorPriority.value() != 65535)
2196 p <<
"(" << globalDtorPriority.value() <<
")";
2199 function_interface_impl::printFunctionAttributes(
2200 p, *
this, cir::FuncOp::getAttributeNames());
2203 Region &body = getOperation()->getRegion(0);
2204 if (!body.empty()) {
2206 p.printRegion(body,
false,
2211mlir::LogicalResult cir::FuncOp::verify() {
2213 if (!isDeclaration() && getCoroutine()) {
2214 bool foundAwait =
false;
2215 this->walk([&](Operation *op) {
2216 if (
auto await = dyn_cast<AwaitOp>(op)) {
2222 return emitOpError()
2223 <<
"coroutine body must use at least one cir.await op";
2226 llvm::SmallSet<llvm::StringRef, 16> labels;
2227 llvm::SmallSet<llvm::StringRef, 16> gotos;
2228 llvm::SmallSet<llvm::StringRef, 16> blockAddresses;
2229 bool invalidBlockAddress =
false;
2230 getOperation()->walk([&](mlir::Operation *op) {
2231 if (
auto lab = dyn_cast<cir::LabelOp>(op)) {
2232 labels.insert(lab.getLabel());
2233 }
else if (
auto goTo = dyn_cast<cir::GotoOp>(op)) {
2234 gotos.insert(goTo.getLabel());
2235 }
else if (
auto blkAdd = dyn_cast<cir::BlockAddressOp>(op)) {
2236 if (blkAdd.getBlockAddrInfoAttr().getFunc().getAttr() != getSymName()) {
2238 invalidBlockAddress =
true;
2239 return mlir::WalkResult::interrupt();
2241 blockAddresses.insert(blkAdd.getBlockAddrInfoAttr().getLabel());
2243 return mlir::WalkResult::advance();
2246 if (invalidBlockAddress)
2247 return emitOpError() <<
"blockaddress references a different function";
2249 llvm::SmallSet<llvm::StringRef, 16> mismatched;
2250 if (!labels.empty() || !gotos.empty()) {
2251 mismatched = llvm::set_difference(gotos, labels);
2253 if (!mismatched.empty())
2254 return emitOpError() <<
"goto/label mismatch";
2259 if (!labels.empty() || !blockAddresses.empty()) {
2260 mismatched = llvm::set_difference(blockAddresses, labels);
2262 if (!mismatched.empty())
2263 return emitOpError()
2264 <<
"expects an existing label target in the referenced function";
2273LogicalResult cir::BinOp::verify() {
2274 bool noWrap = getNoUnsignedWrap() || getNoSignedWrap();
2275 bool saturated = getSaturated();
2277 if (!isa<cir::IntType>(
getType()) && noWrap)
2279 <<
"only operations on integer values may have nsw/nuw flags";
2281 bool noWrapOps =
getKind() == cir::BinOpKind::Add ||
2282 getKind() == cir::BinOpKind::Sub ||
2283 getKind() == cir::BinOpKind::Mul;
2286 getKind() == cir::BinOpKind::Add ||
getKind() == cir::BinOpKind::Sub;
2288 if (noWrap && !noWrapOps)
2289 return emitError() <<
"The nsw/nuw flags are applicable to opcodes: 'add', "
2291 if (saturated && !saturatedOps)
2292 return emitError() <<
"The saturated flag is applicable to opcodes: 'add' "
2294 if (noWrap && saturated)
2295 return emitError() <<
"The nsw/nuw flags and the saturated flag are "
2296 "mutually exclusive";
2298 return mlir::success();
2310void cir::TernaryOp::getSuccessorRegions(
2311 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
2313 if (!point.isParent()) {
2314 regions.push_back(RegionSuccessor(getOperation(), this->getODSResults(0)));
2320 regions.push_back(RegionSuccessor(&getTrueRegion()));
2321 regions.push_back(RegionSuccessor(&getFalseRegion()));
2324void cir::TernaryOp::build(
2325 OpBuilder &builder, OperationState &result,
Value cond,
2326 function_ref<
void(OpBuilder &, Location)> trueBuilder,
2327 function_ref<
void(OpBuilder &, Location)> falseBuilder) {
2328 result.addOperands(cond);
2329 OpBuilder::InsertionGuard guard(builder);
2330 Region *trueRegion = result.addRegion();
2331 builder.createBlock(trueRegion);
2332 trueBuilder(builder, result.location);
2333 Region *falseRegion = result.addRegion();
2334 builder.createBlock(falseRegion);
2335 falseBuilder(builder, result.location);
2340 dyn_cast_or_null<cir::YieldOp>(trueRegion->back().getTerminator());
2342 yield = dyn_cast_or_null<cir::YieldOp>(falseRegion->back().getTerminator());
2344 assert((yield && yield.getNumOperands() <= 1) &&
2345 "expected zero or one result type");
2346 if (yield.getNumOperands() == 1)
2347 result.addTypes(TypeRange{yield.getOperandTypes().front()});
2354OpFoldResult cir::SelectOp::fold(FoldAdaptor adaptor) {
2355 mlir::Attribute condition = adaptor.getCondition();
2357 bool conditionValue = mlir::cast<cir::BoolAttr>(condition).getValue();
2358 return conditionValue ? getTrueValue() : getFalseValue();
2362 mlir::Attribute trueValue = adaptor.getTrueValue();
2363 mlir::Attribute falseValue = adaptor.getFalseValue();
2364 if (trueValue == falseValue)
2366 if (getTrueValue() == getFalseValue())
2367 return getTrueValue();
2372LogicalResult cir::SelectOp::verify() {
2374 auto condTy = dyn_cast<cir::VectorType>(getCondition().
getType());
2381 if (!isa<cir::VectorType>(getTrueValue().
getType()) ||
2382 !isa<cir::VectorType>(getFalseValue().
getType())) {
2383 return emitOpError()
2384 <<
"expected both true and false operands to be vector types "
2385 "when the condition is a vector boolean type";
2394LogicalResult cir::ShiftOp::verify() {
2395 mlir::Operation *op = getOperation();
2396 auto op0VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(0).getType());
2397 auto op1VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(1).getType());
2398 if (!op0VecTy ^ !op1VecTy)
2399 return emitOpError() <<
"input types cannot be one vector and one scalar";
2402 if (op0VecTy.getSize() != op1VecTy.getSize())
2403 return emitOpError() <<
"input vector types must have the same size";
2405 auto opResultTy = mlir::dyn_cast<cir::VectorType>(
getType());
2407 return emitOpError() <<
"the type of the result must be a vector "
2408 <<
"if it is vector shift";
2410 auto op0VecEleTy = mlir::cast<cir::IntType>(op0VecTy.getElementType());
2411 auto op1VecEleTy = mlir::cast<cir::IntType>(op1VecTy.getElementType());
2412 if (op0VecEleTy.getWidth() != op1VecEleTy.getWidth())
2413 return emitOpError()
2414 <<
"vector operands do not have the same elements sizes";
2416 auto resVecEleTy = mlir::cast<cir::IntType>(opResultTy.getElementType());
2417 if (op0VecEleTy.getWidth() != resVecEleTy.getWidth())
2418 return emitOpError() <<
"vector operands and result type do not have the "
2419 "same elements sizes";
2422 return mlir::success();
2429LogicalResult cir::LabelOp::verify() {
2430 mlir::Operation *op = getOperation();
2431 mlir::Block *blk = op->getBlock();
2432 if (&blk->front() != op)
2433 return emitError() <<
"must be the first operation in a block";
2435 return mlir::success();
2442LogicalResult cir::UnaryOp::verify() {
2444 case cir::UnaryOpKind::Inc:
2445 case cir::UnaryOpKind::Dec:
2446 case cir::UnaryOpKind::Plus:
2447 case cir::UnaryOpKind::Minus:
2448 case cir::UnaryOpKind::Not:
2453 llvm_unreachable(
"Unknown UnaryOp kind?");
2457 return isa<cir::BoolType>(op.getInput().getType()) &&
2458 op.getKind() == cir::UnaryOpKind::Not;
2470OpFoldResult cir::UnaryOp::fold(FoldAdaptor adaptor) {
2472 mlir::dyn_cast_if_present<cir::PoisonAttr>(adaptor.getInput())) {
2478 if (
auto previous = getInput().getDefiningOp<cir::UnaryOp>())
2480 return previous.getInput();
2488void cir::AwaitOp::build(OpBuilder &builder, OperationState &result,
2492 result.addAttribute(getKindAttrName(result.name),
2493 cir::AwaitKindAttr::get(builder.getContext(), kind));
2495 OpBuilder::InsertionGuard guard(builder);
2496 Region *readyRegion = result.addRegion();
2497 builder.createBlock(readyRegion);
2498 readyBuilder(builder, result.location);
2502 OpBuilder::InsertionGuard guard(builder);
2503 Region *suspendRegion = result.addRegion();
2504 builder.createBlock(suspendRegion);
2505 suspendBuilder(builder, result.location);
2509 OpBuilder::InsertionGuard guard(builder);
2510 Region *resumeRegion = result.addRegion();
2511 builder.createBlock(resumeRegion);
2512 resumeBuilder(builder, result.location);
2516void cir::AwaitOp::getSuccessorRegions(
2517 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
2520 if (!point.isParent()) {
2522 RegionSuccessor(getOperation(), getOperation()->getResults()));
2529 regions.push_back(RegionSuccessor(&this->getReady()));
2530 regions.push_back(RegionSuccessor(&this->getSuspend()));
2531 regions.push_back(RegionSuccessor(&this->getResume()));
2534LogicalResult cir::AwaitOp::verify() {
2535 if (!isa<ConditionOp>(this->getReady().back().getTerminator()))
2536 return emitOpError(
"ready region must end with cir.condition");
2544LogicalResult cir::CopyOp::verify() {
2546 if (!
getType().getPointee().hasTrait<DataLayoutTypeInterface::Trait>())
2547 return emitError() <<
"missing data layout for pointee type";
2549 if (getSrc() == getDst())
2550 return emitError() <<
"source and destination are the same";
2552 return mlir::success();
2559LogicalResult cir::GetRuntimeMemberOp::verify() {
2560 auto recordTy = mlir::cast<RecordType>(getAddr().
getType().getPointee());
2561 cir::DataMemberType memberPtrTy = getMember().getType();
2563 if (recordTy != memberPtrTy.getClassTy())
2564 return emitError() <<
"record type does not match the member pointer type";
2565 if (
getType().getPointee() != memberPtrTy.getMemberTy())
2566 return emitError() <<
"result type does not match the member pointer type";
2567 return mlir::success();
2574LogicalResult cir::GetMemberOp::verify() {
2575 const auto recordTy = dyn_cast<RecordType>(getAddrTy().getPointee());
2577 return emitError() <<
"expected pointer to a record type";
2579 if (recordTy.getMembers().size() <=
getIndex())
2580 return emitError() <<
"member index out of bounds";
2583 return emitError() <<
"member type mismatch";
2585 return mlir::success();
2592LogicalResult cir::ExtractMemberOp::verify() {
2593 auto recordTy = mlir::cast<cir::RecordType>(getRecord().
getType());
2594 if (recordTy.getKind() == cir::RecordType::Union)
2596 <<
"cir.extract_member currently does not support unions";
2597 if (recordTy.getMembers().size() <=
getIndex())
2598 return emitError() <<
"member index out of bounds";
2600 return emitError() <<
"member type mismatch";
2601 return mlir::success();
2608OpFoldResult cir::VecCreateOp::fold(FoldAdaptor adaptor) {
2609 if (llvm::any_of(getElements(), [](mlir::Value value) {
2610 return !value.getDefiningOp<cir::ConstantOp>();
2614 return cir::ConstVectorAttr::get(
2615 getType(), mlir::ArrayAttr::get(getContext(), adaptor.getElements()));
2618LogicalResult cir::VecCreateOp::verify() {
2622 const cir::VectorType vecTy =
getType();
2623 if (getElements().size() != vecTy.getSize()) {
2624 return emitOpError() <<
"operand count of " << getElements().size()
2625 <<
" doesn't match vector type " << vecTy
2626 <<
" element count of " << vecTy.getSize();
2629 const mlir::Type elementType = vecTy.getElementType();
2630 for (
const mlir::Value element : getElements()) {
2631 if (element.getType() != elementType) {
2632 return emitOpError() <<
"operand type " << element.getType()
2633 <<
" doesn't match vector element type "
2645OpFoldResult cir::VecExtractOp::fold(FoldAdaptor adaptor) {
2646 const auto vectorAttr =
2647 llvm::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec());
2651 const auto indexAttr =
2652 llvm::dyn_cast_if_present<cir::IntAttr>(adaptor.getIndex());
2656 const mlir::ArrayAttr elements = vectorAttr.getElts();
2657 const uint64_t index = indexAttr.getUInt();
2658 if (index >= elements.size())
2661 return elements[index];
2668OpFoldResult cir::VecCmpOp::fold(FoldAdaptor adaptor) {
2670 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getLhs());
2672 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getRhs());
2673 if (!lhsVecAttr || !rhsVecAttr)
2676 mlir::Type inputElemTy =
2677 mlir::cast<cir::VectorType>(lhsVecAttr.getType()).getElementType();
2678 if (!isAnyIntegerOrFloatingPointType(inputElemTy))
2681 cir::CmpOpKind opKind = adaptor.getKind();
2682 mlir::ArrayAttr lhsVecElhs = lhsVecAttr.getElts();
2683 mlir::ArrayAttr rhsVecElhs = rhsVecAttr.getElts();
2684 uint64_t vecSize = lhsVecElhs.size();
2687 bool isIntAttr = vecSize && mlir::isa<cir::IntAttr>(lhsVecElhs[0]);
2688 for (uint64_t i = 0; i < vecSize; i++) {
2689 mlir::Attribute lhsAttr = lhsVecElhs[i];
2690 mlir::Attribute rhsAttr = rhsVecElhs[i];
2693 case cir::CmpOpKind::lt: {
2695 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <
2696 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2698 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <
2699 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2703 case cir::CmpOpKind::le: {
2705 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <=
2706 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2708 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <=
2709 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2713 case cir::CmpOpKind::gt: {
2715 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >
2716 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2718 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >
2719 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2723 case cir::CmpOpKind::ge: {
2725 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >=
2726 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2728 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >=
2729 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2733 case cir::CmpOpKind::eq: {
2735 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() ==
2736 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2738 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() ==
2739 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2743 case cir::CmpOpKind::ne: {
2745 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() !=
2746 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2748 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() !=
2749 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2755 elements[i] = cir::IntAttr::get(
getType().getElementType(), cmpResult);
2758 return cir::ConstVectorAttr::get(
2759 getType(), mlir::ArrayAttr::get(getContext(), elements));
2766OpFoldResult cir::VecShuffleOp::fold(FoldAdaptor adaptor) {
2768 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec1());
2770 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec2());
2771 if (!vec1Attr || !vec2Attr)
2774 mlir::Type vec1ElemTy =
2775 mlir::cast<cir::VectorType>(vec1Attr.getType()).getElementType();
2777 mlir::ArrayAttr vec1Elts = vec1Attr.getElts();
2778 mlir::ArrayAttr vec2Elts = vec2Attr.getElts();
2779 mlir::ArrayAttr indicesElts = adaptor.getIndices();
2782 elements.reserve(indicesElts.size());
2784 uint64_t vec1Size = vec1Elts.size();
2785 for (
const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
2786 if (idxAttr.getSInt() == -1) {
2787 elements.push_back(cir::UndefAttr::get(vec1ElemTy));
2791 uint64_t idxValue = idxAttr.getUInt();
2792 elements.push_back(idxValue < vec1Size ? vec1Elts[idxValue]
2793 : vec2Elts[idxValue - vec1Size]);
2796 return cir::ConstVectorAttr::get(
2797 getType(), mlir::ArrayAttr::get(getContext(), elements));
2800LogicalResult cir::VecShuffleOp::verify() {
2803 if (getIndices().size() != getResult().
getType().getSize()) {
2804 return emitOpError() <<
": the number of elements in " << getIndices()
2805 <<
" and " << getResult().getType() <<
" don't match";
2810 if (getVec1().
getType().getElementType() !=
2811 getResult().
getType().getElementType()) {
2812 return emitOpError() <<
": element types of " << getVec1().getType()
2813 <<
" and " << getResult().getType() <<
" don't match";
2816 const uint64_t maxValidIndex =
2817 getVec1().getType().getSize() + getVec2().getType().getSize() - 1;
2819 getIndices().getAsRange<cir::IntAttr>(), [&](cir::IntAttr idxAttr) {
2820 return idxAttr.getSInt() != -1 && idxAttr.getUInt() > maxValidIndex;
2822 return emitOpError() <<
": index for __builtin_shufflevector must be "
2823 "less than the total number of vector elements";
2832OpFoldResult cir::VecShuffleDynamicOp::fold(FoldAdaptor adaptor) {
2833 mlir::Attribute vec = adaptor.getVec();
2834 mlir::Attribute indices = adaptor.getIndices();
2835 if (mlir::isa_and_nonnull<cir::ConstVectorAttr>(vec) &&
2836 mlir::isa_and_nonnull<cir::ConstVectorAttr>(indices)) {
2837 auto vecAttr = mlir::cast<cir::ConstVectorAttr>(vec);
2838 auto indicesAttr = mlir::cast<cir::ConstVectorAttr>(indices);
2840 mlir::ArrayAttr vecElts = vecAttr.getElts();
2841 mlir::ArrayAttr indicesElts = indicesAttr.getElts();
2843 const uint64_t numElements = vecElts.size();
2846 elements.reserve(numElements);
2848 const uint64_t maskBits = llvm::NextPowerOf2(numElements - 1) - 1;
2849 for (
const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
2850 uint64_t idxValue = idxAttr.getUInt();
2851 uint64_t newIdx = idxValue & maskBits;
2852 elements.push_back(vecElts[newIdx]);
2855 return cir::ConstVectorAttr::get(
2856 getType(), mlir::ArrayAttr::get(getContext(), elements));
2862LogicalResult cir::VecShuffleDynamicOp::verify() {
2864 if (getVec().
getType().getSize() !=
2865 mlir::cast<cir::VectorType>(getIndices().
getType()).getSize()) {
2866 return emitOpError() <<
": the number of elements in " << getVec().getType()
2867 <<
" and " << getIndices().getType() <<
" don't match";
2876LogicalResult cir::VecTernaryOp::verify() {
2881 if (getCond().
getType().getSize() != getLhs().
getType().getSize()) {
2882 return emitOpError() <<
": the number of elements in "
2883 << getCond().getType() <<
" and " << getLhs().getType()
2889OpFoldResult cir::VecTernaryOp::fold(FoldAdaptor adaptor) {
2890 mlir::Attribute cond = adaptor.getCond();
2891 mlir::Attribute lhs = adaptor.getLhs();
2892 mlir::Attribute rhs = adaptor.getRhs();
2894 if (!mlir::isa_and_nonnull<cir::ConstVectorAttr>(cond) ||
2895 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(lhs) ||
2896 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(rhs))
2898 auto condVec = mlir::cast<cir::ConstVectorAttr>(cond);
2899 auto lhsVec = mlir::cast<cir::ConstVectorAttr>(lhs);
2900 auto rhsVec = mlir::cast<cir::ConstVectorAttr>(rhs);
2902 mlir::ArrayAttr condElts = condVec.getElts();
2905 elements.reserve(condElts.size());
2907 for (
const auto &[idx, condAttr] :
2908 llvm::enumerate(condElts.getAsRange<cir::IntAttr>())) {
2909 if (condAttr.getSInt()) {
2910 elements.push_back(lhsVec.getElts()[idx]);
2912 elements.push_back(rhsVec.getElts()[idx]);
2916 cir::VectorType vecTy = getLhs().getType();
2917 return cir::ConstVectorAttr::get(
2918 vecTy, mlir::ArrayAttr::get(getContext(), elements));
2925LogicalResult cir::ComplexCreateOp::verify() {
2928 <<
"operand type of cir.complex.create does not match its result type";
2935OpFoldResult cir::ComplexCreateOp::fold(FoldAdaptor adaptor) {
2936 mlir::Attribute real = adaptor.getReal();
2937 mlir::Attribute imag = adaptor.getImag();
2943 auto realAttr = mlir::cast<mlir::TypedAttr>(real);
2944 auto imagAttr = mlir::cast<mlir::TypedAttr>(imag);
2945 return cir::ConstComplexAttr::get(realAttr, imagAttr);
2952LogicalResult cir::ComplexRealOp::verify() {
2953 mlir::Type operandTy = getOperand().getType();
2954 if (
auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
2955 operandTy = complexOperandTy.getElementType();
2958 emitOpError() <<
": result type does not match operand type";
2965OpFoldResult cir::ComplexRealOp::fold(FoldAdaptor adaptor) {
2966 if (!mlir::isa<cir::ComplexType>(getOperand().
getType()))
2969 if (
auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
2970 return complexCreateOp.getOperand(0);
2973 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
2974 return complex ? complex.getReal() :
nullptr;
2981LogicalResult cir::ComplexImagOp::verify() {
2982 mlir::Type operandTy = getOperand().getType();
2983 if (
auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
2984 operandTy = complexOperandTy.getElementType();
2987 emitOpError() <<
": result type does not match operand type";
2994OpFoldResult cir::ComplexImagOp::fold(FoldAdaptor adaptor) {
2995 if (!mlir::isa<cir::ComplexType>(getOperand().
getType()))
2998 if (
auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
2999 return complexCreateOp.getOperand(1);
3002 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
3003 return complex ? complex.getImag() :
nullptr;
3010LogicalResult cir::ComplexRealPtrOp::verify() {
3011 mlir::Type resultPointeeTy =
getType().getPointee();
3012 cir::PointerType operandPtrTy = getOperand().getType();
3013 auto operandPointeeTy =
3014 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
3016 if (resultPointeeTy != operandPointeeTy.getElementType()) {
3017 return emitOpError() <<
": result type does not match operand type";
3027LogicalResult cir::ComplexImagPtrOp::verify() {
3028 mlir::Type resultPointeeTy =
getType().getPointee();
3029 cir::PointerType operandPtrTy = getOperand().getType();
3030 auto operandPointeeTy =
3031 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
3033 if (resultPointeeTy != operandPointeeTy.getElementType()) {
3034 return emitOpError()
3035 <<
"cir.complex.imag_ptr result type does not match operand type";
3046 llvm::function_ref<llvm::APInt(
const llvm::APInt &)> func,
3047 bool poisonZero =
false) {
3048 if (mlir::isa_and_present<cir::PoisonAttr>(inputAttr)) {
3053 auto input = mlir::dyn_cast_if_present<IntAttr>(inputAttr);
3057 llvm::APInt inputValue = input.getValue();
3058 if (poisonZero && inputValue.isZero())
3059 return cir::PoisonAttr::get(input.getType());
3061 llvm::APInt resultValue = func(inputValue);
3062 return IntAttr::get(input.getType(), resultValue);
3065OpFoldResult BitClrsbOp::fold(FoldAdaptor adaptor) {
3066 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3067 unsigned resultValue =
3068 inputValue.getBitWidth() - inputValue.getSignificantBits();
3069 return llvm::APInt(inputValue.getBitWidth(), resultValue);
3073OpFoldResult BitClzOp::fold(FoldAdaptor adaptor) {
3076 [](
const llvm::APInt &inputValue) {
3077 unsigned resultValue = inputValue.countLeadingZeros();
3078 return llvm::APInt(inputValue.getBitWidth(), resultValue);
3083OpFoldResult BitCtzOp::fold(FoldAdaptor adaptor) {
3086 [](
const llvm::APInt &inputValue) {
3087 return llvm::APInt(inputValue.getBitWidth(),
3088 inputValue.countTrailingZeros());
3093OpFoldResult BitFfsOp::fold(FoldAdaptor adaptor) {
3094 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3095 unsigned trailingZeros = inputValue.countTrailingZeros();
3097 trailingZeros == inputValue.getBitWidth() ? 0 : trailingZeros + 1;
3098 return llvm::APInt(inputValue.getBitWidth(), result);
3102OpFoldResult BitParityOp::fold(FoldAdaptor adaptor) {
3103 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3104 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount() % 2);
3108OpFoldResult BitPopcountOp::fold(FoldAdaptor adaptor) {
3109 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3110 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount());
3114OpFoldResult BitReverseOp::fold(FoldAdaptor adaptor) {
3115 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3116 return inputValue.reverseBits();
3120OpFoldResult ByteSwapOp::fold(FoldAdaptor adaptor) {
3121 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3122 return inputValue.byteSwap();
3126OpFoldResult RotateOp::fold(FoldAdaptor adaptor) {
3127 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()) ||
3128 mlir::isa_and_present<cir::PoisonAttr>(adaptor.getAmount())) {
3130 return cir::PoisonAttr::get(
getType());
3133 auto input = mlir::dyn_cast_if_present<IntAttr>(adaptor.getInput());
3134 auto amount = mlir::dyn_cast_if_present<IntAttr>(adaptor.getAmount());
3135 if (!input && !amount)
3144 llvm::APInt inputValue;
3146 inputValue = input.getValue();
3147 if (inputValue.isZero() || inputValue.isAllOnes()) {
3153 uint64_t amountValue;
3155 amountValue = amount.getValue().urem(getInput().
getType().getWidth());
3156 if (amountValue == 0) {
3162 if (!input || !amount)
3165 assert(inputValue.getBitWidth() == getInput().
getType().getWidth() &&
3166 "input value must have the same bit width as the input type");
3168 llvm::APInt resultValue;
3170 resultValue = inputValue.rotl(amountValue);
3172 resultValue = inputValue.rotr(amountValue);
3174 return IntAttr::get(input.getContext(), input.getType(), resultValue);
3181void cir::InlineAsmOp::print(OpAsmPrinter &p) {
3182 p <<
'(' << getAsmFlavor() <<
", ";
3187 auto *nameIt = names.begin();
3188 auto *attrIt = getOperandAttrs().begin();
3190 for (mlir::OperandRange ops : getAsmOperands()) {
3191 p << *nameIt <<
" = ";
3194 llvm::interleaveComma(llvm::make_range(ops.begin(), ops.end()), p,
3196 p.printOperand(value);
3197 p <<
" : " << value.getType();
3199 p <<
" (maybe_memory)";
3208 p.printString(getAsmString());
3210 p.printString(getConstraints());
3214 if (getSideEffects())
3215 p <<
" side_effects";
3217 std::array elidedAttrs{
3218 llvm::StringRef(
"asm_flavor"), llvm::StringRef(
"asm_string"),
3219 llvm::StringRef(
"constraints"), llvm::StringRef(
"operand_attrs"),
3220 llvm::StringRef(
"operands_segments"), llvm::StringRef(
"side_effects")};
3221 p.printOptionalAttrDict(getOperation()->getAttrs(), elidedAttrs);
3223 if (
auto v = getRes())
3224 p <<
" -> " << v.getType();
3227void cir::InlineAsmOp::build(OpBuilder &odsBuilder, OperationState &odsState,
3229 StringRef asmString, StringRef constraints,
3230 bool sideEffects, cir::AsmFlavor asmFlavor,
3234 for (
auto operandRange : asmOperands) {
3235 segments.push_back(operandRange.size());
3236 odsState.addOperands(operandRange);
3239 odsState.addAttribute(
3240 "operands_segments",
3241 DenseI32ArrayAttr::get(odsBuilder.getContext(), segments));
3242 odsState.addAttribute(
"asm_string", odsBuilder.getStringAttr(asmString));
3243 odsState.addAttribute(
"constraints", odsBuilder.getStringAttr(constraints));
3244 odsState.addAttribute(
"asm_flavor",
3245 AsmFlavorAttr::get(odsBuilder.getContext(), asmFlavor));
3248 odsState.addAttribute(
"side_effects", odsBuilder.getUnitAttr());
3250 odsState.addAttribute(
"operand_attrs", odsBuilder.getArrayAttr(operandAttrs));
3253ParseResult cir::InlineAsmOp::parse(OpAsmParser &parser,
3254 OperationState &result) {
3257 std::string asmString, constraints;
3259 MLIRContext *ctxt = parser.getBuilder().getContext();
3261 auto error = [&](
const Twine &msg) -> LogicalResult {
3262 return parser.emitError(parser.getCurrentLocation(), msg);
3265 auto expected = [&](
const std::string &
c) {
3266 return error(
"expected '" +
c +
"'");
3269 if (parser.parseLParen().failed())
3270 return expected(
"(");
3272 auto flavor = FieldParser<AsmFlavor, AsmFlavor>::parse(parser);
3274 return error(
"Unknown AsmFlavor");
3276 if (parser.parseComma().failed())
3277 return expected(
",");
3279 auto parseValue = [&](
Value &v) {
3280 OpAsmParser::UnresolvedOperand op;
3282 if (parser.parseOperand(op) || parser.parseColon())
3283 return error(
"can't parse operand");
3286 if (parser.parseType(typ).failed())
3287 return error(
"can't parse operand type");
3289 if (parser.resolveOperand(op, typ, tmp))
3290 return error(
"can't resolve operand");
3292 return mlir::success();
3295 auto parseOperands = [&](llvm::StringRef
name) {
3296 if (parser.parseKeyword(name).failed())
3297 return error(
"expected " + name +
" operands here");
3298 if (parser.parseEqual().failed())
3299 return expected(
"=");
3300 if (parser.parseLSquare().failed())
3301 return expected(
"[");
3304 if (parser.parseOptionalRSquare().succeeded()) {
3305 operandsGroupSizes.push_back(size);
3306 if (parser.parseComma())
3307 return expected(
",");
3308 return mlir::success();
3311 auto parseOperand = [&]() {
3313 if (parseValue(val).succeeded()) {
3314 result.operands.push_back(val);
3317 if (parser.parseOptionalLParen().failed()) {
3318 operandAttrs.push_back(mlir::Attribute());
3319 return mlir::success();
3322 if (parser.parseKeyword(
"maybe_memory").succeeded()) {
3323 operandAttrs.push_back(mlir::UnitAttr::get(ctxt));
3324 if (parser.parseRParen())
3325 return expected(
")");
3326 return mlir::success();
3328 return expected(
"maybe_memory");
3331 return mlir::failure();
3334 if (parser.parseCommaSeparatedList(parseOperand).failed())
3335 return mlir::failure();
3337 if (parser.parseRSquare().failed() || parser.parseComma().failed())
3338 return expected(
"]");
3339 operandsGroupSizes.push_back(size);
3340 return mlir::success();
3343 if (parseOperands(
"out").failed() || parseOperands(
"in").failed() ||
3344 parseOperands(
"in_out").failed())
3345 return error(
"failed to parse operands");
3347 if (parser.parseLBrace())
3348 return expected(
"{");
3349 if (parser.parseString(&asmString))
3350 return error(
"asm string parsing failed");
3351 if (parser.parseString(&constraints))
3352 return error(
"constraints string parsing failed");
3353 if (parser.parseRBrace())
3354 return expected(
"}");
3355 if (parser.parseRParen())
3356 return expected(
")");
3358 if (parser.parseOptionalKeyword(
"side_effects").succeeded())
3359 result.attributes.set(
"side_effects", UnitAttr::get(ctxt));
3361 if (parser.parseOptionalArrow().succeeded() &&
3362 parser.parseType(resType).failed())
3363 return mlir::failure();
3365 if (parser.parseOptionalAttrDict(result.attributes).failed())
3366 return mlir::failure();
3368 result.attributes.set(
"asm_flavor", AsmFlavorAttr::get(ctxt, *flavor));
3369 result.attributes.set(
"asm_string", StringAttr::get(ctxt, asmString));
3370 result.attributes.set(
"constraints", StringAttr::get(ctxt, constraints));
3371 result.attributes.set(
"operand_attrs", ArrayAttr::get(ctxt, operandAttrs));
3372 result.getOrAddProperties<InlineAsmOp::Properties>().operands_segments =
3373 parser.getBuilder().getDenseI32ArrayAttr(operandsGroupSizes);
3375 result.addTypes(TypeRange{resType});
3377 return mlir::success();
3384mlir::LogicalResult cir::ThrowOp::verify() {
3389 if (getNumOperands() != 0) {
3392 return emitOpError() <<
"'type_info' symbol attribute missing";
3402LogicalResult cir::AtomicFetchOp::verify() {
3403 if (getBinop() != cir::AtomicFetchKind::Add &&
3404 getBinop() != cir::AtomicFetchKind::Sub &&
3405 getBinop() != cir::AtomicFetchKind::Max &&
3406 getBinop() != cir::AtomicFetchKind::Min &&
3407 !mlir::isa<cir::IntType>(getVal().
getType()))
3408 return emitError(
"only atomic add, sub, max, and min operation could "
3409 "operate on floating-point values");
3417LogicalResult cir::TypeInfoAttr::verify(
3418 ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError,
3419 ::mlir::Type type, ::mlir::ArrayAttr typeInfoData) {
3421 if (cir::ConstRecordAttr::verify(emitError, type, typeInfoData).failed())
3431void cir::TryOp::getSuccessorRegions(
3432 mlir::RegionBranchPoint point,
3435 if (!point.isParent()) {
3437 RegionSuccessor(getOperation(), getOperation()->getResults()));
3441 regions.push_back(mlir::RegionSuccessor(&getTryRegion()));
3445 for (mlir::Region &handlerRegion : this->getHandlerRegions())
3446 regions.push_back(mlir::RegionSuccessor(&handlerRegion));
3451 mlir::MutableArrayRef<mlir::Region> handlerRegions,
3452 mlir::ArrayAttr handlerTypes) {
3456 for (
const auto [typeIdx, typeAttr] : llvm::enumerate(handlerTypes)) {
3460 if (mlir::isa<cir::CatchAllAttr>(typeAttr)) {
3461 printer <<
"catch all ";
3462 }
else if (mlir::isa<cir::UnwindAttr>(typeAttr)) {
3463 printer <<
"unwind ";
3465 printer <<
"catch [type ";
3466 printer.printAttribute(typeAttr);
3470 printer.printRegion(handlerRegions[typeIdx],
3477 mlir::OpAsmParser &parser,
3479 mlir::ArrayAttr &handlerTypes) {
3481 auto parseCheckedCatcherRegion = [&]() -> mlir::ParseResult {
3482 handlerRegions.emplace_back(
new mlir::Region);
3484 mlir::Region &currRegion = *handlerRegions.back();
3485 mlir::SMLoc regionLoc = parser.getCurrentLocation();
3486 if (parser.parseRegion(currRegion)) {
3487 handlerRegions.clear();
3491 if (currRegion.empty())
3492 return parser.emitError(regionLoc,
"handler region shall not be empty");
3494 if (!(currRegion.back().mightHaveTerminator() &&
3495 currRegion.back().getTerminator()))
3496 return parser.emitError(
3497 regionLoc,
"blocks are expected to be explicitly terminated");
3502 bool hasCatchAll =
false;
3504 while (parser.parseOptionalKeyword(
"catch").succeeded()) {
3505 bool hasLSquare = parser.parseOptionalLSquare().succeeded();
3507 llvm::StringRef attrStr;
3508 if (parser.parseOptionalKeyword(&attrStr, {
"all",
"type"}).failed())
3509 return parser.emitError(parser.getCurrentLocation(),
3510 "expected 'all' or 'type' keyword");
3512 bool isCatchAll = attrStr ==
"all";
3515 return parser.emitError(parser.getCurrentLocation(),
3516 "can't have more than one catch all");
3520 mlir::Attribute exceptionRTTIAttr;
3521 if (!isCatchAll && parser.parseAttribute(exceptionRTTIAttr).failed())
3522 return parser.emitError(parser.getCurrentLocation(),
3523 "expected valid RTTI info attribute");
3525 catcherAttrs.push_back(isCatchAll
3526 ? cir::CatchAllAttr::get(parser.getContext())
3527 : exceptionRTTIAttr);
3529 if (hasLSquare && isCatchAll)
3530 return parser.emitError(parser.getCurrentLocation(),
3531 "catch all dosen't need RTTI info attribute");
3533 if (hasLSquare && parser.parseRSquare().failed())
3534 return parser.emitError(parser.getCurrentLocation(),
3535 "expected `]` after RTTI info attribute");
3537 if (parseCheckedCatcherRegion().failed())
3538 return mlir::failure();
3541 if (parser.parseOptionalKeyword(
"unwind").succeeded()) {
3543 return parser.emitError(parser.getCurrentLocation(),
3544 "unwind can't be used with catch all");
3546 catcherAttrs.push_back(cir::UnwindAttr::get(parser.getContext()));
3547 if (parseCheckedCatcherRegion().failed())
3548 return mlir::failure();
3551 handlerTypes = parser.getBuilder().getArrayAttr(catcherAttrs);
3552 return mlir::success();
3560cir::EhTypeIdOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
3561 Operation *op = symbolTable.lookupNearestSymbolFrom(*
this, getTypeSymAttr());
3562 if (!isa_and_nonnull<GlobalOp>(op))
3563 return emitOpError(
"'")
3564 << getTypeSym() <<
"' does not reference a valid cir.global";
3572#define GET_OP_CLASSES
3573#include "clang/CIR/Dialect/IR/CIROps.cpp.inc"
static const MemRegion * getRegion(const CallEvent &Call, const MutexDescriptor &Descriptor, bool IsLock)
static mlir::LogicalResult checkReturnAndFunction(cir::ReturnOp op, cir::FuncOp function)
static bool isBoolNot(cir::UnaryOp op)
static mlir::ParseResult parseCallCommon(mlir::OpAsmParser &parser, mlir::OperationState &result, bool hasDestinationBlocks=false)
static bool isIntOrBoolCast(cir::CastOp op)
static void printConstant(OpAsmPrinter &p, Attribute value)
static mlir::ParseResult parseOmittedTerminatorRegion(mlir::OpAsmParser &parser, mlir::Region ®ion)
ParseResult parseInlineKindAttr(OpAsmParser &parser, cir::InlineKindAttr &inlineKindAttr)
void printInlineKindAttr(OpAsmPrinter &p, cir::InlineKindAttr inlineKindAttr)
void printVisibilityAttr(OpAsmPrinter &printer, cir::VisibilityAttr &visibility)
static ParseResult parseSwitchFlatOpCases(OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues, SmallVectorImpl< Block * > &caseDestinations, SmallVectorImpl< llvm::SmallVector< OpAsmParser::UnresolvedOperand > > &caseOperands, SmallVectorImpl< llvm::SmallVector< Type > > &caseOperandTypes)
<cases> ::= [ (case (, case )* )?
static LogicalResult 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.
static void printSwitchFlatOpCases(OpAsmPrinter &p, cir::SwitchFlatOp op, Type flagType, mlir::ArrayAttr caseValues, SuccessorRange caseDestinations, OperandRangeRange caseOperands, const TypeRangeRange &caseOperandTypes)
static mlir::ParseResult parseTryCallDestinations(mlir::OpAsmParser &parser, mlir::OperationState &result)
static void printGlobalOpTypeAndInitialValue(OpAsmPrinter &p, cir::GlobalOp op, TypeAttr type, Attribute initAttr, mlir::Region &ctorRegion, mlir::Region &dtorRegion)
static ParseResult parseCIRKeyword(AsmParser &parser, RetTy &result)
Parse an enum from the keyword, return failure if the keyword is not found.
static Value tryFoldCastChain(cir::CastOp op)
void parseVisibilityAttr(OpAsmParser &parser, cir::VisibilityAttr &visibility)
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 printCallCommon(mlir::Operation *op, mlir::FlatSymbolRefAttr calleeSym, mlir::Value indirectCallee, mlir::OpAsmPrinter &printer, bool isNothrow, cir::SideEffect sideEffect, mlir::Block *normalDest=nullptr, mlir::Block *unwindDest=nullptr)
static void printOmittedTerminatorRegion(mlir::OpAsmPrinter &printer, cir::ScopeOp &op, mlir::Region ®ion)
static ParseResult parseConstantValue(OpAsmParser &parser, mlir::Attribute &valueAttr)
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)
__device__ __2f16 float c
void buildTerminatedBody(mlir::OpBuilder &builder, mlir::Location loc)
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 addressSpace()
static bool opCallCallConv()
static bool opScopeCleanupRegion()
static bool supportIFuncAttr()