18#include "mlir/IR/DialectImplementation.h"
19#include "mlir/Interfaces/ControlFlowInterfaces.h"
20#include "mlir/Interfaces/FunctionImplementation.h"
21#include "mlir/Support/LLVM.h"
23#include "clang/CIR/Dialect/IR/CIROpsDialect.cpp.inc"
24#include "clang/CIR/Dialect/IR/CIROpsEnums.cpp.inc"
26#include "llvm/ADT/SetOperations.h"
27#include "llvm/ADT/SmallSet.h"
28#include "llvm/Support/LogicalResult.h"
37struct CIROpAsmDialectInterface :
public OpAsmDialectInterface {
38 using OpAsmDialectInterface::OpAsmDialectInterface;
40 AliasResult getAlias(Type type, raw_ostream &os)
const final {
41 if (
auto recordType = dyn_cast<cir::RecordType>(type)) {
44 os <<
"rec_anon_" <<
recordType.getKindAsStr();
46 os <<
"rec_" << nameAttr.getValue();
47 return AliasResult::OverridableAlias;
49 if (
auto intType = dyn_cast<cir::IntType>(type)) {
52 unsigned width = intType.getWidth();
53 if (width < 8 || !llvm::isPowerOf2_32(width))
54 return AliasResult::NoAlias;
55 os << intType.getAlias();
56 return AliasResult::OverridableAlias;
58 if (
auto voidType = dyn_cast<cir::VoidType>(type)) {
59 os << voidType.getAlias();
60 return AliasResult::OverridableAlias;
63 return AliasResult::NoAlias;
66 AliasResult getAlias(Attribute attr, raw_ostream &os)
const final {
67 if (
auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr)) {
68 os << (boolAttr.getValue() ?
"true" :
"false");
69 return AliasResult::FinalAlias;
71 if (
auto bitfield = mlir::dyn_cast<cir::BitfieldInfoAttr>(attr)) {
72 os <<
"bfi_" << bitfield.getName().str();
73 return AliasResult::FinalAlias;
75 if (
auto dynCastInfoAttr = mlir::dyn_cast<cir::DynamicCastInfoAttr>(attr)) {
76 os << dynCastInfoAttr.getAlias();
77 return AliasResult::FinalAlias;
79 return AliasResult::NoAlias;
84void cir::CIRDialect::initialize() {
89#include "clang/CIR/Dialect/IR/CIROps.cpp.inc"
91 addInterfaces<CIROpAsmDialectInterface>();
94Operation *cir::CIRDialect::materializeConstant(mlir::OpBuilder &builder,
95 mlir::Attribute value,
98 return cir::ConstantOp::create(builder, loc, type,
99 mlir::cast<mlir::TypedAttr>(value));
111 for (
auto en : llvm::enumerate(keywords)) {
112 if (succeeded(parser.parseOptionalKeyword(en.value())))
119template <
typename Ty>
struct EnumTraits {};
121#define REGISTER_ENUM_TYPE(Ty) \
122 template <> struct EnumTraits<cir::Ty> { \
123 static llvm::StringRef stringify(cir::Ty value) { \
124 return stringify##Ty(value); \
126 static unsigned getMaxEnumVal() { return cir::getMaxEnumValFor##Ty(); } \
137template <
typename EnumTy,
typename RetTy = EnumTy>
140 for (
unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
141 names.push_back(EnumTraits<EnumTy>::stringify(
static_cast<EnumTy
>(i)));
145 return static_cast<RetTy
>(defaultValue);
146 return static_cast<RetTy
>(index);
150template <
typename EnumTy,
typename RetTy = EnumTy>
153 for (
unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
154 names.push_back(EnumTraits<EnumTy>::stringify(
static_cast<EnumTy
>(i)));
159 result =
static_cast<RetTy
>(index);
167 Location eLoc = parser.getEncodedSourceLoc(parser.getCurrentLocation());
168 OpBuilder builder(parser.getBuilder().getContext());
173 builder.createBlock(®ion);
175 Block &block = region.back();
177 if (!block.empty() && block.back().hasTrait<OpTrait::IsTerminator>())
181 if (!region.hasOneBlock())
182 return parser.emitError(errLoc,
183 "multi-block region must not omit terminator");
186 builder.setInsertionPointToEnd(&block);
187 cir::YieldOp::create(builder, eLoc);
193 const auto singleNonEmptyBlock = r.hasOneBlock() && !r.back().empty();
194 const auto yieldsNothing = [&r]() {
195 auto y = dyn_cast<cir::YieldOp>(r.back().getTerminator());
196 return y && y.getArgs().empty();
198 return singleNonEmptyBlock && yieldsNothing();
202 cir::VisibilityAttr &visibility) {
203 switch (visibility.getValue()) {
204 case cir::VisibilityKind::Hidden:
207 case cir::VisibilityKind::Protected:
208 printer <<
"protected";
210 case cir::VisibilityKind::Default:
216 cir::VisibilityKind visibilityKind =
218 visibility = cir::VisibilityAttr::get(parser.getContext(), visibilityKind);
226 mlir::Region ®ion) {
227 auto regionLoc = parser.getCurrentLocation();
228 if (parser.parseRegion(region))
237 mlir::Region ®ion) {
238 printer.printRegion(region,
247void cir::AllocaOp::build(mlir::OpBuilder &odsBuilder,
248 mlir::OperationState &odsState, mlir::Type addr,
249 mlir::Type allocaType, llvm::StringRef name,
250 mlir::IntegerAttr alignment) {
251 odsState.addAttribute(getAllocaTypeAttrName(odsState.name),
252 mlir::TypeAttr::get(allocaType));
253 odsState.addAttribute(getNameAttrName(odsState.name),
254 odsBuilder.getStringAttr(name));
256 odsState.addAttribute(getAlignmentAttrName(odsState.name), alignment);
258 odsState.addTypes(addr);
265LogicalResult cir::BreakOp::verify() {
267 if (!getOperation()->getParentOfType<LoopOpInterface>() &&
268 !getOperation()->getParentOfType<SwitchOp>())
269 return emitOpError(
"must be within a loop");
281void cir::ConditionOp::getSuccessorRegions(
287 if (
auto loopOp = dyn_cast<LoopOpInterface>(getOperation()->getParentOp())) {
288 regions.emplace_back(&loopOp.getBody(), loopOp.getBody().getArguments());
289 regions.emplace_back(getOperation(), loopOp->getResults());
296cir::ConditionOp::getMutableSuccessorOperands(RegionSuccessor point) {
298 return MutableOperandRange(getOperation(), 0, 0);
301LogicalResult cir::ConditionOp::verify() {
303 if (!isa<LoopOpInterface>(getOperation()->getParentOp()))
304 return emitOpError(
"condition must be within a conditional region");
313 mlir::Attribute attrType) {
314 if (isa<cir::ConstPtrAttr>(attrType)) {
315 if (!mlir::isa<cir::PointerType>(opType))
316 return op->emitOpError(
317 "pointer constant initializing a non-pointer type");
321 if (isa<cir::ZeroAttr>(attrType)) {
322 if (isa<cir::RecordType, cir::ArrayType, cir::VectorType, cir::ComplexType>(
325 return op->emitOpError(
326 "zero expects struct, array, vector, or complex type");
329 if (mlir::isa<cir::BoolAttr>(attrType)) {
330 if (!mlir::isa<cir::BoolType>(opType))
331 return op->emitOpError(
"result type (")
332 << opType <<
") must be '!cir.bool' for '" << attrType <<
"'";
336 if (mlir::isa<cir::IntAttr, cir::FPAttr>(attrType)) {
337 auto at = cast<TypedAttr>(attrType);
338 if (at.getType() != opType) {
339 return op->emitOpError(
"result type (")
340 << opType <<
") does not match value type (" << at.getType()
346 if (mlir::isa<cir::ConstArrayAttr, cir::ConstVectorAttr,
347 cir::ConstComplexAttr, cir::ConstRecordAttr,
348 cir::GlobalViewAttr, cir::PoisonAttr, cir::TypeInfoAttr,
349 cir::VTableAttr>(attrType))
352 assert(isa<TypedAttr>(attrType) &&
"What else could we be looking at here?");
353 return op->emitOpError(
"global with type ")
354 << cast<TypedAttr>(attrType).getType() <<
" not yet supported";
357LogicalResult cir::ConstantOp::verify() {
364OpFoldResult cir::ConstantOp::fold(FoldAdaptor ) {
372LogicalResult cir::ContinueOp::verify() {
373 if (!getOperation()->getParentOfType<LoopOpInterface>())
374 return emitOpError(
"must be within a loop");
382LogicalResult cir::CastOp::verify() {
383 mlir::Type resType =
getType();
384 mlir::Type srcType = getSrc().getType();
386 if (mlir::isa<cir::VectorType>(srcType) &&
387 mlir::isa<cir::VectorType>(resType)) {
390 srcType = mlir::dyn_cast<cir::VectorType>(srcType).getElementType();
391 resType = mlir::dyn_cast<cir::VectorType>(resType).getElementType();
395 case cir::CastKind::int_to_bool: {
396 if (!mlir::isa<cir::BoolType>(resType))
397 return emitOpError() <<
"requires !cir.bool type for result";
398 if (!mlir::isa<cir::IntType>(srcType))
399 return emitOpError() <<
"requires !cir.int type for source";
402 case cir::CastKind::ptr_to_bool: {
403 if (!mlir::isa<cir::BoolType>(resType))
404 return emitOpError() <<
"requires !cir.bool type for result";
405 if (!mlir::isa<cir::PointerType>(srcType))
406 return emitOpError() <<
"requires !cir.ptr type for source";
409 case cir::CastKind::integral: {
410 if (!mlir::isa<cir::IntType>(resType))
411 return emitOpError() <<
"requires !cir.int type for result";
412 if (!mlir::isa<cir::IntType>(srcType))
413 return emitOpError() <<
"requires !cir.int type for source";
416 case cir::CastKind::array_to_ptrdecay: {
417 const auto arrayPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
418 const auto flatPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
419 if (!arrayPtrTy || !flatPtrTy)
420 return emitOpError() <<
"requires !cir.ptr type for source and result";
425 case cir::CastKind::bitcast: {
427 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
428 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
430 if (srcPtrTy && resPtrTy) {
436 case cir::CastKind::floating: {
437 if (!mlir::isa<cir::FPTypeInterface>(srcType) ||
438 !mlir::isa<cir::FPTypeInterface>(resType))
439 return emitOpError() <<
"requires !cir.float type for source and result";
442 case cir::CastKind::float_to_int: {
443 if (!mlir::isa<cir::FPTypeInterface>(srcType))
444 return emitOpError() <<
"requires !cir.float type for source";
445 if (!mlir::dyn_cast<cir::IntType>(resType))
446 return emitOpError() <<
"requires !cir.int type for result";
449 case cir::CastKind::int_to_ptr: {
450 if (!mlir::dyn_cast<cir::IntType>(srcType))
451 return emitOpError() <<
"requires !cir.int type for source";
452 if (!mlir::dyn_cast<cir::PointerType>(resType))
453 return emitOpError() <<
"requires !cir.ptr type for result";
456 case cir::CastKind::ptr_to_int: {
457 if (!mlir::dyn_cast<cir::PointerType>(srcType))
458 return emitOpError() <<
"requires !cir.ptr type for source";
459 if (!mlir::dyn_cast<cir::IntType>(resType))
460 return emitOpError() <<
"requires !cir.int type for result";
463 case cir::CastKind::float_to_bool: {
464 if (!mlir::isa<cir::FPTypeInterface>(srcType))
465 return emitOpError() <<
"requires !cir.float type for source";
466 if (!mlir::isa<cir::BoolType>(resType))
467 return emitOpError() <<
"requires !cir.bool type for result";
470 case cir::CastKind::bool_to_int: {
471 if (!mlir::isa<cir::BoolType>(srcType))
472 return emitOpError() <<
"requires !cir.bool type for source";
473 if (!mlir::isa<cir::IntType>(resType))
474 return emitOpError() <<
"requires !cir.int type for result";
477 case cir::CastKind::int_to_float: {
478 if (!mlir::isa<cir::IntType>(srcType))
479 return emitOpError() <<
"requires !cir.int type for source";
480 if (!mlir::isa<cir::FPTypeInterface>(resType))
481 return emitOpError() <<
"requires !cir.float type for result";
484 case cir::CastKind::bool_to_float: {
485 if (!mlir::isa<cir::BoolType>(srcType))
486 return emitOpError() <<
"requires !cir.bool type for source";
487 if (!mlir::isa<cir::FPTypeInterface>(resType))
488 return emitOpError() <<
"requires !cir.float type for result";
491 case cir::CastKind::address_space: {
492 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
493 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
494 if (!srcPtrTy || !resPtrTy)
495 return emitOpError() <<
"requires !cir.ptr type for source and result";
496 if (srcPtrTy.getPointee() != resPtrTy.getPointee())
497 return emitOpError() <<
"requires two types differ in addrspace only";
500 case cir::CastKind::float_to_complex: {
501 if (!mlir::isa<cir::FPTypeInterface>(srcType))
502 return emitOpError() <<
"requires !cir.float type for source";
503 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
505 return emitOpError() <<
"requires !cir.complex type for result";
506 if (srcType != resComplexTy.getElementType())
507 return emitOpError() <<
"requires source type match result element type";
510 case cir::CastKind::int_to_complex: {
511 if (!mlir::isa<cir::IntType>(srcType))
512 return emitOpError() <<
"requires !cir.int type for source";
513 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
515 return emitOpError() <<
"requires !cir.complex type for result";
516 if (srcType != resComplexTy.getElementType())
517 return emitOpError() <<
"requires source type match result element type";
520 case cir::CastKind::float_complex_to_real: {
521 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
523 return emitOpError() <<
"requires !cir.complex type for source";
524 if (!mlir::isa<cir::FPTypeInterface>(resType))
525 return emitOpError() <<
"requires !cir.float type for result";
526 if (srcComplexTy.getElementType() != resType)
527 return emitOpError() <<
"requires source element type match result type";
530 case cir::CastKind::int_complex_to_real: {
531 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
533 return emitOpError() <<
"requires !cir.complex type for source";
534 if (!mlir::isa<cir::IntType>(resType))
535 return emitOpError() <<
"requires !cir.int type for result";
536 if (srcComplexTy.getElementType() != resType)
537 return emitOpError() <<
"requires source element type match result type";
540 case cir::CastKind::float_complex_to_bool: {
541 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
542 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
544 <<
"requires floating point !cir.complex type for source";
545 if (!mlir::isa<cir::BoolType>(resType))
546 return emitOpError() <<
"requires !cir.bool type for result";
549 case cir::CastKind::int_complex_to_bool: {
550 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
551 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
553 <<
"requires floating point !cir.complex type for source";
554 if (!mlir::isa<cir::BoolType>(resType))
555 return emitOpError() <<
"requires !cir.bool type for result";
558 case cir::CastKind::float_complex: {
559 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
560 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
562 <<
"requires floating point !cir.complex type for source";
563 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
564 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
566 <<
"requires floating point !cir.complex type for result";
569 case cir::CastKind::float_complex_to_int_complex: {
570 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
571 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
573 <<
"requires floating point !cir.complex type for source";
574 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
575 if (!resComplexTy || !resComplexTy.isIntegerComplex())
576 return emitOpError() <<
"requires integer !cir.complex type for result";
579 case cir::CastKind::int_complex: {
580 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
581 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
582 return emitOpError() <<
"requires integer !cir.complex type for source";
583 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
584 if (!resComplexTy || !resComplexTy.isIntegerComplex())
585 return emitOpError() <<
"requires integer !cir.complex type for result";
588 case cir::CastKind::int_complex_to_float_complex: {
589 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
590 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
591 return emitOpError() <<
"requires integer !cir.complex type for source";
592 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
593 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
595 <<
"requires floating point !cir.complex type for result";
599 llvm_unreachable(
"Unknown CastOp kind?");
604 auto kind = op.getKind();
605 return kind == cir::CastKind::bool_to_int ||
606 kind == cir::CastKind::int_to_bool || kind == cir::CastKind::integral;
610 cir::CastOp head = op, tail = op;
616 op = head.getSrc().getDefiningOp<cir::CastOp>();
624 if (head.getKind() == cir::CastKind::bool_to_int &&
625 tail.getKind() == cir::CastKind::int_to_bool)
626 return head.getSrc();
631 if (head.getKind() == cir::CastKind::int_to_bool &&
632 tail.getKind() == cir::CastKind::int_to_bool)
633 return head.getResult();
638OpFoldResult cir::CastOp::fold(FoldAdaptor adaptor) {
639 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getSrc())) {
641 return cir::PoisonAttr::get(getContext(),
getType());
646 case cir::CastKind::integral: {
650 auto foldOrder = getSrc().getDefiningOp()->fold(foldResults);
651 if (foldOrder.succeeded() && mlir::isa<mlir::Attribute>(foldResults[0]))
652 return mlir::cast<mlir::Attribute>(foldResults[0]);
655 case cir::CastKind::bitcast:
656 case cir::CastKind::address_space:
657 case cir::CastKind::float_complex:
658 case cir::CastKind::int_complex: {
672mlir::OperandRange cir::CallOp::getArgOperands() {
674 return getArgs().drop_front(1);
678mlir::MutableOperandRange cir::CallOp::getArgOperandsMutable() {
679 mlir::MutableOperandRange args = getArgsMutable();
681 return args.slice(1, args.size() - 1);
685mlir::Value cir::CallOp::getIndirectCall() {
686 assert(isIndirect());
687 return getOperand(0);
691Value cir::CallOp::getArgOperand(
unsigned i) {
694 return getOperand(i);
698unsigned cir::CallOp::getNumArgOperands() {
700 return this->getOperation()->getNumOperands() - 1;
701 return this->getOperation()->getNumOperands();
705 mlir::OperationState &result) {
708 mlir::FlatSymbolRefAttr calleeAttr;
713 .parseOptionalAttribute(calleeAttr, CIRDialect::getCalleeAttrName(),
716 OpAsmParser::UnresolvedOperand indirectVal;
718 if (parser.parseOperand(indirectVal).failed())
720 ops.push_back(indirectVal);
723 if (parser.parseLParen())
724 return mlir::failure();
726 opsLoc = parser.getCurrentLocation();
727 if (parser.parseOperandList(ops))
728 return mlir::failure();
729 if (parser.parseRParen())
730 return mlir::failure();
732 if (parser.parseOptionalKeyword(
"nothrow").succeeded())
733 result.addAttribute(CIRDialect::getNoThrowAttrName(),
734 mlir::UnitAttr::get(parser.getContext()));
736 if (parser.parseOptionalKeyword(
"side_effect").succeeded()) {
737 if (parser.parseLParen().failed())
739 cir::SideEffect sideEffect;
742 if (parser.parseRParen().failed())
744 auto attr = cir::SideEffectAttr::get(parser.getContext(), sideEffect);
745 result.addAttribute(CIRDialect::getSideEffectAttrName(), attr);
748 if (parser.parseOptionalAttrDict(result.attributes))
749 return ::mlir::failure();
751 if (parser.parseColon())
752 return ::mlir::failure();
754 mlir::FunctionType opsFnTy;
755 if (parser.parseType(opsFnTy))
756 return mlir::failure();
758 allResultTypes = opsFnTy.getResults();
759 result.addTypes(allResultTypes);
761 if (parser.resolveOperands(ops, opsFnTy.getInputs(), opsLoc, result.operands))
762 return mlir::failure();
764 return mlir::success();
768 mlir::FlatSymbolRefAttr calleeSym,
769 mlir::Value indirectCallee,
770 mlir::OpAsmPrinter &printer,
bool isNothrow,
771 cir::SideEffect sideEffect) {
774 auto callLikeOp = mlir::cast<cir::CIRCallOpInterface>(op);
775 auto ops = callLikeOp.getArgOperands();
779 printer.printAttributeWithoutType(calleeSym);
782 assert(indirectCallee);
783 printer << indirectCallee;
785 printer <<
"(" << ops <<
")";
788 printer <<
" nothrow";
790 if (sideEffect != cir::SideEffect::All) {
791 printer <<
" side_effect(";
792 printer << stringifySideEffect(sideEffect);
796 printer.printOptionalAttrDict(op->getAttrs(),
797 {CIRDialect::getCalleeAttrName(),
798 CIRDialect::getNoThrowAttrName(),
799 CIRDialect::getSideEffectAttrName()});
802 printer.printFunctionalType(op->getOperands().getTypes(),
803 op->getResultTypes());
806mlir::ParseResult cir::CallOp::parse(mlir::OpAsmParser &parser,
807 mlir::OperationState &result) {
811void cir::CallOp::print(mlir::OpAsmPrinter &p) {
812 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() :
nullptr;
813 cir::SideEffect sideEffect = getSideEffect();
814 printCallCommon(*
this, getCalleeAttr(), indirectCallee, p, getNothrow(),
820 SymbolTableCollection &symbolTable) {
822 op->getAttrOfType<FlatSymbolRefAttr>(CIRDialect::getCalleeAttrName());
825 return mlir::success();
828 auto fn = symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(op, fnAttr);
830 return op->emitOpError() <<
"'" << fnAttr.getValue()
831 <<
"' does not reference a valid function";
833 auto callIf = dyn_cast<cir::CIRCallOpInterface>(op);
834 assert(callIf &&
"expected CIR call interface to be always available");
838 auto fnType = fn.getFunctionType();
839 if (!fn.getNoProto()) {
840 unsigned numCallOperands = callIf.getNumArgOperands();
841 unsigned numFnOpOperands = fnType.getNumInputs();
843 if (!fnType.isVarArg() && numCallOperands != numFnOpOperands)
844 return op->emitOpError(
"incorrect number of operands for callee");
845 if (fnType.isVarArg() && numCallOperands < numFnOpOperands)
846 return op->emitOpError(
"too few operands for callee");
848 for (
unsigned i = 0, e = numFnOpOperands; i != e; ++i)
849 if (callIf.getArgOperand(i).getType() != fnType.getInput(i))
850 return op->emitOpError(
"operand type mismatch: expected operand type ")
851 << fnType.getInput(i) <<
", but provided "
852 << op->getOperand(i).getType() <<
" for operand number " << i;
858 if (fnType.hasVoidReturn() && op->getNumResults() != 0)
859 return op->emitOpError(
"callee returns void but call has results");
862 if (!fnType.hasVoidReturn() && op->getNumResults() != 1)
863 return op->emitOpError(
"incorrect number of results for callee");
866 if (!fnType.hasVoidReturn() &&
867 op->getResultTypes().front() != fnType.getReturnType()) {
868 return op->emitOpError(
"result type mismatch: expected ")
869 << fnType.getReturnType() <<
", but provided "
870 << op->getResult(0).getType();
873 return mlir::success();
877cir::CallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
886 cir::FuncOp function) {
888 if (op.getNumOperands() > 1)
889 return op.emitOpError() <<
"expects at most 1 return operand";
892 auto expectedTy = function.getFunctionType().getReturnType();
894 (op.getNumOperands() == 0 ? cir::VoidType::get(op.getContext())
895 : op.getOperand(0).getType());
896 if (actualTy != expectedTy)
897 return op.emitOpError() <<
"returns " << actualTy
898 <<
" but enclosing function returns " << expectedTy;
900 return mlir::success();
903mlir::LogicalResult cir::ReturnOp::verify() {
906 auto *fnOp = getOperation()->getParentOp();
907 while (!isa<cir::FuncOp>(fnOp))
908 fnOp = fnOp->getParentOp();
921ParseResult cir::IfOp::parse(OpAsmParser &parser, OperationState &result) {
923 result.regions.reserve(2);
924 Region *thenRegion = result.addRegion();
925 Region *elseRegion = result.addRegion();
927 mlir::Builder &builder = parser.getBuilder();
928 OpAsmParser::UnresolvedOperand cond;
929 Type boolType = cir::BoolType::get(builder.getContext());
931 if (parser.parseOperand(cond) ||
932 parser.resolveOperand(cond, boolType, result.operands))
936 mlir::SMLoc parseThenLoc = parser.getCurrentLocation();
937 if (parser.parseRegion(*thenRegion, {}, {}))
944 if (!parser.parseOptionalKeyword(
"else")) {
945 mlir::SMLoc parseElseLoc = parser.getCurrentLocation();
946 if (parser.parseRegion(*elseRegion, {}, {}))
953 if (parser.parseOptionalAttrDict(result.attributes))
958void cir::IfOp::print(OpAsmPrinter &p) {
959 p <<
" " << getCondition() <<
" ";
960 mlir::Region &thenRegion = this->getThenRegion();
961 p.printRegion(thenRegion,
966 mlir::Region &elseRegion = this->getElseRegion();
967 if (!elseRegion.empty()) {
969 p.printRegion(elseRegion,
974 p.printOptionalAttrDict(getOperation()->getAttrs());
980 cir::YieldOp::create(builder, loc);
988void cir::IfOp::getSuccessorRegions(mlir::RegionBranchPoint point,
989 SmallVectorImpl<RegionSuccessor> ®ions) {
991 if (!point.isParent()) {
993 RegionSuccessor(getOperation(), getOperation()->getResults()));
998 Region *elseRegion = &this->getElseRegion();
999 if (elseRegion->empty())
1000 elseRegion =
nullptr;
1003 regions.push_back(RegionSuccessor(&getThenRegion()));
1006 regions.push_back(RegionSuccessor(elseRegion));
1011void cir::IfOp::build(OpBuilder &builder, OperationState &result,
Value cond,
1014 assert(thenBuilder &&
"the builder callback for 'then' must be present");
1015 result.addOperands(cond);
1017 OpBuilder::InsertionGuard guard(builder);
1018 Region *thenRegion = result.addRegion();
1019 builder.createBlock(thenRegion);
1020 thenBuilder(builder, result.location);
1022 Region *elseRegion = result.addRegion();
1023 if (!withElseRegion)
1026 builder.createBlock(elseRegion);
1027 elseBuilder(builder, result.location);
1039void cir::ScopeOp::getSuccessorRegions(
1040 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1042 if (!point.isParent()) {
1043 regions.push_back(RegionSuccessor(getOperation(), getODSResults(0)));
1048 regions.push_back(RegionSuccessor(&getScopeRegion()));
1051void cir::ScopeOp::build(
1052 OpBuilder &builder, OperationState &result,
1053 function_ref<
void(OpBuilder &, Type &, Location)> scopeBuilder) {
1054 assert(scopeBuilder &&
"the builder callback for 'then' must be present");
1056 OpBuilder::InsertionGuard guard(builder);
1057 Region *scopeRegion = result.addRegion();
1058 builder.createBlock(scopeRegion);
1062 scopeBuilder(builder, yieldTy, result.location);
1065 result.addTypes(TypeRange{yieldTy});
1068void cir::ScopeOp::build(
1069 OpBuilder &builder, OperationState &result,
1070 function_ref<
void(OpBuilder &, Location)> scopeBuilder) {
1071 assert(scopeBuilder &&
"the builder callback for 'then' must be present");
1072 OpBuilder::InsertionGuard guard(builder);
1073 Region *scopeRegion = result.addRegion();
1074 builder.createBlock(scopeRegion);
1076 scopeBuilder(builder, result.location);
1079LogicalResult cir::ScopeOp::verify() {
1081 return emitOpError() <<
"cir.scope must not be empty since it should "
1082 "include at least an implicit cir.yield ";
1085 mlir::Block &lastBlock =
getRegion().back();
1086 if (lastBlock.empty() || !lastBlock.mightHaveTerminator() ||
1087 !lastBlock.getTerminator()->hasTrait<OpTrait::IsTerminator>())
1088 return emitOpError() <<
"last block of cir.scope must be terminated";
1096mlir::SuccessorOperands cir::BrOp::getSuccessorOperands(
unsigned index) {
1097 assert(index == 0 &&
"invalid successor index");
1098 return mlir::SuccessorOperands(getDestOperandsMutable());
1109mlir::SuccessorOperands cir::BrCondOp::getSuccessorOperands(
unsigned index) {
1110 assert(index < getNumSuccessors() &&
"invalid successor index");
1111 return SuccessorOperands(index == 0 ? getDestOperandsTrueMutable()
1112 : getDestOperandsFalseMutable());
1116 if (IntegerAttr condAttr = dyn_cast_if_present<IntegerAttr>(operands.front()))
1117 return condAttr.getValue().isOne() ? getDestTrue() : getDestFalse();
1125void cir::CaseOp::getSuccessorRegions(
1126 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1127 if (!point.isParent()) {
1129 RegionSuccessor(getOperation(), getOperation()->getResults()));
1132 regions.push_back(RegionSuccessor(&getCaseRegion()));
1135void cir::CaseOp::build(OpBuilder &builder, OperationState &result,
1136 ArrayAttr value, CaseOpKind kind,
1137 OpBuilder::InsertPoint &insertPoint) {
1138 OpBuilder::InsertionGuard guardSwitch(builder);
1139 result.addAttribute(
"value", value);
1140 result.getOrAddProperties<Properties>().kind =
1141 cir::CaseOpKindAttr::get(builder.getContext(), kind);
1142 Region *caseRegion = result.addRegion();
1143 builder.createBlock(caseRegion);
1145 insertPoint = builder.saveInsertionPoint();
1153 mlir::OpAsmParser::UnresolvedOperand &cond,
1154 mlir::Type &condType) {
1155 cir::IntType intCondType;
1157 if (parser.parseLParen())
1158 return mlir::failure();
1160 if (parser.parseOperand(cond))
1161 return mlir::failure();
1162 if (parser.parseColon())
1163 return mlir::failure();
1164 if (parser.parseCustomTypeWithFallback(intCondType))
1165 return mlir::failure();
1166 condType = intCondType;
1168 if (parser.parseRParen())
1169 return mlir::failure();
1170 if (parser.parseRegion(regions, {}, {}))
1173 return mlir::success();
1177 mlir::Region &bodyRegion, mlir::Value condition,
1178 mlir::Type condType) {
1182 p.printStrippedAttrOrType(condType);
1186 p.printRegion(bodyRegion,
false,
1190void cir::SwitchOp::getSuccessorRegions(
1191 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ion) {
1192 if (!point.isParent()) {
1194 RegionSuccessor(getOperation(), getOperation()->getResults()));
1198 region.push_back(RegionSuccessor(&getBody()));
1201void cir::SwitchOp::build(OpBuilder &builder, OperationState &result,
1203 assert(switchBuilder &&
"the builder callback for regions must be present");
1204 OpBuilder::InsertionGuard guardSwitch(builder);
1205 Region *switchRegion = result.addRegion();
1206 builder.createBlock(switchRegion);
1207 result.addOperands({cond});
1208 switchBuilder(builder, result.location, result);
1212 walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
1214 if (isa<cir::SwitchOp>(op) && op != *
this)
1215 return WalkResult::skip();
1217 if (
auto caseOp = dyn_cast<cir::CaseOp>(op))
1218 cases.push_back(caseOp);
1220 return WalkResult::advance();
1225 collectCases(cases);
1227 if (getBody().empty())
1230 if (!isa<YieldOp>(getBody().front().back()))
1233 if (!llvm::all_of(getBody().front(),
1234 [](Operation &op) {
return isa<CaseOp, YieldOp>(op); }))
1237 return llvm::all_of(cases, [
this](CaseOp op) {
1238 return op->getParentOfType<SwitchOp>() == *
this;
1246void cir::SwitchFlatOp::build(OpBuilder &builder, OperationState &result,
1247 Value value, Block *defaultDestination,
1248 ValueRange defaultOperands,
1250 BlockRange caseDestinations,
1253 std::vector<mlir::Attribute> caseValuesAttrs;
1254 for (
const APInt &val : caseValues)
1255 caseValuesAttrs.push_back(cir::IntAttr::get(value.getType(), val));
1256 mlir::ArrayAttr attrs = ArrayAttr::get(builder.getContext(), caseValuesAttrs);
1258 build(builder, result, value, defaultOperands, caseOperands, attrs,
1259 defaultDestination, caseDestinations);
1265 OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues,
1266 SmallVectorImpl<Block *> &caseDestinations,
1270 if (failed(parser.parseLSquare()))
1272 if (succeeded(parser.parseOptionalRSquare()))
1276 auto parseCase = [&]() {
1278 if (failed(parser.parseInteger(value)))
1281 values.push_back(cir::IntAttr::get(flagType, value));
1286 if (parser.parseColon() || parser.parseSuccessor(destination))
1288 if (!parser.parseOptionalLParen()) {
1289 if (parser.parseOperandList(operands, OpAsmParser::Delimiter::None,
1291 parser.parseColonTypeList(operandTypes) || parser.parseRParen())
1294 caseDestinations.push_back(destination);
1295 caseOperands.emplace_back(operands);
1296 caseOperandTypes.emplace_back(operandTypes);
1299 if (failed(parser.parseCommaSeparatedList(parseCase)))
1302 caseValues = ArrayAttr::get(flagType.getContext(), values);
1304 return parser.parseRSquare();
1308 Type flagType, mlir::ArrayAttr caseValues,
1309 SuccessorRange caseDestinations,
1310 OperandRangeRange caseOperands,
1311 const TypeRangeRange &caseOperandTypes) {
1321 llvm::zip(caseValues, caseDestinations),
1324 mlir::Attribute a = std::get<0>(i);
1325 p << mlir::cast<cir::IntAttr>(a).getValue();
1327 p.printSuccessorAndUseList(std::get<1>(i), caseOperands[index++]);
1342 mlir::Attribute &valueAttr) {
1344 return parser.parseAttribute(valueAttr,
"value", attr);
1348 p.printAttribute(value);
1351mlir::LogicalResult cir::GlobalOp::verify() {
1354 if (getInitialValue().has_value()) {
1366void cir::GlobalOp::build(
1367 OpBuilder &odsBuilder, OperationState &odsState, llvm::StringRef sym_name,
1368 mlir::Type sym_type,
bool isConstant, cir::GlobalLinkageKind linkage,
1369 function_ref<
void(OpBuilder &, Location)> ctorBuilder,
1370 function_ref<
void(OpBuilder &, Location)> dtorBuilder) {
1371 odsState.addAttribute(getSymNameAttrName(odsState.name),
1372 odsBuilder.getStringAttr(sym_name));
1373 odsState.addAttribute(getSymTypeAttrName(odsState.name),
1374 mlir::TypeAttr::get(sym_type));
1376 odsState.addAttribute(getConstantAttrName(odsState.name),
1377 odsBuilder.getUnitAttr());
1379 cir::GlobalLinkageKindAttr linkageAttr =
1380 cir::GlobalLinkageKindAttr::get(odsBuilder.getContext(), linkage);
1381 odsState.addAttribute(getLinkageAttrName(odsState.name), linkageAttr);
1383 Region *ctorRegion = odsState.addRegion();
1385 odsBuilder.createBlock(ctorRegion);
1386 ctorBuilder(odsBuilder, odsState.location);
1389 Region *dtorRegion = odsState.addRegion();
1391 odsBuilder.createBlock(dtorRegion);
1392 dtorBuilder(odsBuilder, odsState.location);
1395 odsState.addAttribute(getGlobalVisibilityAttrName(odsState.name),
1396 cir::VisibilityAttr::get(odsBuilder.getContext()));
1404void cir::GlobalOp::getSuccessorRegions(
1405 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1407 if (!point.isParent()) {
1409 RegionSuccessor(getOperation(), getOperation()->getResults()));
1414 Region *ctorRegion = &this->getCtorRegion();
1415 if (ctorRegion->empty())
1416 ctorRegion =
nullptr;
1419 Region *dtorRegion = &this->getCtorRegion();
1420 if (dtorRegion->empty())
1421 dtorRegion =
nullptr;
1425 regions.push_back(RegionSuccessor(ctorRegion));
1427 regions.push_back(RegionSuccessor(dtorRegion));
1431 TypeAttr type, Attribute initAttr,
1432 mlir::Region &ctorRegion,
1433 mlir::Region &dtorRegion) {
1434 auto printType = [&]() { p <<
": " << type; };
1435 if (!op.isDeclaration()) {
1437 if (!ctorRegion.empty()) {
1441 p.printRegion(ctorRegion,
1450 if (!dtorRegion.empty()) {
1452 p.printRegion(dtorRegion,
1463 Attribute &initialValueAttr,
1464 mlir::Region &ctorRegion,
1465 mlir::Region &dtorRegion) {
1467 if (parser.parseOptionalEqual().failed()) {
1470 if (parser.parseColonType(opTy))
1475 if (!parser.parseOptionalKeyword(
"ctor")) {
1476 if (parser.parseColonType(opTy))
1478 auto parseLoc = parser.getCurrentLocation();
1479 if (parser.parseRegion(ctorRegion, {}, {}))
1490 assert(mlir::isa<mlir::TypedAttr>(initialValueAttr) &&
1491 "Non-typed attrs shouldn't appear here.");
1492 auto typedAttr = mlir::cast<mlir::TypedAttr>(initialValueAttr);
1493 opTy = typedAttr.getType();
1498 if (!parser.parseOptionalKeyword(
"dtor")) {
1499 auto parseLoc = parser.getCurrentLocation();
1500 if (parser.parseRegion(dtorRegion, {}, {}))
1507 typeAttr = TypeAttr::get(opTy);
1516cir::GetGlobalOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1519 mlir::Operation *op =
1520 symbolTable.lookupNearestSymbolFrom(*
this, getNameAttr());
1521 if (op ==
nullptr || !(isa<GlobalOp>(op) || isa<FuncOp>(op)))
1522 return emitOpError(
"'")
1524 <<
"' does not reference a valid cir.global or cir.func";
1527 if (
auto g = dyn_cast<GlobalOp>(op)) {
1528 symTy = g.getSymType();
1531 }
else if (
auto f = dyn_cast<FuncOp>(op)) {
1532 symTy = f.getFunctionType();
1534 llvm_unreachable(
"Unexpected operation for GetGlobalOp");
1537 auto resultType = dyn_cast<PointerType>(getAddr().
getType());
1538 if (!resultType || symTy != resultType.getPointee())
1539 return emitOpError(
"result type pointee type '")
1540 << resultType.getPointee() <<
"' does not match type " << symTy
1541 <<
" of the global @" <<
getName();
1551cir::VTableAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1557 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*
this, getNameAttr());
1559 return emitOpError(
"'")
1560 <<
name <<
"' does not reference a valid cir.global";
1561 std::optional<mlir::Attribute> init = op.getInitialValue();
1564 if (!isa<cir::VTableAttr>(*init))
1565 return emitOpError(
"Expected #cir.vtable in initializer for global '")
1575cir::VTTAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1584 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*
this, getNameAttr());
1586 return emitOpError(
"'")
1587 <<
name <<
"' does not reference a valid cir.global";
1588 std::optional<mlir::Attribute> init = op.getInitialValue();
1591 if (!isa<cir::ConstArrayAttr>(*init))
1593 "Expected constant array in initializer for global VTT '")
1598LogicalResult cir::VTTAddrPointOp::verify() {
1600 if (
getName() && getSymAddr())
1601 return emitOpError(
"should use either a symbol or value, but not both");
1607 mlir::Type resultType = getAddr().getType();
1608 mlir::Type resTy = cir::PointerType::get(
1609 cir::PointerType::get(cir::VoidType::get(getContext())));
1611 if (resultType != resTy)
1612 return emitOpError(
"result type must be ")
1613 << resTy <<
", but provided result type is " << resultType;
1625void cir::FuncOp::build(OpBuilder &builder, OperationState &result,
1626 StringRef name, FuncType type,
1627 GlobalLinkageKind linkage) {
1629 result.addAttribute(SymbolTable::getSymbolAttrName(),
1630 builder.getStringAttr(name));
1631 result.addAttribute(getFunctionTypeAttrName(result.name),
1632 TypeAttr::get(type));
1633 result.addAttribute(
1635 GlobalLinkageKindAttr::get(builder.getContext(), linkage));
1636 result.addAttribute(getGlobalVisibilityAttrName(result.name),
1637 cir::VisibilityAttr::get(builder.getContext()));
1640ParseResult cir::FuncOp::parse(OpAsmParser &parser, OperationState &state) {
1641 llvm::SMLoc loc = parser.getCurrentLocation();
1642 mlir::Builder &builder = parser.getBuilder();
1644 mlir::StringAttr builtinNameAttr = getBuiltinAttrName(state.name);
1645 mlir::StringAttr coroutineNameAttr = getCoroutineAttrName(state.name);
1646 mlir::StringAttr lambdaNameAttr = getLambdaAttrName(state.name);
1647 mlir::StringAttr noProtoNameAttr = getNoProtoAttrName(state.name);
1648 mlir::StringAttr visNameAttr = getSymVisibilityAttrName(state.name);
1649 mlir::StringAttr visibilityNameAttr = getGlobalVisibilityAttrName(state.name);
1650 mlir::StringAttr dsoLocalNameAttr = getDsoLocalAttrName(state.name);
1652 if (::mlir::succeeded(parser.parseOptionalKeyword(builtinNameAttr.strref())))
1653 state.addAttribute(builtinNameAttr, parser.getBuilder().getUnitAttr());
1654 if (::mlir::succeeded(
1655 parser.parseOptionalKeyword(coroutineNameAttr.strref())))
1656 state.addAttribute(coroutineNameAttr, parser.getBuilder().getUnitAttr());
1657 if (::mlir::succeeded(parser.parseOptionalKeyword(lambdaNameAttr.strref())))
1658 state.addAttribute(lambdaNameAttr, parser.getBuilder().getUnitAttr());
1659 if (parser.parseOptionalKeyword(noProtoNameAttr).succeeded())
1660 state.addAttribute(noProtoNameAttr, parser.getBuilder().getUnitAttr());
1664 GlobalLinkageKindAttr::get(
1665 parser.getContext(),
1667 parser, GlobalLinkageKind::ExternalLinkage)));
1669 ::llvm::StringRef visAttrStr;
1670 if (parser.parseOptionalKeyword(&visAttrStr, {
"private",
"public",
"nested"})
1672 state.addAttribute(visNameAttr,
1673 parser.getBuilder().getStringAttr(visAttrStr));
1676 cir::VisibilityAttr cirVisibilityAttr;
1678 state.addAttribute(visibilityNameAttr, cirVisibilityAttr);
1680 if (parser.parseOptionalKeyword(dsoLocalNameAttr).succeeded())
1681 state.addAttribute(dsoLocalNameAttr, parser.getBuilder().getUnitAttr());
1683 StringAttr nameAttr;
1684 if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
1690 bool isVariadic =
false;
1691 if (function_interface_impl::parseFunctionSignatureWithArguments(
1692 parser,
true, arguments, isVariadic, resultTypes,
1696 for (OpAsmParser::Argument &arg : arguments)
1697 argTypes.push_back(
arg.type);
1699 if (resultTypes.size() > 1) {
1700 return parser.emitError(
1701 loc,
"functions with multiple return types are not supported");
1704 mlir::Type returnType =
1705 (resultTypes.empty() ? cir::VoidType::get(builder.getContext())
1706 : resultTypes.front());
1708 cir::FuncType fnType = cir::FuncType::get(argTypes, returnType, isVariadic);
1711 state.addAttribute(getFunctionTypeAttrName(state.name),
1712 TypeAttr::get(fnType));
1714 bool hasAlias =
false;
1715 mlir::StringAttr aliaseeNameAttr = getAliaseeAttrName(state.name);
1716 if (parser.parseOptionalKeyword(
"alias").succeeded()) {
1717 if (parser.parseLParen().failed())
1719 mlir::StringAttr aliaseeAttr;
1720 if (parser.parseOptionalSymbolName(aliaseeAttr).failed())
1722 state.addAttribute(aliaseeNameAttr, FlatSymbolRefAttr::get(aliaseeAttr));
1723 if (parser.parseRParen().failed())
1728 auto parseGlobalDtorCtor =
1729 [&](StringRef keyword,
1730 llvm::function_ref<void(std::optional<int> prio)> createAttr)
1731 -> mlir::LogicalResult {
1732 if (mlir::succeeded(parser.parseOptionalKeyword(keyword))) {
1733 std::optional<int> priority;
1734 if (mlir::succeeded(parser.parseOptionalLParen())) {
1735 auto parsedPriority = mlir::FieldParser<int>::parse(parser);
1736 if (mlir::failed(parsedPriority))
1737 return parser.emitError(parser.getCurrentLocation(),
1738 "failed to parse 'priority', of type 'int'");
1739 priority = parsedPriority.value_or(
int());
1741 if (parser.parseRParen())
1744 createAttr(priority);
1749 if (parseGlobalDtorCtor(
"global_ctor", [&](std::optional<int> priority) {
1750 mlir::IntegerAttr globalCtorPriorityAttr =
1751 builder.getI32IntegerAttr(priority.value_or(65535));
1752 state.addAttribute(getGlobalCtorPriorityAttrName(state.name),
1753 globalCtorPriorityAttr);
1757 if (parseGlobalDtorCtor(
"global_dtor", [&](std::optional<int> priority) {
1758 mlir::IntegerAttr globalDtorPriorityAttr =
1759 builder.getI32IntegerAttr(priority.value_or(65535));
1760 state.addAttribute(getGlobalDtorPriorityAttrName(state.name),
1761 globalDtorPriorityAttr);
1766 if (parser.parseOptionalKeyword(
"inline").succeeded()) {
1767 if (parser.parseLParen().failed())
1770 llvm::StringRef inlineKindStr;
1771 const std::array<llvm::StringRef, cir::getMaxEnumValForInlineKind()>
1772 allowedInlineKindStrs{
1773 cir::stringifyInlineKind(cir::InlineKind::NoInline),
1774 cir::stringifyInlineKind(cir::InlineKind::AlwaysInline),
1775 cir::stringifyInlineKind(cir::InlineKind::InlineHint),
1777 if (parser.parseOptionalKeyword(&inlineKindStr, allowedInlineKindStrs)
1779 return parser.emitError(parser.getCurrentLocation(),
1780 "expected 'never', 'always', or 'hint'");
1782 std::optional<InlineKind> inlineKind =
1783 cir::symbolizeInlineKind(inlineKindStr);
1785 return parser.emitError(parser.getCurrentLocation(),
1786 "invalid inline kind");
1788 state.addAttribute(getInlineKindAttrName(state.name),
1789 cir::InlineAttr::get(builder.getContext(), *inlineKind));
1791 if (parser.parseRParen().failed())
1796 auto *body = state.addRegion();
1797 OptionalParseResult parseResult = parser.parseOptionalRegion(
1798 *body, arguments,
false);
1799 if (parseResult.has_value()) {
1801 return parser.emitError(loc,
"function alias shall not have a body");
1802 if (failed(*parseResult))
1806 return parser.emitError(loc,
"expected non-empty function body");
1815bool cir::FuncOp::isDeclaration() {
1818 std::optional<StringRef> aliasee = getAliasee();
1820 return getFunctionBody().empty();
1826mlir::Region *cir::FuncOp::getCallableRegion() {
1832void cir::FuncOp::print(OpAsmPrinter &p) {
1848 if (getLinkage() != GlobalLinkageKind::ExternalLinkage)
1849 p <<
' ' << stringifyGlobalLinkageKind(getLinkage());
1851 mlir::SymbolTable::Visibility vis = getVisibility();
1852 if (vis != mlir::SymbolTable::Visibility::Public)
1855 cir::VisibilityAttr cirVisibilityAttr = getGlobalVisibilityAttr();
1856 if (!cirVisibilityAttr.isDefault()) {
1865 p.printSymbolName(getSymName());
1866 cir::FuncType fnType = getFunctionType();
1867 function_interface_impl::printFunctionSignature(
1868 p, *
this, fnType.getInputs(), fnType.isVarArg(), fnType.getReturnTypes());
1870 if (std::optional<StringRef> aliaseeName = getAliasee()) {
1872 p.printSymbolName(*aliaseeName);
1876 if (
auto globalCtorPriority = getGlobalCtorPriority()) {
1877 p <<
" global_ctor";
1878 if (globalCtorPriority.value() != 65535)
1879 p <<
"(" << globalCtorPriority.value() <<
")";
1882 if (
auto globalDtorPriority = getGlobalDtorPriority()) {
1883 p <<
" global_dtor";
1884 if (globalDtorPriority.value() != 65535)
1885 p <<
"(" << globalDtorPriority.value() <<
")";
1888 if (cir::InlineAttr inlineAttr = getInlineKindAttr()) {
1889 p <<
" inline(" << cir::stringifyInlineKind(inlineAttr.getValue()) <<
")";
1893 Region &body = getOperation()->getRegion(0);
1894 if (!body.empty()) {
1896 p.printRegion(body,
false,
1901mlir::LogicalResult cir::FuncOp::verify() {
1903 llvm::SmallSet<llvm::StringRef, 16> labels;
1904 llvm::SmallSet<llvm::StringRef, 16> gotos;
1906 getOperation()->walk([&](mlir::Operation *op) {
1907 if (
auto lab = dyn_cast<cir::LabelOp>(op)) {
1908 labels.insert(lab.getLabel());
1909 }
else if (
auto goTo = dyn_cast<cir::GotoOp>(op)) {
1910 gotos.insert(goTo.getLabel());
1914 if (!labels.empty() || !gotos.empty()) {
1915 llvm::SmallSet<llvm::StringRef, 16> mismatched =
1916 llvm::set_difference(gotos, labels);
1918 if (!mismatched.empty())
1919 return emitOpError() <<
"goto/label mismatch";
1927LogicalResult cir::BinOp::verify() {
1928 bool noWrap = getNoUnsignedWrap() || getNoSignedWrap();
1929 bool saturated = getSaturated();
1931 if (!isa<cir::IntType>(
getType()) && noWrap)
1933 <<
"only operations on integer values may have nsw/nuw flags";
1935 bool noWrapOps =
getKind() == cir::BinOpKind::Add ||
1936 getKind() == cir::BinOpKind::Sub ||
1937 getKind() == cir::BinOpKind::Mul;
1940 getKind() == cir::BinOpKind::Add ||
getKind() == cir::BinOpKind::Sub;
1942 if (noWrap && !noWrapOps)
1943 return emitError() <<
"The nsw/nuw flags are applicable to opcodes: 'add', "
1945 if (saturated && !saturatedOps)
1946 return emitError() <<
"The saturated flag is applicable to opcodes: 'add' "
1948 if (noWrap && saturated)
1949 return emitError() <<
"The nsw/nuw flags and the saturated flag are "
1950 "mutually exclusive";
1952 return mlir::success();
1964void cir::TernaryOp::getSuccessorRegions(
1965 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1967 if (!point.isParent()) {
1968 regions.push_back(RegionSuccessor(getOperation(), this->getODSResults(0)));
1974 regions.push_back(RegionSuccessor(&getTrueRegion()));
1975 regions.push_back(RegionSuccessor(&getFalseRegion()));
1978void cir::TernaryOp::build(
1979 OpBuilder &builder, OperationState &result,
Value cond,
1980 function_ref<
void(OpBuilder &, Location)> trueBuilder,
1981 function_ref<
void(OpBuilder &, Location)> falseBuilder) {
1982 result.addOperands(cond);
1983 OpBuilder::InsertionGuard guard(builder);
1984 Region *trueRegion = result.addRegion();
1985 builder.createBlock(trueRegion);
1986 trueBuilder(builder, result.location);
1987 Region *falseRegion = result.addRegion();
1988 builder.createBlock(falseRegion);
1989 falseBuilder(builder, result.location);
1994 dyn_cast_or_null<cir::YieldOp>(trueRegion->back().getTerminator());
1996 yield = dyn_cast_or_null<cir::YieldOp>(falseRegion->back().getTerminator());
1998 assert((yield && yield.getNumOperands() <= 1) &&
1999 "expected zero or one result type");
2000 if (yield.getNumOperands() == 1)
2001 result.addTypes(TypeRange{yield.getOperandTypes().front()});
2008OpFoldResult cir::SelectOp::fold(FoldAdaptor adaptor) {
2009 mlir::Attribute condition = adaptor.getCondition();
2011 bool conditionValue = mlir::cast<cir::BoolAttr>(condition).getValue();
2012 return conditionValue ? getTrueValue() : getFalseValue();
2016 mlir::Attribute trueValue = adaptor.getTrueValue();
2017 mlir::Attribute falseValue = adaptor.getFalseValue();
2018 if (trueValue == falseValue)
2020 if (getTrueValue() == getFalseValue())
2021 return getTrueValue();
2029LogicalResult cir::ShiftOp::verify() {
2030 mlir::Operation *op = getOperation();
2031 auto op0VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(0).getType());
2032 auto op1VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(1).getType());
2033 if (!op0VecTy ^ !op1VecTy)
2034 return emitOpError() <<
"input types cannot be one vector and one scalar";
2037 if (op0VecTy.getSize() != op1VecTy.getSize())
2038 return emitOpError() <<
"input vector types must have the same size";
2040 auto opResultTy = mlir::dyn_cast<cir::VectorType>(
getType());
2042 return emitOpError() <<
"the type of the result must be a vector "
2043 <<
"if it is vector shift";
2045 auto op0VecEleTy = mlir::cast<cir::IntType>(op0VecTy.getElementType());
2046 auto op1VecEleTy = mlir::cast<cir::IntType>(op1VecTy.getElementType());
2047 if (op0VecEleTy.getWidth() != op1VecEleTy.getWidth())
2048 return emitOpError()
2049 <<
"vector operands do not have the same elements sizes";
2051 auto resVecEleTy = mlir::cast<cir::IntType>(opResultTy.getElementType());
2052 if (op0VecEleTy.getWidth() != resVecEleTy.getWidth())
2053 return emitOpError() <<
"vector operands and result type do not have the "
2054 "same elements sizes";
2057 return mlir::success();
2064LogicalResult cir::LabelOp::verify() {
2065 mlir::Operation *op = getOperation();
2066 mlir::Block *blk = op->getBlock();
2067 if (&blk->front() != op)
2068 return emitError() <<
"must be the first operation in a block";
2070 return mlir::success();
2077LogicalResult cir::UnaryOp::verify() {
2079 case cir::UnaryOpKind::Inc:
2080 case cir::UnaryOpKind::Dec:
2081 case cir::UnaryOpKind::Plus:
2082 case cir::UnaryOpKind::Minus:
2083 case cir::UnaryOpKind::Not:
2088 llvm_unreachable(
"Unknown UnaryOp kind?");
2092 return isa<cir::BoolType>(op.getInput().getType()) &&
2093 op.getKind() == cir::UnaryOpKind::Not;
2105OpFoldResult cir::UnaryOp::fold(FoldAdaptor adaptor) {
2107 mlir::dyn_cast_if_present<cir::PoisonAttr>(adaptor.getInput())) {
2113 if (
auto previous = getInput().getDefiningOp<cir::UnaryOp>())
2115 return previous.getInput();
2124LogicalResult cir::CopyOp::verify() {
2126 if (!
getType().getPointee().hasTrait<DataLayoutTypeInterface::Trait>())
2127 return emitError() <<
"missing data layout for pointee type";
2129 if (getSrc() == getDst())
2130 return emitError() <<
"source and destination are the same";
2132 return mlir::success();
2139LogicalResult cir::GetMemberOp::verify() {
2140 const auto recordTy = dyn_cast<RecordType>(getAddrTy().getPointee());
2142 return emitError() <<
"expected pointer to a record type";
2144 if (recordTy.getMembers().size() <=
getIndex())
2145 return emitError() <<
"member index out of bounds";
2148 return emitError() <<
"member type mismatch";
2150 return mlir::success();
2157OpFoldResult cir::VecCreateOp::fold(FoldAdaptor adaptor) {
2158 if (llvm::any_of(getElements(), [](mlir::Value value) {
2159 return !value.getDefiningOp<cir::ConstantOp>();
2163 return cir::ConstVectorAttr::get(
2164 getType(), mlir::ArrayAttr::get(getContext(), adaptor.getElements()));
2167LogicalResult cir::VecCreateOp::verify() {
2171 const cir::VectorType vecTy =
getType();
2172 if (getElements().size() != vecTy.getSize()) {
2173 return emitOpError() <<
"operand count of " << getElements().size()
2174 <<
" doesn't match vector type " << vecTy
2175 <<
" element count of " << vecTy.getSize();
2178 const mlir::Type elementType = vecTy.getElementType();
2179 for (
const mlir::Value element : getElements()) {
2180 if (element.getType() != elementType) {
2181 return emitOpError() <<
"operand type " << element.getType()
2182 <<
" doesn't match vector element type "
2194OpFoldResult cir::VecExtractOp::fold(FoldAdaptor adaptor) {
2195 const auto vectorAttr =
2196 llvm::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec());
2200 const auto indexAttr =
2201 llvm::dyn_cast_if_present<cir::IntAttr>(adaptor.getIndex());
2205 const mlir::ArrayAttr elements = vectorAttr.getElts();
2206 const uint64_t index = indexAttr.getUInt();
2207 if (index >= elements.size())
2210 return elements[index];
2217OpFoldResult cir::VecCmpOp::fold(FoldAdaptor adaptor) {
2219 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getLhs());
2221 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getRhs());
2222 if (!lhsVecAttr || !rhsVecAttr)
2225 mlir::Type inputElemTy =
2226 mlir::cast<cir::VectorType>(lhsVecAttr.getType()).getElementType();
2227 if (!isAnyIntegerOrFloatingPointType(inputElemTy))
2230 cir::CmpOpKind opKind = adaptor.getKind();
2231 mlir::ArrayAttr lhsVecElhs = lhsVecAttr.getElts();
2232 mlir::ArrayAttr rhsVecElhs = rhsVecAttr.getElts();
2233 uint64_t vecSize = lhsVecElhs.size();
2236 bool isIntAttr = vecSize && mlir::isa<cir::IntAttr>(lhsVecElhs[0]);
2237 for (uint64_t i = 0; i < vecSize; i++) {
2238 mlir::Attribute lhsAttr = lhsVecElhs[i];
2239 mlir::Attribute rhsAttr = rhsVecElhs[i];
2242 case cir::CmpOpKind::lt: {
2244 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <
2245 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2247 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <
2248 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2252 case cir::CmpOpKind::le: {
2254 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <=
2255 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2257 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <=
2258 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2262 case cir::CmpOpKind::gt: {
2264 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >
2265 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2267 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >
2268 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2272 case cir::CmpOpKind::ge: {
2274 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >=
2275 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2277 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >=
2278 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2282 case cir::CmpOpKind::eq: {
2284 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() ==
2285 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2287 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() ==
2288 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2292 case cir::CmpOpKind::ne: {
2294 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() !=
2295 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2297 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() !=
2298 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2304 elements[i] = cir::IntAttr::get(
getType().getElementType(), cmpResult);
2307 return cir::ConstVectorAttr::get(
2308 getType(), mlir::ArrayAttr::get(getContext(), elements));
2315OpFoldResult cir::VecShuffleOp::fold(FoldAdaptor adaptor) {
2317 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec1());
2319 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec2());
2320 if (!vec1Attr || !vec2Attr)
2323 mlir::Type vec1ElemTy =
2324 mlir::cast<cir::VectorType>(vec1Attr.getType()).getElementType();
2326 mlir::ArrayAttr vec1Elts = vec1Attr.getElts();
2327 mlir::ArrayAttr vec2Elts = vec2Attr.getElts();
2328 mlir::ArrayAttr indicesElts = adaptor.getIndices();
2331 elements.reserve(indicesElts.size());
2333 uint64_t vec1Size = vec1Elts.size();
2334 for (
const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
2335 if (idxAttr.getSInt() == -1) {
2336 elements.push_back(cir::UndefAttr::get(vec1ElemTy));
2340 uint64_t idxValue = idxAttr.getUInt();
2341 elements.push_back(idxValue < vec1Size ? vec1Elts[idxValue]
2342 : vec2Elts[idxValue - vec1Size]);
2345 return cir::ConstVectorAttr::get(
2346 getType(), mlir::ArrayAttr::get(getContext(), elements));
2349LogicalResult cir::VecShuffleOp::verify() {
2352 if (getIndices().size() != getResult().
getType().getSize()) {
2353 return emitOpError() <<
": the number of elements in " << getIndices()
2354 <<
" and " << getResult().getType() <<
" don't match";
2359 if (getVec1().
getType().getElementType() !=
2360 getResult().
getType().getElementType()) {
2361 return emitOpError() <<
": element types of " << getVec1().getType()
2362 <<
" and " << getResult().getType() <<
" don't match";
2365 const uint64_t maxValidIndex =
2366 getVec1().getType().getSize() + getVec2().getType().getSize() - 1;
2368 getIndices().getAsRange<cir::IntAttr>(), [&](cir::IntAttr idxAttr) {
2369 return idxAttr.getSInt() != -1 && idxAttr.getUInt() > maxValidIndex;
2371 return emitOpError() <<
": index for __builtin_shufflevector must be "
2372 "less than the total number of vector elements";
2381OpFoldResult cir::VecShuffleDynamicOp::fold(FoldAdaptor adaptor) {
2382 mlir::Attribute vec = adaptor.getVec();
2383 mlir::Attribute indices = adaptor.getIndices();
2384 if (mlir::isa_and_nonnull<cir::ConstVectorAttr>(vec) &&
2385 mlir::isa_and_nonnull<cir::ConstVectorAttr>(indices)) {
2386 auto vecAttr = mlir::cast<cir::ConstVectorAttr>(vec);
2387 auto indicesAttr = mlir::cast<cir::ConstVectorAttr>(indices);
2389 mlir::ArrayAttr vecElts = vecAttr.getElts();
2390 mlir::ArrayAttr indicesElts = indicesAttr.getElts();
2392 const uint64_t numElements = vecElts.size();
2395 elements.reserve(numElements);
2397 const uint64_t maskBits = llvm::NextPowerOf2(numElements - 1) - 1;
2398 for (
const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
2399 uint64_t idxValue = idxAttr.getUInt();
2400 uint64_t newIdx = idxValue & maskBits;
2401 elements.push_back(vecElts[newIdx]);
2404 return cir::ConstVectorAttr::get(
2405 getType(), mlir::ArrayAttr::get(getContext(), elements));
2411LogicalResult cir::VecShuffleDynamicOp::verify() {
2413 if (getVec().
getType().getSize() !=
2414 mlir::cast<cir::VectorType>(getIndices().
getType()).getSize()) {
2415 return emitOpError() <<
": the number of elements in " << getVec().getType()
2416 <<
" and " << getIndices().getType() <<
" don't match";
2425LogicalResult cir::VecTernaryOp::verify() {
2430 if (getCond().
getType().getSize() != getLhs().
getType().getSize()) {
2431 return emitOpError() <<
": the number of elements in "
2432 << getCond().getType() <<
" and " << getLhs().getType()
2438OpFoldResult cir::VecTernaryOp::fold(FoldAdaptor adaptor) {
2439 mlir::Attribute cond = adaptor.getCond();
2440 mlir::Attribute lhs = adaptor.getLhs();
2441 mlir::Attribute rhs = adaptor.getRhs();
2443 if (!mlir::isa_and_nonnull<cir::ConstVectorAttr>(cond) ||
2444 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(lhs) ||
2445 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(rhs))
2447 auto condVec = mlir::cast<cir::ConstVectorAttr>(cond);
2448 auto lhsVec = mlir::cast<cir::ConstVectorAttr>(lhs);
2449 auto rhsVec = mlir::cast<cir::ConstVectorAttr>(rhs);
2451 mlir::ArrayAttr condElts = condVec.getElts();
2454 elements.reserve(condElts.size());
2456 for (
const auto &[idx, condAttr] :
2457 llvm::enumerate(condElts.getAsRange<cir::IntAttr>())) {
2458 if (condAttr.getSInt()) {
2459 elements.push_back(lhsVec.getElts()[idx]);
2461 elements.push_back(rhsVec.getElts()[idx]);
2465 cir::VectorType vecTy = getLhs().getType();
2466 return cir::ConstVectorAttr::get(
2467 vecTy, mlir::ArrayAttr::get(getContext(), elements));
2474LogicalResult cir::ComplexCreateOp::verify() {
2477 <<
"operand type of cir.complex.create does not match its result type";
2484OpFoldResult cir::ComplexCreateOp::fold(FoldAdaptor adaptor) {
2485 mlir::Attribute real = adaptor.getReal();
2486 mlir::Attribute imag = adaptor.getImag();
2492 auto realAttr = mlir::cast<mlir::TypedAttr>(real);
2493 auto imagAttr = mlir::cast<mlir::TypedAttr>(imag);
2494 return cir::ConstComplexAttr::get(realAttr, imagAttr);
2501LogicalResult cir::ComplexRealOp::verify() {
2502 mlir::Type operandTy = getOperand().getType();
2503 if (
auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
2504 operandTy = complexOperandTy.getElementType();
2507 emitOpError() <<
": result type does not match operand type";
2514OpFoldResult cir::ComplexRealOp::fold(FoldAdaptor adaptor) {
2515 if (!mlir::isa<cir::ComplexType>(getOperand().
getType()))
2518 if (
auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
2519 return complexCreateOp.getOperand(0);
2522 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
2523 return complex ? complex.getReal() :
nullptr;
2530LogicalResult cir::ComplexImagOp::verify() {
2531 mlir::Type operandTy = getOperand().getType();
2532 if (
auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
2533 operandTy = complexOperandTy.getElementType();
2536 emitOpError() <<
": result type does not match operand type";
2543OpFoldResult cir::ComplexImagOp::fold(FoldAdaptor adaptor) {
2544 if (!mlir::isa<cir::ComplexType>(getOperand().
getType()))
2547 if (
auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
2548 return complexCreateOp.getOperand(1);
2551 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
2552 return complex ? complex.getImag() :
nullptr;
2559LogicalResult cir::ComplexRealPtrOp::verify() {
2560 mlir::Type resultPointeeTy =
getType().getPointee();
2561 cir::PointerType operandPtrTy = getOperand().getType();
2562 auto operandPointeeTy =
2563 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
2565 if (resultPointeeTy != operandPointeeTy.getElementType()) {
2566 return emitOpError() <<
": result type does not match operand type";
2576LogicalResult cir::ComplexImagPtrOp::verify() {
2577 mlir::Type resultPointeeTy =
getType().getPointee();
2578 cir::PointerType operandPtrTy = getOperand().getType();
2579 auto operandPointeeTy =
2580 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
2582 if (resultPointeeTy != operandPointeeTy.getElementType()) {
2583 return emitOpError()
2584 <<
"cir.complex.imag_ptr result type does not match operand type";
2595 llvm::function_ref<llvm::APInt(
const llvm::APInt &)> func,
2596 bool poisonZero =
false) {
2597 if (mlir::isa_and_present<cir::PoisonAttr>(inputAttr)) {
2602 auto input = mlir::dyn_cast_if_present<IntAttr>(inputAttr);
2606 llvm::APInt inputValue = input.getValue();
2607 if (poisonZero && inputValue.isZero())
2608 return cir::PoisonAttr::get(input.getType());
2610 llvm::APInt resultValue = func(inputValue);
2611 return IntAttr::get(input.getType(), resultValue);
2614OpFoldResult BitClrsbOp::fold(FoldAdaptor adaptor) {
2615 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
2616 unsigned resultValue =
2617 inputValue.getBitWidth() - inputValue.getSignificantBits();
2618 return llvm::APInt(inputValue.getBitWidth(), resultValue);
2622OpFoldResult BitClzOp::fold(FoldAdaptor adaptor) {
2625 [](
const llvm::APInt &inputValue) {
2626 unsigned resultValue = inputValue.countLeadingZeros();
2627 return llvm::APInt(inputValue.getBitWidth(), resultValue);
2632OpFoldResult BitCtzOp::fold(FoldAdaptor adaptor) {
2635 [](
const llvm::APInt &inputValue) {
2636 return llvm::APInt(inputValue.getBitWidth(),
2637 inputValue.countTrailingZeros());
2642OpFoldResult BitFfsOp::fold(FoldAdaptor adaptor) {
2643 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
2644 unsigned trailingZeros = inputValue.countTrailingZeros();
2646 trailingZeros == inputValue.getBitWidth() ? 0 : trailingZeros + 1;
2647 return llvm::APInt(inputValue.getBitWidth(), result);
2651OpFoldResult BitParityOp::fold(FoldAdaptor adaptor) {
2652 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
2653 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount() % 2);
2657OpFoldResult BitPopcountOp::fold(FoldAdaptor adaptor) {
2658 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
2659 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount());
2663OpFoldResult BitReverseOp::fold(FoldAdaptor adaptor) {
2664 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
2665 return inputValue.reverseBits();
2669OpFoldResult ByteSwapOp::fold(FoldAdaptor adaptor) {
2670 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
2671 return inputValue.byteSwap();
2675OpFoldResult RotateOp::fold(FoldAdaptor adaptor) {
2676 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()) ||
2677 mlir::isa_and_present<cir::PoisonAttr>(adaptor.getAmount())) {
2679 return cir::PoisonAttr::get(
getType());
2682 auto input = mlir::dyn_cast_if_present<IntAttr>(adaptor.getInput());
2683 auto amount = mlir::dyn_cast_if_present<IntAttr>(adaptor.getAmount());
2684 if (!input && !amount)
2693 llvm::APInt inputValue;
2695 inputValue = input.getValue();
2696 if (inputValue.isZero() || inputValue.isAllOnes()) {
2702 uint64_t amountValue;
2704 amountValue = amount.getValue().urem(getInput().
getType().getWidth());
2705 if (amountValue == 0) {
2711 if (!input || !amount)
2714 assert(inputValue.getBitWidth() == getInput().
getType().getWidth() &&
2715 "input value must have the same bit width as the input type");
2717 llvm::APInt resultValue;
2719 resultValue = inputValue.rotl(amountValue);
2721 resultValue = inputValue.rotr(amountValue);
2723 return IntAttr::get(input.getContext(), input.getType(), resultValue);
2730void cir::InlineAsmOp::print(OpAsmPrinter &p) {
2731 p <<
'(' << getAsmFlavor() <<
", ";
2736 auto *nameIt = names.begin();
2737 auto *attrIt = getOperandAttrs().begin();
2739 for (mlir::OperandRange ops : getAsmOperands()) {
2740 p << *nameIt <<
" = ";
2743 llvm::interleaveComma(llvm::make_range(ops.begin(), ops.end()), p,
2745 p.printOperand(value);
2746 p <<
" : " << value.getType();
2748 p <<
" (maybe_memory)";
2757 p.printString(getAsmString());
2759 p.printString(getConstraints());
2763 if (getSideEffects())
2764 p <<
" side_effects";
2766 std::array elidedAttrs{
2767 llvm::StringRef(
"asm_flavor"), llvm::StringRef(
"asm_string"),
2768 llvm::StringRef(
"constraints"), llvm::StringRef(
"operand_attrs"),
2769 llvm::StringRef(
"operands_segments"), llvm::StringRef(
"side_effects")};
2770 p.printOptionalAttrDict(getOperation()->getAttrs(), elidedAttrs);
2772 if (
auto v = getRes())
2773 p <<
" -> " << v.getType();
2776void cir::InlineAsmOp::build(OpBuilder &odsBuilder, OperationState &odsState,
2778 StringRef asmString, StringRef constraints,
2779 bool sideEffects, cir::AsmFlavor asmFlavor,
2783 for (
auto operandRange : asmOperands) {
2784 segments.push_back(operandRange.size());
2785 odsState.addOperands(operandRange);
2788 odsState.addAttribute(
2789 "operands_segments",
2790 DenseI32ArrayAttr::get(odsBuilder.getContext(), segments));
2791 odsState.addAttribute(
"asm_string", odsBuilder.getStringAttr(asmString));
2792 odsState.addAttribute(
"constraints", odsBuilder.getStringAttr(constraints));
2793 odsState.addAttribute(
"asm_flavor",
2794 AsmFlavorAttr::get(odsBuilder.getContext(), asmFlavor));
2797 odsState.addAttribute(
"side_effects", odsBuilder.getUnitAttr());
2799 odsState.addAttribute(
"operand_attrs", odsBuilder.getArrayAttr(operandAttrs));
2802ParseResult cir::InlineAsmOp::parse(OpAsmParser &parser,
2803 OperationState &result) {
2806 std::string asmString, constraints;
2808 MLIRContext *ctxt = parser.getBuilder().getContext();
2810 auto error = [&](
const Twine &msg) -> LogicalResult {
2811 return parser.emitError(parser.getCurrentLocation(), msg);
2814 auto expected = [&](
const std::string &
c) {
2815 return error(
"expected '" +
c +
"'");
2818 if (parser.parseLParen().failed())
2819 return expected(
"(");
2821 auto flavor = FieldParser<AsmFlavor, AsmFlavor>::parse(parser);
2823 return error(
"Unknown AsmFlavor");
2825 if (parser.parseComma().failed())
2826 return expected(
",");
2828 auto parseValue = [&](
Value &v) {
2829 OpAsmParser::UnresolvedOperand op;
2831 if (parser.parseOperand(op) || parser.parseColon())
2832 return error(
"can't parse operand");
2835 if (parser.parseType(typ).failed())
2836 return error(
"can't parse operand type");
2838 if (parser.resolveOperand(op, typ, tmp))
2839 return error(
"can't resolve operand");
2841 return mlir::success();
2844 auto parseOperands = [&](llvm::StringRef
name) {
2845 if (parser.parseKeyword(name).failed())
2846 return error(
"expected " + name +
" operands here");
2847 if (parser.parseEqual().failed())
2848 return expected(
"=");
2849 if (parser.parseLSquare().failed())
2850 return expected(
"[");
2853 if (parser.parseOptionalRSquare().succeeded()) {
2854 operandsGroupSizes.push_back(size);
2855 if (parser.parseComma())
2856 return expected(
",");
2857 return mlir::success();
2860 auto parseOperand = [&]() {
2862 if (parseValue(val).succeeded()) {
2863 result.operands.push_back(val);
2866 if (parser.parseOptionalLParen().failed()) {
2867 operandAttrs.push_back(mlir::Attribute());
2868 return mlir::success();
2871 if (parser.parseKeyword(
"maybe_memory").succeeded()) {
2872 operandAttrs.push_back(mlir::UnitAttr::get(ctxt));
2873 if (parser.parseRParen())
2874 return expected(
")");
2875 return mlir::success();
2877 return expected(
"maybe_memory");
2880 return mlir::failure();
2883 if (parser.parseCommaSeparatedList(parseOperand).failed())
2884 return mlir::failure();
2886 if (parser.parseRSquare().failed() || parser.parseComma().failed())
2887 return expected(
"]");
2888 operandsGroupSizes.push_back(size);
2889 return mlir::success();
2892 if (parseOperands(
"out").failed() || parseOperands(
"in").failed() ||
2893 parseOperands(
"in_out").failed())
2894 return error(
"failed to parse operands");
2896 if (parser.parseLBrace())
2897 return expected(
"{");
2898 if (parser.parseString(&asmString))
2899 return error(
"asm string parsing failed");
2900 if (parser.parseString(&constraints))
2901 return error(
"constraints string parsing failed");
2902 if (parser.parseRBrace())
2903 return expected(
"}");
2904 if (parser.parseRParen())
2905 return expected(
")");
2907 if (parser.parseOptionalKeyword(
"side_effects").succeeded())
2908 result.attributes.set(
"side_effects", UnitAttr::get(ctxt));
2910 if (parser.parseOptionalArrow().succeeded() &&
2911 parser.parseType(resType).failed())
2912 return mlir::failure();
2914 if (parser.parseOptionalAttrDict(result.attributes).failed())
2915 return mlir::failure();
2917 result.attributes.set(
"asm_flavor", AsmFlavorAttr::get(ctxt, *flavor));
2918 result.attributes.set(
"asm_string", StringAttr::get(ctxt, asmString));
2919 result.attributes.set(
"constraints", StringAttr::get(ctxt, constraints));
2920 result.attributes.set(
"operand_attrs", ArrayAttr::get(ctxt, operandAttrs));
2921 result.getOrAddProperties<InlineAsmOp::Properties>().operands_segments =
2922 parser.getBuilder().getDenseI32ArrayAttr(operandsGroupSizes);
2924 result.addTypes(TypeRange{resType});
2926 return mlir::success();
2933mlir::LogicalResult cir::ThrowOp::verify() {
2938 if (getNumOperands() != 0) {
2941 return emitOpError() <<
"'type_info' symbol attribute missing";
2951LogicalResult cir::AtomicFetchOp::verify() {
2952 if (getBinop() != cir::AtomicFetchKind::Add &&
2953 getBinop() != cir::AtomicFetchKind::Sub &&
2954 getBinop() != cir::AtomicFetchKind::Max &&
2955 getBinop() != cir::AtomicFetchKind::Min &&
2956 !mlir::isa<cir::IntType>(getVal().
getType()))
2957 return emitError(
"only atomic add, sub, max, and min operation could "
2958 "operate on floating-point values");
2966LogicalResult cir::TypeInfoAttr::verify(
2967 ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError,
2968 ::mlir::Type type, ::mlir::ArrayAttr typeInfoData) {
2970 if (cir::ConstRecordAttr::verify(emitError, type, typeInfoData).failed())
2980void cir::TryOp::getSuccessorRegions(
2981 mlir::RegionBranchPoint point,
2984 if (!point.isParent()) {
2986 RegionSuccessor(getOperation(), getOperation()->getResults()));
2990 regions.push_back(mlir::RegionSuccessor(&getTryRegion()));
2994 for (mlir::Region &handlerRegion : this->getHandlerRegions())
2995 regions.push_back(mlir::RegionSuccessor(&handlerRegion));
3000 mlir::MutableArrayRef<mlir::Region> handlerRegions,
3001 mlir::ArrayAttr handlerTypes) {
3005 for (
const auto [typeIdx, typeAttr] : llvm::enumerate(handlerTypes)) {
3009 if (mlir::isa<cir::CatchAllAttr>(typeAttr)) {
3010 printer <<
"catch all ";
3011 }
else if (mlir::isa<cir::UnwindAttr>(typeAttr)) {
3012 printer <<
"unwind ";
3014 printer <<
"catch [type ";
3015 printer.printAttribute(typeAttr);
3019 printer.printRegion(handlerRegions[typeIdx],
3026 mlir::OpAsmParser &parser,
3028 mlir::ArrayAttr &handlerTypes) {
3030 auto parseCheckedCatcherRegion = [&]() -> mlir::ParseResult {
3031 handlerRegions.emplace_back(
new mlir::Region);
3033 mlir::Region &currRegion = *handlerRegions.back();
3034 mlir::SMLoc regionLoc = parser.getCurrentLocation();
3035 if (parser.parseRegion(currRegion)) {
3036 handlerRegions.clear();
3040 if (currRegion.empty())
3041 return parser.emitError(regionLoc,
"handler region shall not be empty");
3043 if (!(currRegion.back().mightHaveTerminator() &&
3044 currRegion.back().getTerminator()))
3045 return parser.emitError(
3046 regionLoc,
"blocks are expected to be explicitly terminated");
3051 bool hasCatchAll =
false;
3053 while (parser.parseOptionalKeyword(
"catch").succeeded()) {
3054 bool hasLSquare = parser.parseOptionalLSquare().succeeded();
3056 llvm::StringRef attrStr;
3057 if (parser.parseOptionalKeyword(&attrStr, {
"all",
"type"}).failed())
3058 return parser.emitError(parser.getCurrentLocation(),
3059 "expected 'all' or 'type' keyword");
3061 bool isCatchAll = attrStr ==
"all";
3064 return parser.emitError(parser.getCurrentLocation(),
3065 "can't have more than one catch all");
3069 mlir::Attribute exceptionRTTIAttr;
3070 if (!isCatchAll && parser.parseAttribute(exceptionRTTIAttr).failed())
3071 return parser.emitError(parser.getCurrentLocation(),
3072 "expected valid RTTI info attribute");
3074 catcherAttrs.push_back(isCatchAll
3075 ? cir::CatchAllAttr::get(parser.getContext())
3076 : exceptionRTTIAttr);
3078 if (hasLSquare && isCatchAll)
3079 return parser.emitError(parser.getCurrentLocation(),
3080 "catch all dosen't need RTTI info attribute");
3082 if (hasLSquare && parser.parseRSquare().failed())
3083 return parser.emitError(parser.getCurrentLocation(),
3084 "expected `]` after RTTI info attribute");
3086 if (parseCheckedCatcherRegion().failed())
3087 return mlir::failure();
3090 if (parser.parseOptionalKeyword(
"unwind").succeeded()) {
3092 return parser.emitError(parser.getCurrentLocation(),
3093 "unwind can't be used with catch all");
3095 catcherAttrs.push_back(cir::UnwindAttr::get(parser.getContext()));
3096 if (parseCheckedCatcherRegion().failed())
3097 return mlir::failure();
3100 handlerTypes = parser.getBuilder().getArrayAttr(catcherAttrs);
3101 return mlir::success();
3108#define GET_OP_CLASSES
3109#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 bool isIntOrBoolCast(cir::CastOp op)
static void printConstant(OpAsmPrinter &p, Attribute value)
static mlir::ParseResult parseOmittedTerminatorRegion(mlir::OpAsmParser &parser, mlir::Region ®ion)
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)
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 void printSwitchOp(OpAsmPrinter &p, cir::SwitchOp op, mlir::Region &bodyRegion, mlir::Value condition, mlir::Type condType)
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)
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 void printCallCommon(mlir::Operation *op, mlir::FlatSymbolRefAttr calleeSym, mlir::Value indirectCallee, mlir::OpAsmPrinter &printer, bool isNothrow, cir::SideEffect sideEffect)
static LogicalResult checkConstantTypes(mlir::Operation *op, mlir::Type opType, mlir::Attribute attrType)
static ParseResult parseSwitchOp(OpAsmParser &parser, mlir::Region ®ions, mlir::OpAsmParser::UnresolvedOperand &cond, mlir::Type &condType)
static mlir::ParseResult parseCallCommon(mlir::OpAsmParser &parser, mlir::OperationState &result)
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 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 opGlobalThreadLocal()
static bool opCallCallConv()
static bool opScopeCleanupRegion()
static bool supportIFuncAttr()