clang 24.0.0git
CIRDialect.cpp
Go to the documentation of this file.
1//===- CIRDialect.cpp - MLIR CIR ops implementation -----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the CIR dialect and its operations.
10//
11//===----------------------------------------------------------------------===//
12
14
18
19#include "mlir/IR/Attributes.h"
20#include "mlir/IR/BuiltinTypes.h"
21#include "mlir/IR/DialectImplementation.h"
22#include "mlir/IR/PatternMatch.h"
23#include "mlir/IR/Value.h"
24#include "mlir/Interfaces/ControlFlowInterfaces.h"
25#include "mlir/Interfaces/FunctionImplementation.h"
26#include "mlir/Support/LLVM.h"
27
28#include "clang/CIR/Dialect/IR/CIROpsDialect.cpp.inc"
29#include "clang/CIR/Dialect/IR/CIROpsEnums.cpp.inc"
31#include "llvm/ADT/SetOperations.h"
32#include "llvm/ADT/SmallSet.h"
33#include "llvm/ADT/TypeSwitch.h"
34#include "llvm/Support/LogicalResult.h"
35
36using namespace mlir;
37using namespace cir;
38
39//===----------------------------------------------------------------------===//
40// CIR Dialect
41//===----------------------------------------------------------------------===//
42namespace {
43struct CIROpAsmDialectInterface : public OpAsmDialectInterface {
44 using OpAsmDialectInterface::OpAsmDialectInterface;
45
46 AliasResult getAlias(Type type, raw_ostream &os) const final {
47 if (auto recordType = dyn_cast<cir::RecordType>(type)) {
48 StringAttr nameAttr = recordType.getName();
49 if (!nameAttr)
50 os << "rec_anon_" << recordType.getKindAsStr();
51 else
52 os << "rec_" << nameAttr.getValue();
53 return AliasResult::OverridableAlias;
54 }
55 if (auto intType = dyn_cast<cir::IntType>(type)) {
56 // We only provide alias for standard integer types (i.e. integer types
57 // whose width is a power of 2 and at least 8).
58 unsigned width = intType.getWidth();
59 if (width < 8 || !llvm::isPowerOf2_32(width))
60 return AliasResult::NoAlias;
61 os << intType.getAlias();
62 return AliasResult::OverridableAlias;
63 }
64 if (auto voidType = dyn_cast<cir::VoidType>(type)) {
65 os << voidType.getAlias();
66 return AliasResult::OverridableAlias;
67 }
68
69 return AliasResult::NoAlias;
70 }
71
72 AliasResult getAlias(Attribute attr, raw_ostream &os) const final {
73 if (auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr)) {
74 os << (boolAttr.getValue() ? "true" : "false");
75 return AliasResult::FinalAlias;
76 }
77 if (auto bitfield = mlir::dyn_cast<cir::BitfieldInfoAttr>(attr)) {
78 os << "bfi_" << bitfield.getName().str();
79 return AliasResult::FinalAlias;
80 }
81 if (auto dynCastInfoAttr = mlir::dyn_cast<cir::DynamicCastInfoAttr>(attr)) {
82 os << dynCastInfoAttr.getAlias();
83 return AliasResult::FinalAlias;
84 }
85 if (auto cmpThreeWayInfoAttr =
86 mlir::dyn_cast<cir::CmpThreeWayInfoAttr>(attr)) {
87 os << cmpThreeWayInfoAttr.getAlias();
88 return AliasResult::FinalAlias;
89 }
90 return AliasResult::NoAlias;
91 }
92};
93} // namespace
94
95void cir::CIRDialect::initialize() {
96 registerTypes();
97 registerAttributes();
98 addOperations<
99#define GET_OP_LIST
100#include "clang/CIR/Dialect/IR/CIROps.cpp.inc"
101 >();
102 addInterfaces<CIROpAsmDialectInterface>();
103}
104
105Operation *cir::CIRDialect::materializeConstant(mlir::OpBuilder &builder,
106 mlir::Attribute value,
107 mlir::Type type,
108 mlir::Location loc) {
109 return cir::ConstantOp::create(builder, loc, type,
110 mlir::cast<mlir::TypedAttr>(value));
111}
112
113//===----------------------------------------------------------------------===//
114// Helpers
115//===----------------------------------------------------------------------===//
116
117// Parses one of the keywords provided in the list `keywords` and returns the
118// position of the parsed keyword in the list. If none of the keywords from the
119// list is parsed, returns -1.
120static int parseOptionalKeywordAlternative(AsmParser &parser,
121 ArrayRef<llvm::StringRef> keywords) {
122 for (auto en : llvm::enumerate(keywords)) {
123 if (succeeded(parser.parseOptionalKeyword(en.value())))
124 return en.index();
125 }
126 return -1;
127}
128
129namespace {
130template <typename Ty> struct EnumTraits {};
131
132#define REGISTER_ENUM_TYPE(Ty) \
133 template <> struct EnumTraits<cir::Ty> { \
134 static llvm::StringRef stringify(cir::Ty value) { \
135 return stringify##Ty(value); \
136 } \
137 static unsigned getMaxEnumVal() { return cir::getMaxEnumValFor##Ty(); } \
138 }
139
140REGISTER_ENUM_TYPE(GlobalLinkageKind);
141REGISTER_ENUM_TYPE(VisibilityKind);
142REGISTER_ENUM_TYPE(SideEffect);
143REGISTER_ENUM_TYPE(CallingConv);
144} // namespace
145
146/// Parse an enum from the keyword, or default to the provided default value.
147/// The return type is the enum type by default, unless overriden with the
148/// second template argument.
149template <typename EnumTy, typename RetTy = EnumTy>
150static RetTy parseOptionalCIRKeyword(AsmParser &parser, EnumTy defaultValue) {
152 for (unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
153 names.push_back(EnumTraits<EnumTy>::stringify(static_cast<EnumTy>(i)));
154
155 int index = parseOptionalKeywordAlternative(parser, names);
156 if (index == -1)
157 return static_cast<RetTy>(defaultValue);
158 return static_cast<RetTy>(index);
159}
160
161/// Parse an enum from the keyword, return failure if the keyword is not found.
162template <typename EnumTy, typename RetTy = EnumTy>
163static ParseResult parseCIRKeyword(AsmParser &parser, RetTy &result) {
165 for (unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
166 names.push_back(EnumTraits<EnumTy>::stringify(static_cast<EnumTy>(i)));
167
168 int index = parseOptionalKeywordAlternative(parser, names);
169 if (index == -1)
170 return failure();
171 result = static_cast<RetTy>(index);
172 return success();
173}
174
175// Check if a region's termination omission is valid and, if so, creates and
176// inserts the omitted terminator into the region.
177static LogicalResult ensureRegionTerm(OpAsmParser &parser, Region &region,
178 SMLoc errLoc) {
179 Location eLoc = parser.getEncodedSourceLoc(parser.getCurrentLocation());
180 OpBuilder builder(parser.getBuilder().getContext());
181
182 // Insert empty block in case the region is empty to ensure the terminator
183 // will be inserted
184 if (region.empty())
185 builder.createBlock(&region);
186
187 Block &block = region.back();
188 // Region is properly terminated: nothing to do.
189 if (!block.empty() && block.back().hasTrait<OpTrait::IsTerminator>())
190 return success();
191
192 // Check for invalid terminator omissions.
193 if (!region.hasOneBlock())
194 return parser.emitError(errLoc,
195 "multi-block region must not omit terminator");
196
197 // Terminator was omitted correctly: recreate it.
198 builder.setInsertionPointToEnd(&block);
199 cir::YieldOp::create(builder, eLoc);
200 return success();
201}
202
203// True if the region's terminator should be omitted.
204static bool omitRegionTerm(mlir::Region &r) {
205 const auto singleNonEmptyBlock = r.hasOneBlock() && !r.back().empty();
206 const auto yieldsNothing = [&r]() {
207 auto y = dyn_cast<cir::YieldOp>(r.back().getTerminator());
208 return y && y.getArgs().empty();
209 };
210 return singleNonEmptyBlock && yieldsNothing();
211}
212
213// Verifies that the given operand is produced by an operation of type
214// ExpectedProducerOp.
215template <typename ExpectedProducerOp>
216static LogicalResult verifyProducedBy(Operation *op, Value operand,
217 StringRef operandName) {
218 Operation *producer = operand.getDefiningOp();
219 if (!producer || !isa<ExpectedProducerOp>(producer))
220 return op->emitOpError()
221 << "operand '" << operandName << "' must be produced by '"
222 << ExpectedProducerOp::getOperationName() << "'";
223 return success();
224}
225
226//===----------------------------------------------------------------------===//
227// InlineKindAttr (FIXME: remove once FuncOp uses assembly format)
228//===----------------------------------------------------------------------===//
229
230ParseResult parseInlineKindAttr(OpAsmParser &parser,
231 cir::InlineKindAttr &inlineKindAttr) {
232 // Static list of possible inline kind keywords
233 static constexpr llvm::StringRef keywords[] = {"no_inline", "always_inline",
234 "inline_hint"};
235
236 // Parse the inline kind keyword (optional)
237 llvm::StringRef keyword;
238 if (parser.parseOptionalKeyword(&keyword, keywords).failed()) {
239 // Not an inline kind keyword, leave inlineKindAttr empty
240 return success();
241 }
242
243 // Parse the enum value from the keyword
244 auto inlineKindResult = ::cir::symbolizeEnum<::cir::InlineKind>(keyword);
245 if (!inlineKindResult) {
246 return parser.emitError(parser.getCurrentLocation(), "expected one of [")
247 << llvm::join(llvm::ArrayRef(keywords), ", ")
248 << "] for inlineKind, got: " << keyword;
249 }
250
251 inlineKindAttr =
252 ::cir::InlineKindAttr::get(parser.getContext(), *inlineKindResult);
253 return success();
254}
255
256void printInlineKindAttr(OpAsmPrinter &p, cir::InlineKindAttr inlineKindAttr) {
257 if (inlineKindAttr) {
258 p << " " << stringifyInlineKind(inlineKindAttr.getValue());
259 }
260}
261
262//===----------------------------------------------------------------------===//
263// CIR Custom Parsers/Printers
264//===----------------------------------------------------------------------===//
265
266static mlir::ParseResult parseOmittedTerminatorRegion(mlir::OpAsmParser &parser,
267 mlir::Region &region) {
268 auto regionLoc = parser.getCurrentLocation();
269 if (parser.parseRegion(region))
270 return failure();
271 if (ensureRegionTerm(parser, region, regionLoc).failed())
272 return failure();
273 return success();
274}
275
276static void printOmittedTerminatorRegion(mlir::OpAsmPrinter &printer,
277 cir::ScopeOp &op,
278 mlir::Region &region) {
279 printer.printRegion(region,
280 /*printEntryBlockArgs=*/false,
281 /*printBlockTerminators=*/!omitRegionTerm(region));
282}
283
284mlir::OptionalParseResult
285parseGlobalAddressSpaceValue(mlir::AsmParser &p,
286 mlir::ptr::MemorySpaceAttrInterface &attr);
287
288void printGlobalAddressSpaceValue(mlir::AsmPrinter &printer, cir::GlobalOp op,
289 mlir::ptr::MemorySpaceAttrInterface attr);
290
291//===----------------------------------------------------------------------===//
292// AllocaOp
293//===----------------------------------------------------------------------===//
294
295void cir::AllocaOp::build(mlir::OpBuilder &odsBuilder,
296 mlir::OperationState &odsState, mlir::Type addr,
297 llvm::StringRef name, mlir::IntegerAttr alignment) {
298 odsState.addAttribute(getNameAttrName(odsState.name),
299 odsBuilder.getStringAttr(name));
300 if (alignment) {
301 odsState.addAttribute(getAlignmentAttrName(odsState.name), alignment);
302 }
303 odsState.addTypes(addr);
304}
305
306//===----------------------------------------------------------------------===//
307// ArrayCtor & ArrayDtor
308//===----------------------------------------------------------------------===//
309
310template <typename Op> static LogicalResult verifyArrayCtorDtor(Op op) {
311 auto ptrTy = mlir::cast<cir::PointerType>(op.getAddr().getType());
312 mlir::Type pointeeTy = ptrTy.getPointee();
313
314 mlir::Block &body = op.getBody().front();
315 if (body.getNumArguments() != 1)
316 return op.emitOpError("body must have exactly one block argument");
317
318 auto expectedEltPtrTy =
319 mlir::dyn_cast<cir::PointerType>(body.getArgument(0).getType());
320 if (!expectedEltPtrTy)
321 return op.emitOpError("block argument must be a !cir.ptr type");
322
323 if (op.getNumElements()) {
324 auto recTy = mlir::dyn_cast<cir::RecordType>(pointeeTy);
325 if (!recTy)
326 return op.emitOpError(
327 "when 'num_elements' is present, 'addr' must be a pointer to a "
328 "!cir.struct or !cir.union type");
329
330 if (expectedEltPtrTy != ptrTy)
331 return op.emitOpError("when 'num_elements' is present, 'addr' type must "
332 "match the block argument type");
333 } else {
334 auto arrayTy = mlir::dyn_cast<cir::ArrayType>(pointeeTy);
335 if (!arrayTy)
336 return op.emitOpError(
337 "when 'num_elements' is absent, 'addr' must be a pointer to a "
338 "!cir.array type");
339
340 mlir::Type innerEltTy = arrayTy.getElementType();
341 while (auto nested = mlir::dyn_cast<cir::ArrayType>(innerEltTy))
342 innerEltTy = nested.getElementType();
343
344 auto recTy = mlir::dyn_cast<cir::RecordType>(innerEltTy);
345 if (!recTy)
346 return op.emitOpError("the block argument type must be a pointer to a "
347 "!cir.struct or !cir.union type");
348
349 if (expectedEltPtrTy.getPointee() != innerEltTy)
350 return op.emitOpError(
351 "block argument pointee type must match the innermost array "
352 "element type");
353 }
354
355 return success();
356}
357
358LogicalResult cir::ArrayCtor::verify() {
359 if (failed(verifyArrayCtorDtor(*this)))
360 return failure();
361
362 mlir::Region &partialDtor = getPartialDtor();
363 if (!partialDtor.empty()) {
364 mlir::Block &dtorBlock = partialDtor.front();
365 if (dtorBlock.getNumArguments() != 1)
366 return emitOpError("partial_dtor must have exactly one block argument");
367
368 auto bodyArgTy = getBody().front().getArgument(0).getType();
369 if (dtorBlock.getArgument(0).getType() != bodyArgTy)
370 return emitOpError("partial_dtor block argument type must match "
371 "the body block argument type");
372 }
373 return success();
374}
375LogicalResult cir::ArrayDtor::verify() { return verifyArrayCtorDtor(*this); }
376
377//===----------------------------------------------------------------------===//
378// DeleteArrayOp
379//===----------------------------------------------------------------------===//
380
381LogicalResult cir::DeleteArrayOp::verify() {
382 if (getDtorMayThrow() && !getElementDtorAttr())
383 return emitOpError(
384 "'dtor_may_throw' requires an 'element_dtor' to be present");
385 return success();
386}
387
388//===----------------------------------------------------------------------===//
389// AssumeOp
390//===----------------------------------------------------------------------===//
391
392static void printAssumeBundle(OpAsmPrinter &p, cir::AssumeOp op,
393 cir::AssumeBundleKindAttr kindAttr,
394 OperandRange bundleArgs,
395 TypeRange bundleArgTypes) {
396 cir::AssumeBundleKind kind = kindAttr.getValue();
397 if (kind == cir::AssumeBundleKind::None)
398 return;
399
400 p << " " << cir::stringifyAssumeBundleKind(kind);
401 if (bundleArgs.empty())
402 return;
403
404 p << "(";
405 p.printOperands(bundleArgs);
406 p << " : ";
407 llvm::interleaveComma(bundleArgTypes, p);
408 p << ")";
409}
410
411static ParseResult parseAssumeBundle(
412 OpAsmParser &p, cir::AssumeBundleKindAttr &bundleKindAttr,
414 llvm::SmallVector<mlir::Type, 1> &bundleArgTypes) {
415 StringRef keyword;
416 auto loc = p.getCurrentLocation();
417 if (failed(p.parseOptionalKeyword(&keyword))) {
418 bundleKindAttr = cir::AssumeBundleKindAttr::get(
419 p.getContext(), cir::AssumeBundleKind::None);
420 return success();
421 }
422
423 std::optional<cir::AssumeBundleKind> parsedKind =
424 cir::symbolizeAssumeBundleKind(keyword);
425 if (!parsedKind)
426 return p.emitError(loc, "unknown assume bundle kind '") << keyword << "'";
427
428 bundleKindAttr = cir::AssumeBundleKindAttr::get(p.getContext(), *parsedKind);
429
430 if (p.parseOptionalLParen())
431 return success();
432
433 if (p.parseOperandList(bundleArgs) || p.parseColon() ||
434 p.parseTypeList(bundleArgTypes) || p.parseRParen())
435 return failure();
436
437 return success();
438}
439
440LogicalResult cir::AssumeOp::verify() {
441 cir::AssumeBundleKind kind = getBundleKind();
442 size_t numArgs = getBundleArgs().size();
443
444 if (kind == cir::AssumeBundleKind::None) {
445 if (numArgs != 0)
446 return emitOpError("unexpected bundle operands for kind 'none'");
447 return success();
448 }
449
450 if (numArgs == 0)
451 return emitOpError("expected bundle operands for kind '")
452 << cir::stringifyAssumeBundleKind(kind) << "'";
453
454 switch (kind) {
455 case cir::AssumeBundleKind::Align:
456 if (numArgs != 2 && numArgs != 3)
457 return emitOpError("align bundle expects 2 or 3 operands");
458 break;
459 case cir::AssumeBundleKind::SeparateStorage:
460 if (numArgs != 2)
461 return emitOpError("separate_storage bundle expects 2 operands");
462 break;
463 case cir::AssumeBundleKind::Dereferenceable:
464 if (numArgs != 2)
465 return emitOpError("dereferenceable bundle expects 2 operands");
466 break;
467 default:
468 break;
469 }
470 return success();
471}
472
473//===----------------------------------------------------------------------===//
474// LocalInitOp
475//===----------------------------------------------------------------------===//
476
477LogicalResult
478cir::LocalInitOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
479 cir::GlobalOp global = getReferencedGlobal(symbolTable);
480 if (!global)
481 return emitOpError("'")
482 << getGlobalName() << "' does not reference a valid cir.global";
483
484 if (getTls() && !global.getTlsModel())
485 return emitOpError("access to global not marked thread local");
486
487 if (!global.getStaticLocalGuard().has_value())
488 return emitOpError("static_local attribute mismatch");
489
490 return success();
491}
492
493//===----------------------------------------------------------------------===//
494// ConditionOp
495//===----------------------------------------------------------------------===//
496
497//===----------------------------------
498// BranchOpTerminatorInterface Methods
499//===----------------------------------
500
501void cir::ConditionOp::getSuccessorRegions(
502 ArrayRef<Attribute> operands, SmallVectorImpl<RegionSuccessor> &regions) {
503 // TODO(cir): The condition value may be folded to a constant, narrowing
504 // down its list of possible successors.
505
506 // Parent is a loop: condition may branch to the body, or on the false edge
507 // to the per-iteration cleanup region if present, otherwise to the parent op.
508 if (auto loopOp = dyn_cast<LoopOpInterface>(getOperation()->getParentOp())) {
509 regions.emplace_back(&loopOp.getBody());
510 if (mlir::Region *cleanup = loopOp.maybeGetCleanup())
511 regions.emplace_back(cleanup);
512 else
513 regions.emplace_back(getOperation());
514 return;
515 }
516
517 // Parent is an await: condition may branch to resume or suspend regions.
518 auto await = cast<AwaitOp>(getOperation()->getParentOp());
519 regions.emplace_back(&await.getResume());
520 regions.emplace_back(&await.getSuspend());
521}
522
523MutableOperandRange
524cir::ConditionOp::getMutableSuccessorOperands(RegionSuccessor point) {
525 // No values are yielded to the successor region.
526 return MutableOperandRange(getOperation(), 0, 0);
527}
528
529MutableOperandRange
530cir::ResumeOp::getMutableSuccessorOperands(RegionSuccessor point) {
531 // The eh_token operand is not forwarded to the parent region.
532 return MutableOperandRange(getOperation(), 0, 0);
533}
534
535LogicalResult cir::ConditionOp::verify() {
536 if (!isa<LoopOpInterface, AwaitOp>(getOperation()->getParentOp()))
537 return emitOpError("condition must be within a conditional region");
538 return success();
539}
540
541//===----------------------------------------------------------------------===//
542// WhileOp & ForOp
543//===----------------------------------------------------------------------===//
544
545template <typename LoopOpTy>
546static LogicalResult verifyLoopCleanup(LoopOpTy op) {
547 std::optional<cir::CleanupKind> cleanupKind = op.getCleanupKind();
548
549 // The cleanup kind attribute must be present exactly when a (non-empty)
550 // cleanup region is present.
551 if (cleanupKind.has_value() == op.getCleanup().empty())
552 return op.emitOpError("cleanup kind must be present if and only if the "
553 "cleanup region is non-empty");
554
555 // A loop's per-iteration cleanup runs on every normal exit edge (loop exit,
556 // end of iteration, break/continue), so an EH-only cleanup is meaningless.
557 // Only 'normal' (exceptions disabled) and 'all' (normal + EH unwind) apply.
558 if (cleanupKind == cir::CleanupKind::EH)
559 return op.emitOpError("loop cleanup kind must be 'normal' or 'all', "
560 "not 'eh'");
561
562 return success();
563}
564
565LogicalResult cir::WhileOp::verify() { return verifyLoopCleanup(*this); }
566
567LogicalResult cir::ForOp::verify() { return verifyLoopCleanup(*this); }
568
569//===----------------------------------------------------------------------===//
570// ConstantOp
571//===----------------------------------------------------------------------===//
572
573static LogicalResult checkConstantTypes(mlir::Operation *op, mlir::Type opType,
574 mlir::Attribute attrType) {
575 if (isa<cir::ConstPtrAttr>(attrType)) {
576 if (!mlir::isa<cir::PointerType>(opType))
577 return op->emitOpError(
578 "pointer constant initializing a non-pointer type");
579 return success();
580 }
581
582 if (isa<cir::DataMemberAttr, cir::DataMemberOffsetAttr, cir::MethodAttr>(
583 attrType)) {
584 // More detailed type verifications are already done in
585 // DataMemberAttr::verify or MethodAttr::verify. Don't need to repeat here.
586 return success();
587 }
588
589 if (isa<cir::ZeroAttr>(attrType)) {
590 if (isa<cir::RecordType, cir::ArrayType, cir::VectorType, cir::ComplexType>(
591 opType))
592 return success();
593 return op->emitOpError(
594 "zero expects struct, array, vector, or complex type");
595 }
596
597 if (mlir::isa<cir::UndefAttr>(attrType)) {
598 if (!mlir::isa<cir::VoidType>(opType))
599 return success();
600 return op->emitOpError("undef expects non-void type");
601 }
602
603 if (mlir::isa<cir::BoolAttr>(attrType)) {
604 if (!mlir::isa<cir::BoolType>(opType))
605 return op->emitOpError("result type (")
606 << opType << ") must be '!cir.bool' for '" << attrType << "'";
607 return success();
608 }
609
610 if (mlir::isa<cir::IntAttr, cir::FPAttr>(attrType)) {
611 auto at = cast<TypedAttr>(attrType);
612 if (at.getType() != opType) {
613 return op->emitOpError("result type (")
614 << opType << ") does not match value type (" << at.getType()
615 << ")";
616 }
617 return success();
618 }
619
620 if (mlir::isa<cir::BlockAddrDiffAttr, cir::BlockAddrInfoAttr,
621 cir::ConstArrayAttr, cir::ConstVectorAttr,
622 cir::ConstComplexAttr, cir::ConstRecordAttr,
623 cir::GlobalViewAttr, cir::PoisonAttr, cir::TypeInfoAttr,
624 cir::VTableAttr>(attrType))
625 return success();
626
627 assert(isa<TypedAttr>(attrType) && "What else could we be looking at here?");
628 return op->emitOpError("global with type ")
629 << cast<TypedAttr>(attrType).getType() << " not yet supported";
630}
631
632LogicalResult cir::ConstantOp::verify() {
633 // ODS already generates checks to make sure the result type is valid. We just
634 // need to additionally check that the value's attribute type is consistent
635 // with the result type.
636 return checkConstantTypes(getOperation(), getType(), getValue());
637}
638
639OpFoldResult cir::ConstantOp::fold(FoldAdaptor /*adaptor*/) {
640 return getValue();
641}
642
643//===----------------------------------------------------------------------===//
644// CastOp
645//===----------------------------------------------------------------------===//
646
647static bool isFloatingPointCastKind(cir::CastKind kind) {
648 switch (kind) {
649 case cir::CastKind::floating:
650 case cir::CastKind::int_to_float:
651 case cir::CastKind::float_to_int:
652 case cir::CastKind::float_to_bool:
653 case cir::CastKind::bool_to_float:
654 case cir::CastKind::float_to_complex:
655 case cir::CastKind::float_complex_to_real:
656 case cir::CastKind::float_complex_to_bool:
657 case cir::CastKind::float_complex:
658 case cir::CastKind::float_complex_to_int_complex:
659 case cir::CastKind::int_complex_to_float_complex:
660 return true;
661 default:
662 return false;
663 }
664}
665
666LogicalResult cir::CastOp::verify() {
667 mlir::Type resType = getType();
668 mlir::Type srcType = getSrc().getType();
669 cir::CastKind kind = getKind();
670
671 if (getFenvAttr() && !isFloatingPointCastKind(kind))
672 return emitOpError()
673 << "'fenv' is only valid for floating-point cast kinds";
674
675 // Verify address space casts for pointer types. given that
676 // casts for within a different address space are illegal.
677 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
678 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
679 if (srcPtrTy && resPtrTy && (kind != cir::CastKind::address_space))
680 if (srcPtrTy.getAddrSpace() != resPtrTy.getAddrSpace()) {
681 return emitOpError() << "result type address space does not match the "
682 "address space of the operand";
683 }
684
685 auto srcVTy = mlir::dyn_cast<cir::VectorType>(srcType);
686 auto resVTy = mlir::dyn_cast<cir::VectorType>(resType);
687 if (srcVTy && resVTy) {
688 if ((kind == cir::CastKind::int_to_float ||
689 kind == cir::CastKind::float_to_int) &&
690 srcVTy.getSize() != resVTy.getSize()) {
691 return emitOpError()
692 << "vector float-to-int and int-to-float casts require "
693 "source and destination vectors to have the same number of "
694 "elements";
695 }
696 // Use the element type of the vector to verify the cast kind. (Except for
697 // bitcast, see below.)
698 srcType = srcVTy.getElementType();
699 resType = resVTy.getElementType();
700 }
701
702 switch (kind) {
703 case cir::CastKind::int_to_bool: {
704 if (!mlir::isa<cir::BoolType>(resType))
705 return emitOpError() << "requires !cir.bool type for result";
706 if (!mlir::isa<cir::IntType>(srcType))
707 return emitOpError() << "requires !cir.int type for source";
708 return success();
709 }
710 case cir::CastKind::ptr_to_bool: {
711 if (!mlir::isa<cir::BoolType>(resType))
712 return emitOpError() << "requires !cir.bool type for result";
713 if (!mlir::isa<cir::PointerType>(srcType))
714 return emitOpError() << "requires !cir.ptr type for source";
715 return success();
716 }
717 case cir::CastKind::integral: {
718 if (!mlir::isa<cir::IntType>(resType))
719 return emitOpError() << "requires !cir.int type for result";
720 if (!mlir::isa<cir::IntType>(srcType))
721 return emitOpError() << "requires !cir.int type for source";
722 return success();
723 }
724 case cir::CastKind::array_to_ptrdecay: {
725 const auto arrayPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
726 const auto flatPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
727 if (!arrayPtrTy || !flatPtrTy)
728 return emitOpError() << "requires !cir.ptr type for source and result";
729
730 // TODO(CIR): Make sure the AddrSpace of both types are equals
731 return success();
732 }
733 case cir::CastKind::bitcast: {
734 // Handle the pointer types first.
735 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
736 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
737
738 if (srcPtrTy && resPtrTy) {
739 return success();
740 }
741
742 return success();
743 }
744 case cir::CastKind::floating: {
745 if (!mlir::isa<cir::FPTypeInterface>(srcType) ||
746 !mlir::isa<cir::FPTypeInterface>(resType))
747 return emitOpError() << "requires !cir.float type for source and result";
748 return success();
749 }
750 case cir::CastKind::float_to_int: {
751 if (!mlir::isa<cir::FPTypeInterface>(srcType))
752 return emitOpError() << "requires !cir.float type for source";
753 if (!mlir::dyn_cast<cir::IntType>(resType))
754 return emitOpError() << "requires !cir.int type for result";
755 return success();
756 }
757 case cir::CastKind::int_to_ptr: {
758 if (!mlir::dyn_cast<cir::IntType>(srcType))
759 return emitOpError() << "requires !cir.int type for source";
760 if (!mlir::dyn_cast<cir::PointerType>(resType))
761 return emitOpError() << "requires !cir.ptr type for result";
762 return success();
763 }
764 case cir::CastKind::ptr_to_int: {
765 if (!mlir::dyn_cast<cir::PointerType>(srcType))
766 return emitOpError() << "requires !cir.ptr type for source";
767 if (!mlir::dyn_cast<cir::IntType>(resType))
768 return emitOpError() << "requires !cir.int type for result";
769 return success();
770 }
771 case cir::CastKind::float_to_bool: {
772 if (!mlir::isa<cir::FPTypeInterface>(srcType))
773 return emitOpError() << "requires !cir.float type for source";
774 if (!mlir::isa<cir::BoolType>(resType))
775 return emitOpError() << "requires !cir.bool type for result";
776 return success();
777 }
778 case cir::CastKind::bool_to_int: {
779 if (!mlir::isa<cir::BoolType>(srcType))
780 return emitOpError() << "requires !cir.bool type for source";
781 if (!mlir::isa<cir::IntType>(resType))
782 return emitOpError() << "requires !cir.int type for result";
783 return success();
784 }
785 case cir::CastKind::int_to_float: {
786 if (!mlir::isa<cir::IntType>(srcType))
787 return emitOpError() << "requires !cir.int type for source";
788 if (!mlir::isa<cir::FPTypeInterface>(resType))
789 return emitOpError() << "requires !cir.float type for result";
790 return success();
791 }
792 case cir::CastKind::bool_to_float: {
793 if (!mlir::isa<cir::BoolType>(srcType))
794 return emitOpError() << "requires !cir.bool type for source";
795 if (!mlir::isa<cir::FPTypeInterface>(resType))
796 return emitOpError() << "requires !cir.float type for result";
797 return success();
798 }
799 case cir::CastKind::address_space: {
800 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
801 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
802 if (!srcPtrTy || !resPtrTy)
803 return emitOpError() << "requires !cir.ptr type for source and result";
804 if (srcPtrTy.getPointee() != resPtrTy.getPointee())
805 return emitOpError() << "requires two types differ in addrspace only";
806 return success();
807 }
808 case cir::CastKind::float_to_complex: {
809 if (!mlir::isa<cir::FPTypeInterface>(srcType))
810 return emitOpError() << "requires !cir.float type for source";
811 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
812 if (!resComplexTy)
813 return emitOpError() << "requires !cir.complex type for result";
814 if (srcType != resComplexTy.getElementType())
815 return emitOpError() << "requires source type match result element type";
816 return success();
817 }
818 case cir::CastKind::int_to_complex: {
819 if (!mlir::isa<cir::IntType>(srcType))
820 return emitOpError() << "requires !cir.int type for source";
821 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
822 if (!resComplexTy)
823 return emitOpError() << "requires !cir.complex type for result";
824 if (srcType != resComplexTy.getElementType())
825 return emitOpError() << "requires source type match result element type";
826 return success();
827 }
828 case cir::CastKind::float_complex_to_real: {
829 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
830 if (!srcComplexTy)
831 return emitOpError() << "requires !cir.complex type for source";
832 if (!mlir::isa<cir::FPTypeInterface>(resType))
833 return emitOpError() << "requires !cir.float type for result";
834 if (srcComplexTy.getElementType() != resType)
835 return emitOpError() << "requires source element type match result type";
836 return success();
837 }
838 case cir::CastKind::int_complex_to_real: {
839 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
840 if (!srcComplexTy)
841 return emitOpError() << "requires !cir.complex type for source";
842 if (!mlir::isa<cir::IntType>(resType))
843 return emitOpError() << "requires !cir.int type for result";
844 if (srcComplexTy.getElementType() != resType)
845 return emitOpError() << "requires source element type match result type";
846 return success();
847 }
848 case cir::CastKind::float_complex_to_bool: {
849 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
850 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
851 return emitOpError()
852 << "requires floating point !cir.complex type for source";
853 if (!mlir::isa<cir::BoolType>(resType))
854 return emitOpError() << "requires !cir.bool type for result";
855 return success();
856 }
857 case cir::CastKind::int_complex_to_bool: {
858 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
859 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
860 return emitOpError()
861 << "requires floating point !cir.complex type for source";
862 if (!mlir::isa<cir::BoolType>(resType))
863 return emitOpError() << "requires !cir.bool type for result";
864 return success();
865 }
866 case cir::CastKind::float_complex: {
867 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
868 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
869 return emitOpError()
870 << "requires floating point !cir.complex type for source";
871 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
872 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
873 return emitOpError()
874 << "requires floating point !cir.complex type for result";
875 return success();
876 }
877 case cir::CastKind::float_complex_to_int_complex: {
878 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
879 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
880 return emitOpError()
881 << "requires floating point !cir.complex type for source";
882 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
883 if (!resComplexTy || !resComplexTy.isIntegerComplex())
884 return emitOpError() << "requires integer !cir.complex type for result";
885 return success();
886 }
887 case cir::CastKind::int_complex: {
888 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
889 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
890 return emitOpError() << "requires integer !cir.complex type for source";
891 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
892 if (!resComplexTy || !resComplexTy.isIntegerComplex())
893 return emitOpError() << "requires integer !cir.complex type for result";
894 return success();
895 }
896 case cir::CastKind::int_complex_to_float_complex: {
897 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
898 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
899 return emitOpError() << "requires integer !cir.complex type for source";
900 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
901 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
902 return emitOpError()
903 << "requires floating point !cir.complex type for result";
904 return success();
905 }
906 case cir::CastKind::member_ptr_to_bool: {
907 if (!mlir::isa<cir::DataMemberType, cir::MethodType>(srcType))
908 return emitOpError()
909 << "requires !cir.data_member or !cir.method type for source";
910 if (!mlir::isa<cir::BoolType>(resType))
911 return emitOpError() << "requires !cir.bool type for result";
912 return success();
913 }
914 }
915 llvm_unreachable("Unknown CastOp kind?");
916}
917
918static bool isIntOrBoolCast(cir::CastOp op) {
919 auto kind = op.getKind();
920 return kind == cir::CastKind::bool_to_int ||
921 kind == cir::CastKind::int_to_bool || kind == cir::CastKind::integral;
922}
923
924static bool isCirFunctionPointerType(mlir::Type ty) {
925 const auto ptrTy = mlir::dyn_cast<cir::PointerType>(ty);
926 return ptrTy && mlir::isa<cir::FuncType>(ptrTy.getPointee());
927}
928
929static Value tryFoldCastChain(cir::CastOp op) {
930 cir::CastOp head = op, tail = op;
931
932 while (op) {
933 if (!isIntOrBoolCast(op))
934 break;
935 head = op;
936 op = head.getSrc().getDefiningOp<cir::CastOp>();
937 }
938
939 if (head != tail) {
940 // if bool_to_int -> ... -> int_to_bool: take the bool
941 // as we had it was before all casts
942 if (head.getKind() == cir::CastKind::bool_to_int &&
943 tail.getKind() == cir::CastKind::int_to_bool)
944 return head.getSrc();
945
946 // if int_to_bool -> ... -> int_to_bool: take the result
947 // of the first one, as no other casts (and ext casts as well)
948 // don't change the first result
949 if (head.getKind() == cir::CastKind::int_to_bool &&
950 tail.getKind() == cir::CastKind::int_to_bool)
951 return head.getResult();
952
953 return {};
954 }
955
956 // Bitcast round-trip on function pointers: T0 -> T1 -> T0 (e.g. no-proto
957 // redeclaration vs. actual prototype). Restrict to function pointers so
958 // other pointer bitcast chains are unchanged.
959 if (tail.getKind() == cir::CastKind::bitcast) {
960 auto *inner = tail.getSrc().getDefiningOp();
961 if (inner && isCirFunctionPointerType(tail.getType())) {
962 auto innerCast = mlir::dyn_cast<cir::CastOp>(inner);
963 if (innerCast && innerCast.getKind() == cir::CastKind::bitcast &&
964 innerCast.getSrc().getType() == tail.getType() &&
965 innerCast.getType() == tail.getSrc().getType()) {
966 return innerCast.getSrc();
967 }
968 }
969 }
970
971 return {};
972}
973
974OpFoldResult cir::CastOp::fold(FoldAdaptor adaptor) {
975 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getSrc())) {
976 // Propagate poison value
977 return cir::PoisonAttr::get(getContext(), getType());
978 }
979
980 // Propagate Undef value
981 if (mlir::isa_and_present<cir::UndefAttr>(adaptor.getSrc()))
982 return cir::UndefAttr::get(getType());
983
984 if (getSrc().getType() == getType()) {
985 switch (getKind()) {
986 case cir::CastKind::integral: {
988 auto foldOrder = getSrc().getDefiningOp()->fold(foldResults);
989 if (foldOrder.succeeded() && mlir::isa<mlir::Attribute>(foldResults[0]))
990 return mlir::cast<mlir::Attribute>(foldResults[0]);
991 return {};
992 }
993 case cir::CastKind::bitcast:
994 case cir::CastKind::address_space:
995 case cir::CastKind::float_complex:
996 case cir::CastKind::int_complex: {
997 return getSrc();
998 }
999 default:
1000 return {};
1001 }
1002 }
1003
1004 // Handle cases where a chain of casts cancel out.
1005 Value result = tryFoldCastChain(*this);
1006 if (result)
1007 return result;
1008
1009 // Handle simple constant casts.
1010 if (auto srcConst = getSrc().getDefiningOp<cir::ConstantOp>()) {
1011 switch (getKind()) {
1012 case cir::CastKind::integral: {
1013 mlir::Type srcTy = getSrc().getType();
1014 // Don't try to fold vector casts for now.
1015 assert(mlir::isa<cir::VectorType>(srcTy) ==
1016 mlir::isa<cir::VectorType>(getType()));
1017 if (mlir::isa<cir::VectorType>(srcTy))
1018 break;
1019
1020 auto srcIntTy = mlir::cast<cir::IntType>(srcTy);
1021 auto dstIntTy = mlir::cast<cir::IntType>(getType());
1022 auto constIntAttr = srcConst.getValueAttr<cir::IntAttr>();
1023 if (!constIntAttr)
1024 return {};
1025
1026 APInt srcValue = constIntAttr.getValue();
1027 APInt newVal = srcIntTy.isSigned()
1028 ? srcValue.sextOrTrunc(dstIntTy.getWidth())
1029 : srcValue.zextOrTrunc(dstIntTy.getWidth());
1030 return cir::IntAttr::get(dstIntTy, newVal);
1031 }
1032 default:
1033 break;
1034 }
1035 }
1036 return {};
1037}
1038
1039//===----------------------------------------------------------------------===//
1040// BuiltinIntCastOp
1041//===----------------------------------------------------------------------===//
1042
1043LogicalResult cir::BuiltinIntCastOp::verify() {
1044 mlir::Type srcType = getSrc().getType();
1045 mlir::Type resType = getType();
1046
1047 auto srcCirInt = mlir::dyn_cast<cir::IntType>(srcType);
1048 auto resCirInt = mlir::dyn_cast<cir::IntType>(resType);
1049
1050 // One side must be a CIR integer the other must be a builtin
1051 // integer or index type.
1052 if (static_cast<bool>(srcCirInt) == static_cast<bool>(resCirInt))
1053 return emitOpError()
1054 << "requires exactly one '!cir.int' operand or result; the other "
1055 "must be a builtin integer or 'index' type";
1056
1057 mlir::Type builtinType = srcCirInt ? resType : srcType;
1058 if (!mlir::isa<mlir::IntegerType, mlir::IndexType>(builtinType))
1059 return emitOpError() << "requires a builtin integer or 'index' type on the "
1060 "non-CIR side";
1061
1062 // The cast preserves bit width. 'index' has no fixed width, so only check
1063 // when the builtin side is a fixed-width integer.
1064 if (auto builtinInt = mlir::dyn_cast<mlir::IntegerType>(builtinType)) {
1065 cir::IntType cirInt = srcCirInt ? srcCirInt : resCirInt;
1066 if (cirInt.getWidth() != builtinInt.getWidth())
1067 return emitOpError()
1068 << "requires the CIR and builtin integer types to have the same "
1069 "width; use 'cir.cast' for width conversions";
1070 }
1071
1072 return success();
1073}
1074
1075OpFoldResult cir::BuiltinIntCastOp::fold(FoldAdaptor adaptor) {
1076 // Fold: builtin_int_cast(builtin_int_cast(x)) -> x
1077 // Inner source type must match the cast's result type.
1078 if (auto inner = getSrc().getDefiningOp<cir::BuiltinIntCastOp>())
1079 if (inner.getSrc().getType() == getType())
1080 return inner.getSrc();
1081 return {};
1082}
1083
1084//===----------------------------------------------------------------------===//
1085// CallOp
1086//===----------------------------------------------------------------------===//
1087
1088mlir::OperandRange cir::CallOp::getArgOperands() {
1089 if (isIndirect())
1090 return getArgs().drop_front(1);
1091 return getArgs();
1092}
1093
1094mlir::MutableOperandRange cir::CallOp::getArgOperandsMutable() {
1095 mlir::MutableOperandRange args = getArgsMutable();
1096 if (isIndirect())
1097 return args.slice(1, args.size() - 1);
1098 return args;
1099}
1100
1101mlir::Value cir::CallOp::getIndirectCall() {
1102 assert(isIndirect());
1103 return getOperand(0);
1104}
1105
1106/// Return the operand at index 'i'.
1107Value cir::CallOp::getArgOperand(unsigned i) {
1108 if (isIndirect())
1109 ++i;
1110 return getOperand(i);
1111}
1112
1113/// Return the number of operands.
1114unsigned cir::CallOp::getNumArgOperands() {
1115 if (isIndirect())
1116 return this->getOperation()->getNumOperands() - 1;
1117 return this->getOperation()->getNumOperands();
1118}
1119
1120static mlir::ParseResult
1121parseTryCallDestinations(mlir::OpAsmParser &parser,
1122 mlir::OperationState &result) {
1123 mlir::Block *normalDestSuccessor;
1124 if (parser.parseSuccessor(normalDestSuccessor))
1125 return mlir::failure();
1126
1127 if (parser.parseComma())
1128 return mlir::failure();
1129
1130 mlir::Block *unwindDestSuccessor;
1131 if (parser.parseSuccessor(unwindDestSuccessor))
1132 return mlir::failure();
1133
1134 result.addSuccessors(normalDestSuccessor);
1135 result.addSuccessors(unwindDestSuccessor);
1136 return mlir::success();
1137}
1138
1139static mlir::ParseResult parseCallCommon(mlir::OpAsmParser &parser,
1140 mlir::OperationState &result,
1141 bool hasDestinationBlocks = false) {
1143 llvm::SMLoc opsLoc;
1144 mlir::FlatSymbolRefAttr calleeAttr;
1145
1146 // If we cannot parse a string callee, it means this is an indirect call.
1147 if (!parser
1148 .parseOptionalAttribute(calleeAttr, CIRDialect::getCalleeAttrName(),
1149 result.attributes)
1150 .has_value()) {
1151 OpAsmParser::UnresolvedOperand indirectVal;
1152 // Do not resolve right now, since we need to figure out the type
1153 if (parser.parseOperand(indirectVal).failed())
1154 return failure();
1155 ops.push_back(indirectVal);
1156 }
1157
1158 if (parser.parseLParen())
1159 return mlir::failure();
1160
1161 opsLoc = parser.getCurrentLocation();
1162 if (parser.parseOperandList(ops))
1163 return mlir::failure();
1164 if (parser.parseRParen())
1165 return mlir::failure();
1166
1167 if (hasDestinationBlocks &&
1168 parseTryCallDestinations(parser, result).failed()) {
1169 return ::mlir::failure();
1170 }
1171
1172 if (parser.parseOptionalKeyword("musttail").succeeded())
1173 result.addAttribute(CIRDialect::getMustTailAttrName(),
1174 mlir::UnitAttr::get(parser.getContext()));
1175
1176 if (parser.parseOptionalKeyword("nothrow").succeeded())
1177 result.addAttribute(CIRDialect::getNoThrowAttrName(),
1178 mlir::UnitAttr::get(parser.getContext()));
1179
1180 if (parser.parseOptionalKeyword("side_effect").succeeded()) {
1181 if (parser.parseLParen().failed())
1182 return failure();
1183 cir::SideEffect sideEffect;
1184 if (parseCIRKeyword<cir::SideEffect>(parser, sideEffect).failed())
1185 return failure();
1186 if (parser.parseRParen().failed())
1187 return failure();
1188 auto attr = cir::SideEffectAttr::get(parser.getContext(), sideEffect);
1189 result.addAttribute(CIRDialect::getSideEffectAttrName(), attr);
1190 }
1191
1192 if (parser.parseOptionalAttrDict(result.attributes))
1193 return ::mlir::failure();
1194
1195 if (parser.parseColon())
1196 return ::mlir::failure();
1197
1198 SmallVector<Type> argTypes;
1200 SmallVector<Type> resultTypes;
1201 SmallVector<DictionaryAttr> resultAttrs;
1202 if (call_interface_impl::parseFunctionSignature(parser, argTypes, argAttrs,
1203 resultTypes, resultAttrs))
1204 return mlir::failure();
1205
1206 if (resultTypes.size() > 1 || resultAttrs.size() > 1)
1207 return parser.emitError(
1208 parser.getCurrentLocation(),
1209 "functions with multiple return types are not supported");
1210
1211 result.addTypes(resultTypes);
1212
1213 if (parser.resolveOperands(ops, argTypes, opsLoc, result.operands))
1214 return mlir::failure();
1215
1216 if (!resultAttrs.empty() && resultAttrs[0])
1217 result.addAttribute(
1218 CIRDialect::getResAttrsAttrName(),
1219 mlir::ArrayAttr::get(parser.getContext(), {resultAttrs[0]}));
1220
1221 // ArrayAttr requires a vector of 'Attribute', so we have to do the conversion
1222 // here into a separate collection.
1223 llvm::SmallVector<Attribute> convertedArgAttrs;
1224 bool argAttrsEmpty = true;
1225
1226 llvm::transform(argAttrs, std::back_inserter(convertedArgAttrs),
1227 [&](DictionaryAttr da) -> mlir::Attribute {
1228 if (da)
1229 argAttrsEmpty = false;
1230 return da;
1231 });
1232
1233 if (!argAttrsEmpty) {
1234 llvm::ArrayRef argAttrsRef = convertedArgAttrs;
1235 if (!calleeAttr) {
1236 // Fixup for indirect calls, which get an extra entry in the 'args' for
1237 // the indirect type, which doesn't get attributes.
1238 argAttrsRef = argAttrsRef.drop_front();
1239 }
1240 result.addAttribute(CIRDialect::getArgAttrsAttrName(),
1241 mlir::ArrayAttr::get(parser.getContext(), argAttrsRef));
1242 }
1243
1244 return mlir::success();
1245}
1246
1247static void
1248printCallCommon(mlir::Operation *op, mlir::FlatSymbolRefAttr calleeSym,
1249 mlir::Value indirectCallee, mlir::OpAsmPrinter &printer,
1250 bool isNothrow, cir::SideEffect sideEffect, ArrayAttr argAttrs,
1251 ArrayAttr resAttrs, mlir::Block *normalDest = nullptr,
1252 mlir::Block *unwindDest = nullptr) {
1253 printer << ' ';
1254
1255 auto callLikeOp = mlir::cast<cir::CIRCallOpInterface>(op);
1256 auto ops = callLikeOp.getArgOperands();
1257
1258 if (calleeSym) {
1259 // Direct calls
1260 printer.printAttributeWithoutType(calleeSym);
1261 } else {
1262 // Indirect calls
1263 assert(indirectCallee);
1264 printer << indirectCallee;
1265 }
1266
1267 printer << "(" << ops << ")";
1268
1269 if (normalDest) {
1270 assert(unwindDest && "expected two successors");
1271 auto tryCall = cast<cir::TryCallOp>(op);
1272 printer << ' ' << tryCall.getNormalDest();
1273 printer << ",";
1274 printer << ' ';
1275 printer << tryCall.getUnwindDest();
1276 }
1277
1278 if (op->hasAttr(CIRDialect::getMustTailAttrName()))
1279 printer << " musttail";
1280
1281 if (isNothrow)
1282 printer << " nothrow";
1283
1284 if (sideEffect != cir::SideEffect::All) {
1285 printer << " side_effect(";
1286 printer << stringifySideEffect(sideEffect);
1287 printer << ")";
1288 }
1289
1291 CIRDialect::getCalleeAttrName(),
1292 CIRDialect::getMustTailAttrName(),
1293 CIRDialect::getNoThrowAttrName(),
1294 CIRDialect::getSideEffectAttrName(),
1295 CIRDialect::getOperandSegmentSizesAttrName(),
1296 llvm::StringRef("res_attrs"),
1297 llvm::StringRef("arg_attrs")};
1298 printer.printOptionalAttrDict(op->getAttrs(), elidedAttrs);
1299 printer << " : ";
1300 if (calleeSym || !argAttrs) {
1301 call_interface_impl::printFunctionSignature(
1302 printer, op->getOperands().getTypes(), argAttrs,
1303 /*isVariadic=*/false, op->getResultTypes(), resAttrs);
1304 } else {
1305 // indirect function calls use an 'arg' type for the type of its indirect
1306 // argument. However, we don't store a similar attribute collection. In
1307 // order to make `printFunctionSignature` have the attributes line up, we
1308 // have to make a 'shimmed' copy of the attributes that have a blank set of
1309 // attributes for the indirect argument.
1310 llvm::SmallVector<Attribute> shimmedArgAttrs;
1311 shimmedArgAttrs.push_back(mlir::DictionaryAttr::get(op->getContext(), {}));
1312 shimmedArgAttrs.append(argAttrs.begin(), argAttrs.end());
1313 call_interface_impl::printFunctionSignature(
1314 printer, op->getOperands().getTypes(),
1315 mlir::ArrayAttr::get(op->getContext(), shimmedArgAttrs),
1316 /*isVariadic=*/false, op->getResultTypes(), resAttrs);
1317 }
1318}
1319
1320mlir::ParseResult cir::CallOp::parse(mlir::OpAsmParser &parser,
1321 mlir::OperationState &result) {
1322 return parseCallCommon(parser, result);
1323}
1324
1325void cir::CallOp::print(mlir::OpAsmPrinter &p) {
1326 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() : nullptr;
1327 cir::SideEffect sideEffect = getSideEffect();
1328 printCallCommon(*this, getCalleeAttr(), indirectCallee, p, getNothrow(),
1329 sideEffect, getArgAttrsAttr(), getResAttrsAttr());
1330}
1331
1332static LogicalResult
1333verifyCallCommInSymbolUses(mlir::Operation *op,
1334 SymbolTableCollection &symbolTable) {
1335 auto fnAttr =
1336 op->getAttrOfType<FlatSymbolRefAttr>(CIRDialect::getCalleeAttrName());
1337 if (!fnAttr) {
1338 // This is an indirect call, thus we don't have to check the symbol uses.
1339 return mlir::success();
1340 }
1341
1342 auto fn = symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(op, fnAttr);
1343 if (!fn)
1344 return op->emitOpError() << "'" << fnAttr.getValue()
1345 << "' does not reference a valid function";
1346
1347 auto callIf = dyn_cast<cir::CIRCallOpInterface>(op);
1348 assert(callIf && "expected CIR call interface to be always available");
1349
1350 // Verify that the operand and result types match the callee. Note that
1351 // argument-checking is disabled for functions without a prototype.
1352 auto fnType = fn.getFunctionType();
1353 if (!fn.getNoProto()) {
1354 unsigned numCallOperands = callIf.getNumArgOperands();
1355 unsigned numFnOpOperands = fnType.getNumInputs();
1356
1357 if (!fnType.isVarArg() && numCallOperands != numFnOpOperands)
1358 return op->emitOpError("incorrect number of operands for callee");
1359 if (fnType.isVarArg() && numCallOperands < numFnOpOperands)
1360 return op->emitOpError("too few operands for callee");
1361
1362 for (unsigned i = 0, e = numFnOpOperands; i != e; ++i)
1363 if (callIf.getArgOperand(i).getType() != fnType.getInput(i))
1364 return op->emitOpError("operand type mismatch: expected operand type ")
1365 << fnType.getInput(i) << ", but provided "
1366 << op->getOperand(i).getType() << " for operand number " << i;
1367 }
1368
1370
1371 // Void function must not return any results.
1372 if (fnType.hasVoidReturn() && op->getNumResults() != 0)
1373 return op->emitOpError("callee returns void but call has results");
1374
1375 // Non-void function calls must return exactly one result.
1376 if (!fnType.hasVoidReturn() && op->getNumResults() != 1)
1377 return op->emitOpError("incorrect number of results for callee");
1378
1379 // Parent function and return value types must match.
1380 if (!fnType.hasVoidReturn() &&
1381 op->getResultTypes().front() != fnType.getReturnType()) {
1382 return op->emitOpError("result type mismatch: expected ")
1383 << fnType.getReturnType() << ", but provided "
1384 << op->getResult(0).getType();
1385 }
1386
1387 return mlir::success();
1388}
1389
1390LogicalResult
1391cir::CallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1392 return verifyCallCommInSymbolUses(*this, symbolTable);
1393}
1394
1395//===----------------------------------------------------------------------===//
1396// TryCallOp
1397//===----------------------------------------------------------------------===//
1398
1399mlir::OperandRange cir::TryCallOp::getArgOperands() {
1400 if (isIndirect())
1401 return getArgs().drop_front(1);
1402 return getArgs();
1403}
1404
1405mlir::MutableOperandRange cir::TryCallOp::getArgOperandsMutable() {
1406 mlir::MutableOperandRange args = getArgsMutable();
1407 if (isIndirect())
1408 return args.slice(1, args.size() - 1);
1409 return args;
1410}
1411
1412mlir::Value cir::TryCallOp::getIndirectCall() {
1413 assert(isIndirect());
1414 return getOperand(0);
1415}
1416
1417/// Return the operand at index 'i'.
1418Value cir::TryCallOp::getArgOperand(unsigned i) {
1419 if (isIndirect())
1420 ++i;
1421 return getOperand(i);
1422}
1423
1424/// Return the number of operands.
1425unsigned cir::TryCallOp::getNumArgOperands() {
1426 if (isIndirect())
1427 return this->getOperation()->getNumOperands() - 1;
1428 return this->getOperation()->getNumOperands();
1429}
1430
1431LogicalResult
1432cir::TryCallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1433 return verifyCallCommInSymbolUses(*this, symbolTable);
1434}
1435
1436mlir::ParseResult cir::TryCallOp::parse(mlir::OpAsmParser &parser,
1437 mlir::OperationState &result) {
1438 return parseCallCommon(parser, result, /*hasDestinationBlocks=*/true);
1439}
1440
1441void cir::TryCallOp::print(::mlir::OpAsmPrinter &p) {
1442 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() : nullptr;
1443 cir::SideEffect sideEffect = getSideEffect();
1444 printCallCommon(*this, getCalleeAttr(), indirectCallee, p, getNothrow(),
1445 sideEffect, getArgAttrsAttr(), getResAttrsAttr(),
1446 getNormalDest(), getUnwindDest());
1447}
1448
1449//===----------------------------------------------------------------------===//
1450// ReturnOp
1451//===----------------------------------------------------------------------===//
1452
1453static mlir::LogicalResult checkReturnAndFunction(cir::ReturnOp op,
1454 cir::FuncOp function) {
1455 // ReturnOps currently only have a single optional operand.
1456 if (op.getNumOperands() > 1)
1457 return op.emitOpError() << "expects at most 1 return operand";
1458
1459 // Ensure returned type matches the function signature.
1460 auto expectedTy = function.getFunctionType().getReturnType();
1461 auto actualTy =
1462 (op.getNumOperands() == 0 ? cir::VoidType::get(op.getContext())
1463 : op.getOperand(0).getType());
1464 if (actualTy != expectedTy)
1465 return op.emitOpError() << "returns " << actualTy
1466 << " but enclosing function returns " << expectedTy;
1467
1468 return mlir::success();
1469}
1470
1471mlir::LogicalResult cir::ReturnOp::verify() {
1472 // Returns can be present in multiple different scopes, get the
1473 // wrapping function and start from there.
1474 auto *fnOp = getOperation()->getParentOp();
1475 while (!isa<cir::FuncOp>(fnOp))
1476 fnOp = fnOp->getParentOp();
1477
1478 // Make sure return types match function return type.
1479 if (checkReturnAndFunction(*this, cast<cir::FuncOp>(fnOp)).failed())
1480 return failure();
1481
1482 return success();
1483}
1484
1485//===----------------------------------------------------------------------===//
1486// IfOp
1487//===----------------------------------------------------------------------===//
1488
1489ParseResult cir::IfOp::parse(OpAsmParser &parser, OperationState &result) {
1490 // create the regions for 'then'.
1491 result.regions.reserve(2);
1492 Region *thenRegion = result.addRegion();
1493 Region *elseRegion = result.addRegion();
1494
1495 mlir::Builder &builder = parser.getBuilder();
1496 OpAsmParser::UnresolvedOperand cond;
1497 Type boolType = cir::BoolType::get(builder.getContext());
1498
1499 if (parser.parseOperand(cond) ||
1500 parser.resolveOperand(cond, boolType, result.operands))
1501 return failure();
1502
1503 // Parse 'then' region.
1504 mlir::SMLoc parseThenLoc = parser.getCurrentLocation();
1505 if (parser.parseRegion(*thenRegion, /*arguments=*/{}, /*argTypes=*/{}))
1506 return failure();
1507
1508 if (ensureRegionTerm(parser, *thenRegion, parseThenLoc).failed())
1509 return failure();
1510
1511 // If we find an 'else' keyword, parse the 'else' region.
1512 if (!parser.parseOptionalKeyword("else")) {
1513 mlir::SMLoc parseElseLoc = parser.getCurrentLocation();
1514 if (parser.parseRegion(*elseRegion, /*arguments=*/{}, /*argTypes=*/{}))
1515 return failure();
1516 if (ensureRegionTerm(parser, *elseRegion, parseElseLoc).failed())
1517 return failure();
1518 }
1519
1520 // Parse the optional attribute list.
1521 if (parser.parseOptionalAttrDict(result.attributes))
1522 return failure();
1523 return success();
1524}
1525
1526void cir::IfOp::print(OpAsmPrinter &p) {
1527 p << " " << getCondition() << " ";
1528 mlir::Region &thenRegion = this->getThenRegion();
1529 p.printRegion(thenRegion,
1530 /*printEntryBlockArgs=*/false,
1531 /*printBlockTerminators=*/!omitRegionTerm(thenRegion));
1532
1533 // Print the 'else' regions if it exists and has a block.
1534 mlir::Region &elseRegion = this->getElseRegion();
1535 if (!elseRegion.empty()) {
1536 p << " else ";
1537 p.printRegion(elseRegion,
1538 /*printEntryBlockArgs=*/false,
1539 /*printBlockTerminators=*/!omitRegionTerm(elseRegion));
1540 }
1541
1542 p.printOptionalAttrDict(getOperation()->getAttrs());
1543}
1544
1545/// Default callback for IfOp builders.
1546void cir::buildTerminatedBody(OpBuilder &builder, Location loc) {
1547 // add cir.yield to end of the block
1548 cir::YieldOp::create(builder, loc);
1549}
1550
1551/// Given the region at `index`, or the parent operation if `index` is None,
1552/// return the successor regions. These are the regions that may be selected
1553/// during the flow of control. `operands` is a set of optional attributes that
1554/// correspond to a constant value for each operand, or null if that operand is
1555/// not a constant.
1556void cir::IfOp::getSuccessorRegions(mlir::RegionBranchPoint point,
1557 SmallVectorImpl<RegionSuccessor> &regions) {
1558 // The `then` and the `else` region branch back to the parent operation.
1559 if (!point.isParent()) {
1560 regions.emplace_back(getOperation());
1561 return;
1562 }
1563
1564 // Don't consider the else region if it is empty.
1565 Region *elseRegion = &this->getElseRegion();
1566 if (elseRegion->empty())
1567 elseRegion = nullptr;
1568
1569 // If the condition isn't constant, both regions may be executed.
1570 regions.push_back(RegionSuccessor(&getThenRegion()));
1571 if (elseRegion)
1572 regions.push_back(RegionSuccessor(elseRegion));
1573 else
1574 regions.emplace_back(getOperation());
1575}
1576
1577mlir::ValueRange cir::IfOp::getSuccessorInputs(RegionSuccessor successor) {
1578 return successor.isOperation() ? ValueRange(getOperation()->getResults())
1579 : ValueRange();
1580}
1581
1582void cir::IfOp::build(OpBuilder &builder, OperationState &result, Value cond,
1583 bool withElseRegion, BuilderCallbackRef thenBuilder,
1584 BuilderCallbackRef elseBuilder) {
1585 assert(thenBuilder && "the builder callback for 'then' must be present");
1586 result.addOperands(cond);
1587
1588 OpBuilder::InsertionGuard guard(builder);
1589 Region *thenRegion = result.addRegion();
1590 builder.createBlock(thenRegion);
1591 thenBuilder(builder, result.location);
1592
1593 Region *elseRegion = result.addRegion();
1594 if (!withElseRegion)
1595 return;
1596
1597 builder.createBlock(elseRegion);
1598 elseBuilder(builder, result.location);
1599}
1600
1601//===----------------------------------------------------------------------===//
1602// ScopeOp
1603//===----------------------------------------------------------------------===//
1604
1605/// Given the region at `index`, or the parent operation if `index` is None,
1606/// return the successor regions. These are the regions that may be selected
1607/// during the flow of control. `operands` is a set of optional attributes
1608/// that correspond to a constant value for each operand, or null if that
1609/// operand is not a constant.
1610void cir::ScopeOp::getSuccessorRegions(
1611 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &regions) {
1612 // The only region always branch back to the parent operation.
1613 if (!point.isParent()) {
1614 regions.emplace_back(getOperation());
1615 return;
1616 }
1617
1618 // If the condition isn't constant, both regions may be executed.
1619 regions.push_back(RegionSuccessor(&getScopeRegion()));
1620}
1621
1622mlir::ValueRange cir::ScopeOp::getSuccessorInputs(RegionSuccessor successor) {
1623 return successor.isOperation() ? ValueRange(getOperation()->getResults())
1624 : ValueRange();
1625}
1626
1627void cir::ScopeOp::build(
1628 OpBuilder &builder, OperationState &result,
1629 function_ref<void(OpBuilder &, Type &, Location)> scopeBuilder) {
1630 assert(scopeBuilder && "the builder callback for 'then' must be present");
1631
1632 OpBuilder::InsertionGuard guard(builder);
1633 Region *scopeRegion = result.addRegion();
1634 builder.createBlock(scopeRegion);
1636
1637 mlir::Type yieldTy;
1638 scopeBuilder(builder, yieldTy, result.location);
1639
1640 if (yieldTy)
1641 result.addTypes(TypeRange{yieldTy});
1642}
1643
1644void cir::ScopeOp::build(
1645 OpBuilder &builder, OperationState &result,
1646 function_ref<void(OpBuilder &, Location)> scopeBuilder) {
1647 assert(scopeBuilder && "the builder callback for 'then' must be present");
1648 OpBuilder::InsertionGuard guard(builder);
1649 Region *scopeRegion = result.addRegion();
1650 builder.createBlock(scopeRegion);
1652 scopeBuilder(builder, result.location);
1653}
1654
1655LogicalResult cir::ScopeOp::verify() {
1656 if (getRegion().empty()) {
1657 return emitOpError() << "cir.scope must not be empty since it should "
1658 "include at least an implicit cir.yield ";
1659 }
1660
1661 mlir::Block &lastBlock = getRegion().back();
1662 if (lastBlock.empty() || !lastBlock.mightHaveTerminator() ||
1663 !lastBlock.getTerminator()->hasTrait<OpTrait::IsTerminator>())
1664 return emitOpError() << "last block of cir.scope must be terminated";
1665 return success();
1666}
1667
1668LogicalResult cir::ScopeOp::fold(FoldAdaptor /*adaptor*/,
1669 SmallVectorImpl<OpFoldResult> &results) {
1670 // Only fold "trivial" scopes: a single block containing only a `cir.yield`.
1671 if (!getRegion().hasOneBlock())
1672 return failure();
1673 Block &block = getRegion().front();
1674 if (block.getOperations().size() != 1)
1675 return failure();
1676
1677 auto yield = dyn_cast<cir::YieldOp>(block.front());
1678 if (!yield)
1679 return failure();
1680
1681 // Only fold when the scope produces a value.
1682 if (getNumResults() != 1 || yield.getNumOperands() != 1)
1683 return failure();
1684
1685 results.push_back(yield.getOperand(0));
1686 return success();
1687}
1688
1689//===----------------------------------------------------------------------===//
1690// CleanupScopeOp
1691//===----------------------------------------------------------------------===//
1692
1693void cir::CleanupScopeOp::getSuccessorRegions(
1694 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &regions) {
1695 if (!point.isParent()) {
1696 regions.emplace_back(getOperation());
1697 return;
1698 }
1699
1700 // Execution always proceeds from the body region to the cleanup region.
1701 regions.push_back(RegionSuccessor(&getBodyRegion()));
1702 regions.push_back(RegionSuccessor(&getCleanupRegion()));
1703}
1704
1705mlir::ValueRange
1706cir::CleanupScopeOp::getSuccessorInputs(RegionSuccessor successor) {
1707 return ValueRange();
1708}
1709
1710LogicalResult cir::CleanupScopeOp::canonicalize(CleanupScopeOp op,
1711 PatternRewriter &rewriter) {
1712 auto isRegionTrivial = [](Region &region) {
1713 assert(!region.empty() && "CleanupScopeOp regions must not be empty");
1714 if (!region.hasOneBlock())
1715 return false;
1716 Block &block = llvm::getSingleElement(region);
1717 return llvm::hasSingleElement(block) &&
1718 isa<cir::YieldOp>(llvm::getSingleElement(block));
1719 };
1720
1721 Region &body = op.getBodyRegion();
1722 Region &cleanup = op.getCleanupRegion();
1723
1724 // An EH-only cleanup scope with an empty body can never trigger its cleanup
1725 // region — there are no operations in the body that could throw. Erase it.
1726 if (op.getCleanupKind() == CleanupKind::EH && isRegionTrivial(body)) {
1727 rewriter.eraseOp(op);
1728 return success();
1729 }
1730
1731 // A cleanup scope with a trivial cleanup region has no cleanup to perform.
1732 // Inline the body into the parent block and erase the scope.
1733 if (!isRegionTrivial(cleanup) || !body.hasOneBlock())
1734 return failure();
1735
1736 Block &bodyBlock = body.front();
1737 if (!isa<cir::YieldOp>(bodyBlock.getTerminator()))
1738 return failure();
1739
1740 Operation *yield = bodyBlock.getTerminator();
1741 rewriter.inlineBlockBefore(&bodyBlock, op);
1742 rewriter.eraseOp(yield);
1743 rewriter.eraseOp(op);
1744 return success();
1745}
1746
1747void cir::CleanupScopeOp::build(
1748 OpBuilder &builder, OperationState &result, CleanupKind cleanupKind,
1749 function_ref<void(OpBuilder &, Location)> bodyBuilder,
1750 function_ref<void(OpBuilder &, Location)> cleanupBuilder) {
1751 result.addAttribute(getCleanupKindAttrName(result.name),
1752 CleanupKindAttr::get(builder.getContext(), cleanupKind));
1753
1754 OpBuilder::InsertionGuard guard(builder);
1755
1756 // Build body region.
1757 Region *bodyRegion = result.addRegion();
1758 builder.createBlock(bodyRegion);
1759 if (bodyBuilder)
1760 bodyBuilder(builder, result.location);
1761
1762 // Build cleanup region.
1763 Region *cleanupRegion = result.addRegion();
1764 builder.createBlock(cleanupRegion);
1765 if (cleanupBuilder)
1766 cleanupBuilder(builder, result.location);
1767}
1768
1769//===----------------------------------------------------------------------===//
1770// BrOp
1771//===----------------------------------------------------------------------===//
1772
1773/// Merges blocks connected by a unique unconditional branch.
1774///
1775/// ^bb0: ^bb0:
1776/// ... ...
1777/// cir.br ^bb1 => ...
1778/// ^bb1: cir.return
1779/// ...
1780/// cir.return
1781LogicalResult cir::BrOp::canonicalize(BrOp op, PatternRewriter &rewriter) {
1782 Block *src = op->getBlock();
1783 Block *dst = op.getDest();
1784
1785 // Do not fold self-loops.
1786 if (src == dst)
1787 return failure();
1788
1789 // Only merge when this is the unique edge between the blocks.
1790 if (src->getNumSuccessors() != 1 || dst->getSinglePredecessor() != src)
1791 return failure();
1792
1793 // Don't merge blocks that start with LabelOp or IndirectBrOp.
1794 // This is to avoid merging blocks that have an indirect predecessor.
1795 if (isa<cir::LabelOp, cir::IndirectBrOp>(dst->front()))
1796 return failure();
1797
1798 auto operands = op.getDestOperands();
1799 rewriter.eraseOp(op);
1800 rewriter.mergeBlocks(dst, src, operands);
1801 return success();
1802}
1803
1804mlir::SuccessorOperands cir::BrOp::getSuccessorOperands(unsigned index) {
1805 assert(index == 0 && "invalid successor index");
1806 return mlir::SuccessorOperands(getDestOperandsMutable());
1807}
1808
1809Block *cir::BrOp::getSuccessorForOperands(ArrayRef<Attribute>) {
1810 return getDest();
1811}
1812
1813//===----------------------------------------------------------------------===//
1814// IndirectBrCondOp
1815//===----------------------------------------------------------------------===//
1816
1817mlir::SuccessorOperands
1818cir::IndirectBrOp::getSuccessorOperands(unsigned index) {
1819 assert(index < getNumSuccessors() && "invalid successor index");
1820 return mlir::SuccessorOperands(getSuccOperandsMutable()[index]);
1821}
1822
1824 OpAsmParser &parser, Type &flagType,
1825 SmallVectorImpl<Block *> &succOperandBlocks,
1826 SmallVectorImpl<SmallVector<OpAsmParser::UnresolvedOperand>> &succOperands,
1827 SmallVectorImpl<SmallVector<Type>> &succOperandsTypes) {
1828 if (failed(parser.parseCommaSeparatedList(
1829 OpAsmParser::Delimiter::Square,
1830 [&]() {
1831 Block *destination = nullptr;
1832 SmallVector<OpAsmParser::UnresolvedOperand> operands;
1833 SmallVector<Type> operandTypes;
1834
1835 if (parser.parseSuccessor(destination).failed())
1836 return failure();
1837
1838 if (succeeded(parser.parseOptionalLParen())) {
1839 if (failed(parser.parseOperandList(
1840 operands, OpAsmParser::Delimiter::None)) ||
1841 failed(parser.parseColonTypeList(operandTypes)) ||
1842 failed(parser.parseRParen()))
1843 return failure();
1844 }
1845 succOperandBlocks.push_back(destination);
1846 succOperands.emplace_back(operands);
1847 succOperandsTypes.emplace_back(operandTypes);
1848 return success();
1849 },
1850 "successor blocks")))
1851 return failure();
1852 return success();
1853}
1854
1855void printIndirectBrOpSucessors(OpAsmPrinter &p, cir::IndirectBrOp op,
1856 Type flagType, SuccessorRange succs,
1857 OperandRangeRange succOperands,
1858 const TypeRangeRange &succOperandsTypes) {
1859 p << "[";
1860 llvm::interleave(
1861 llvm::zip(succs, succOperands),
1862 [&](auto i) {
1863 p.printNewline();
1864 p.printSuccessorAndUseList(std::get<0>(i), std::get<1>(i));
1865 },
1866 [&] { p << ','; });
1867 if (!succOperands.empty())
1868 p.printNewline();
1869 p << "]";
1870}
1871
1872//===----------------------------------------------------------------------===//
1873// BrCondOp
1874//===----------------------------------------------------------------------===//
1875
1876mlir::SuccessorOperands cir::BrCondOp::getSuccessorOperands(unsigned index) {
1877 assert(index < getNumSuccessors() && "invalid successor index");
1878 return SuccessorOperands(index == 0 ? getDestOperandsTrueMutable()
1879 : getDestOperandsFalseMutable());
1880}
1881
1882Block *cir::BrCondOp::getSuccessorForOperands(ArrayRef<Attribute> operands) {
1883 if (IntegerAttr condAttr = dyn_cast_if_present<IntegerAttr>(operands.front()))
1884 return condAttr.getValue().isOne() ? getDestTrue() : getDestFalse();
1885 return nullptr;
1886}
1887
1888//===----------------------------------------------------------------------===//
1889// CaseOp
1890//===----------------------------------------------------------------------===//
1891
1892void cir::CaseOp::getSuccessorRegions(
1893 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &regions) {
1894 if (!point.isParent()) {
1895 regions.emplace_back(getOperation());
1896 return;
1897 }
1898 regions.push_back(RegionSuccessor(&getCaseRegion()));
1899}
1900
1901mlir::ValueRange cir::CaseOp::getSuccessorInputs(RegionSuccessor successor) {
1902 return successor.isOperation() ? ValueRange(getOperation()->getResults())
1903 : ValueRange();
1904}
1905
1906void cir::CaseOp::build(OpBuilder &builder, OperationState &result,
1907 ArrayAttr value, CaseOpKind kind,
1908 OpBuilder::InsertPoint &insertPoint) {
1909 OpBuilder::InsertionGuard guardSwitch(builder);
1910 result.addAttribute("value", value);
1911 result.getOrAddProperties<Properties>().kind =
1912 cir::CaseOpKindAttr::get(builder.getContext(), kind);
1913 Region *caseRegion = result.addRegion();
1914 builder.createBlock(caseRegion);
1915
1916 insertPoint = builder.saveInsertionPoint();
1917}
1918
1919//===----------------------------------------------------------------------===//
1920// SwitchOp
1921//===----------------------------------------------------------------------===//
1922
1923void cir::SwitchOp::getSuccessorRegions(
1924 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &region) {
1925 if (!point.isParent()) {
1926 region.emplace_back(getOperation());
1927 return;
1928 }
1929
1930 region.push_back(RegionSuccessor(&getBody()));
1931}
1932
1933mlir::ValueRange cir::SwitchOp::getSuccessorInputs(RegionSuccessor successor) {
1934 return successor.isOperation() ? ValueRange(getOperation()->getResults())
1935 : ValueRange();
1936}
1937
1938void cir::SwitchOp::build(OpBuilder &builder, OperationState &result,
1939 Value cond, BuilderOpStateCallbackRef switchBuilder) {
1940 assert(switchBuilder && "the builder callback for regions must be present");
1941 OpBuilder::InsertionGuard guardSwitch(builder);
1942 Region *switchRegion = result.addRegion();
1943 builder.createBlock(switchRegion);
1944 result.addOperands({cond});
1945 switchBuilder(builder, result.location, result);
1946}
1947
1948void cir::SwitchOp::collectCases(llvm::SmallVectorImpl<CaseOp> &cases) {
1949 walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
1950 // Don't walk in nested switch op.
1951 if (isa<cir::SwitchOp>(op) && op != *this)
1952 return WalkResult::skip();
1953
1954 if (auto caseOp = dyn_cast<cir::CaseOp>(op))
1955 cases.push_back(caseOp);
1956
1957 return WalkResult::advance();
1958 });
1959}
1960
1961bool cir::SwitchOp::isSimpleForm(llvm::SmallVectorImpl<CaseOp> &cases) {
1962 collectCases(cases);
1963
1964 if (getBody().empty())
1965 return false;
1966
1967 if (!isa<YieldOp>(getBody().front().back()))
1968 return false;
1969
1970 if (!llvm::all_of(getBody().front(),
1971 [](Operation &op) { return isa<CaseOp, YieldOp>(op); }))
1972 return false;
1973
1974 return llvm::all_of(cases, [this](CaseOp op) {
1975 return op->getParentOfType<SwitchOp>() == *this;
1976 });
1977}
1978
1979//===----------------------------------------------------------------------===//
1980// SwitchFlatOp
1981//===----------------------------------------------------------------------===//
1982
1983void cir::SwitchFlatOp::build(OpBuilder &builder, OperationState &result,
1984 Value value, Block *defaultDestination,
1985 ValueRange defaultOperands,
1986 ArrayRef<APInt> caseValues,
1987 BlockRange caseDestinations,
1988 ArrayRef<ValueRange> caseOperands) {
1989
1990 std::vector<mlir::Attribute> caseValuesAttrs;
1991 for (const APInt &val : caseValues)
1992 caseValuesAttrs.push_back(cir::IntAttr::get(value.getType(), val));
1993 mlir::ArrayAttr attrs = ArrayAttr::get(builder.getContext(), caseValuesAttrs);
1994
1995 build(builder, result, value, defaultOperands, caseOperands, attrs,
1996 defaultDestination, caseDestinations);
1997}
1998
1999/// <cases> ::= `[` (case (`,` case )* )? `]`
2000/// <case> ::= integer `:` bb-id (`(` ssa-use-and-type-list `)`)?
2001static ParseResult parseSwitchFlatOpCases(
2002 OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues,
2003 SmallVectorImpl<Block *> &caseDestinations,
2005 &caseOperands,
2006 SmallVectorImpl<llvm::SmallVector<Type>> &caseOperandTypes) {
2007 if (failed(parser.parseLSquare()))
2008 return failure();
2009 if (succeeded(parser.parseOptionalRSquare()))
2010 return success();
2012
2013 auto parseCase = [&]() {
2014 int64_t value = 0;
2015 if (failed(parser.parseInteger(value)))
2016 return failure();
2017
2018 values.push_back(cir::IntAttr::get(flagType, value));
2019
2020 Block *destination;
2022 llvm::SmallVector<Type> operandTypes;
2023 if (parser.parseColon() || parser.parseSuccessor(destination))
2024 return failure();
2025 if (!parser.parseOptionalLParen()) {
2026 if (parser.parseOperandList(operands, OpAsmParser::Delimiter::None,
2027 /*allowResultNumber=*/false) ||
2028 parser.parseColonTypeList(operandTypes) || parser.parseRParen())
2029 return failure();
2030 }
2031 caseDestinations.push_back(destination);
2032 caseOperands.emplace_back(operands);
2033 caseOperandTypes.emplace_back(operandTypes);
2034 return success();
2035 };
2036 if (failed(parser.parseCommaSeparatedList(parseCase)))
2037 return failure();
2038
2039 caseValues = ArrayAttr::get(flagType.getContext(), values);
2040
2041 return parser.parseRSquare();
2042}
2043
2044static void printSwitchFlatOpCases(OpAsmPrinter &p, cir::SwitchFlatOp op,
2045 Type flagType, mlir::ArrayAttr caseValues,
2046 SuccessorRange caseDestinations,
2047 OperandRangeRange caseOperands,
2048 const TypeRangeRange &caseOperandTypes) {
2049 p << '[';
2050 p.printNewline();
2051 if (!caseValues) {
2052 p << ']';
2053 return;
2054 }
2055
2056 size_t index = 0;
2057 llvm::interleave(
2058 llvm::zip(caseValues, caseDestinations),
2059 [&](auto i) {
2060 p << " ";
2061 mlir::Attribute a = std::get<0>(i);
2062 p << mlir::cast<cir::IntAttr>(a).getValue();
2063 p << ": ";
2064 p.printSuccessorAndUseList(std::get<1>(i), caseOperands[index++]);
2065 },
2066 [&] {
2067 p << ',';
2068 p.printNewline();
2069 });
2070 p.printNewline();
2071 p << ']';
2072}
2073
2074//===----------------------------------------------------------------------===//
2075// GlobalOp
2076//===----------------------------------------------------------------------===//
2077
2078static ParseResult parseConstantValue(OpAsmParser &parser,
2079 mlir::Attribute &valueAttr) {
2080 NamedAttrList attr;
2081 return parser.parseAttribute(valueAttr, "value", attr);
2082}
2083
2084static void printConstant(OpAsmPrinter &p, Attribute value) {
2085 p.printAttribute(value);
2086}
2087
2088mlir::LogicalResult cir::GlobalOp::verify() {
2089 // A function is not an object, so it cannot be the type of a global. A
2090 // global that holds a function's address carries a pointer type instead.
2091 if (mlir::isa<cir::FuncType>(getSymType()))
2092 return emitOpError("global type cannot be a function type");
2093
2094 // Verify that the initial value, if present, is either a unit attribute or
2095 // an attribute CIR supports.
2096 if (getInitialValue().has_value()) {
2097 if (checkConstantTypes(getOperation(), getSymType(), *getInitialValue())
2098 .failed())
2099 return failure();
2100 }
2101
2102 if ((getStaticLocalGuard().has_value()) &&
2103 (!getCtorRegion().empty() || !getDtorRegion().empty()))
2104 return emitOpError(
2105 "Cannot have a static-local global-op with a constructor or "
2106 "destructor, they require in-function initialization via LocalInitOp");
2107
2108 if (getTlsRefs()) {
2109 if (getStaticLocalGuard().has_value())
2110 return emitOpError("cannot have both static local and tls references");
2111 if (!getTlsModel())
2112 return emitOpError("'tls_refs' only valid for tls");
2113 }
2114
2115 if (getAliasee().has_value()) {
2116 if (getInitialValue().has_value() || !getCtorRegion().empty() ||
2117 !getDtorRegion().empty())
2118 return emitOpError("global alias shall not have an initializer or "
2119 "constructor/destructor regions");
2120 }
2121
2122 // TODO(CIR): Many other checks for properties that haven't been upstreamed
2123 // yet.
2124
2125 return success();
2126}
2127
2128void cir::GlobalOp::build(
2129 OpBuilder &odsBuilder, OperationState &odsState, llvm::StringRef sym_name,
2130 mlir::Type sym_type, bool isConstant,
2131 mlir::ptr::MemorySpaceAttrInterface addrSpace,
2132 cir::GlobalLinkageKind linkage,
2133 function_ref<void(OpBuilder &, Location)> ctorBuilder,
2134 function_ref<void(OpBuilder &, Location)> dtorBuilder) {
2135 odsState.addAttribute(getSymNameAttrName(odsState.name),
2136 odsBuilder.getStringAttr(sym_name));
2137 odsState.addAttribute(getSymTypeAttrName(odsState.name),
2138 mlir::TypeAttr::get(sym_type));
2139 auto &properties = odsState.getOrAddProperties<cir::GlobalOp::Properties>();
2140 properties.setConstant(isConstant);
2141
2142 addrSpace = normalizeDefaultAddressSpace(addrSpace);
2143 if (addrSpace)
2144 odsState.addAttribute(getAddrSpaceAttrName(odsState.name), addrSpace);
2145
2146 cir::GlobalLinkageKindAttr linkageAttr =
2147 cir::GlobalLinkageKindAttr::get(odsBuilder.getContext(), linkage);
2148 odsState.addAttribute(getLinkageAttrName(odsState.name), linkageAttr);
2149
2150 Region *ctorRegion = odsState.addRegion();
2151 if (ctorBuilder) {
2152 odsBuilder.createBlock(ctorRegion);
2153 ctorBuilder(odsBuilder, odsState.location);
2154 }
2155
2156 Region *dtorRegion = odsState.addRegion();
2157 if (dtorBuilder) {
2158 odsBuilder.createBlock(dtorRegion);
2159 dtorBuilder(odsBuilder, odsState.location);
2160 }
2161}
2162
2163/// Given the region at `index`, or the parent operation if `index` is None,
2164/// return the successor regions. These are the regions that may be selected
2165/// during the flow of control. `operands` is a set of optional attributes that
2166/// correspond to a constant value for each operand, or null if that operand is
2167/// not a constant.
2168void cir::GlobalOp::getSuccessorRegions(
2169 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &regions) {
2170 // The `ctor` and `dtor` regions always branch back to the parent operation.
2171 if (!point.isParent()) {
2172 regions.emplace_back(getOperation());
2173 return;
2174 }
2175
2176 // Don't consider the ctor region if it is empty.
2177 Region *ctorRegion = &this->getCtorRegion();
2178 if (ctorRegion->empty())
2179 ctorRegion = nullptr;
2180
2181 // Don't consider the dtor region if it is empty.
2182 Region *dtorRegion = &this->getDtorRegion();
2183 if (dtorRegion->empty())
2184 dtorRegion = nullptr;
2185
2186 // If the condition isn't constant, both regions may be executed.
2187 if (ctorRegion)
2188 regions.push_back(RegionSuccessor(ctorRegion));
2189 if (dtorRegion)
2190 regions.push_back(RegionSuccessor(dtorRegion));
2191}
2192
2193mlir::ValueRange cir::GlobalOp::getSuccessorInputs(RegionSuccessor successor) {
2194 return successor.isOperation() ? ValueRange(getOperation()->getResults())
2195 : ValueRange();
2196}
2197
2198static void printGlobalOpTypeAndInitialValue(OpAsmPrinter &p, cir::GlobalOp op,
2199 TypeAttr type, Attribute initAttr,
2200 mlir::Region &ctorRegion,
2201 mlir::Region &dtorRegion) {
2202 auto printType = [&]() { p << ": " << type; };
2203 // Aliases are definitions but they have no initial value or ctor/dtor; the
2204 // assembly prints them like declarations (`: type`).
2205 if (op.isDeclaration() || op.getAliasee()) {
2206 printType();
2207 return;
2208 }
2209
2210 p << "= ";
2211 if (!ctorRegion.empty()) {
2212 p << "ctor ";
2213 printType();
2214 p << " ";
2215 p.printRegion(ctorRegion,
2216 /*printEntryBlockArgs=*/false,
2217 /*printBlockTerminators=*/false);
2218 } else {
2219 // This also prints the type...
2220 if (initAttr)
2221 printConstant(p, initAttr);
2222 }
2223
2224 if (!dtorRegion.empty()) {
2225 p << " dtor ";
2226 p.printRegion(dtorRegion,
2227 /*printEntryBlockArgs=*/false,
2228 /*printBlockTerminators=*/false);
2229 }
2230}
2231
2232static ParseResult parseGlobalOpTypeAndInitialValue(OpAsmParser &parser,
2233 TypeAttr &typeAttr,
2234 Attribute &initialValueAttr,
2235 mlir::Region &ctorRegion,
2236 mlir::Region &dtorRegion) {
2237 mlir::Type opTy;
2238 if (parser.parseOptionalEqual().failed()) {
2239 // Absence of equal means a declaration, so we need to parse the type.
2240 // cir.global @a : !cir.int<s, 32>
2241 if (parser.parseColonType(opTy))
2242 return failure();
2243 } else {
2244 // Parse contructor, example:
2245 // cir.global @rgb = ctor : type { ... }
2246 if (!parser.parseOptionalKeyword("ctor")) {
2247 if (parser.parseColonType(opTy))
2248 return failure();
2249 auto parseLoc = parser.getCurrentLocation();
2250 if (parser.parseRegion(ctorRegion, /*arguments=*/{}, /*argTypes=*/{}))
2251 return failure();
2252 if (ensureRegionTerm(parser, ctorRegion, parseLoc).failed())
2253 return failure();
2254 } else {
2255 // Parse constant with initializer, examples:
2256 // cir.global @y = 3.400000e+00 : f32
2257 // cir.global @rgb = #cir.const_array<[...] : !cir.array<i8 x 3>>
2258 if (parseConstantValue(parser, initialValueAttr).failed())
2259 return failure();
2260
2261 assert(mlir::isa<mlir::TypedAttr>(initialValueAttr) &&
2262 "Non-typed attrs shouldn't appear here.");
2263 opTy = mlir::cast<mlir::TypedAttr>(initialValueAttr).getType();
2264 }
2265
2266 // Parse destructor, example:
2267 // dtor { ... }
2268 if (!parser.parseOptionalKeyword("dtor")) {
2269 auto parseLoc = parser.getCurrentLocation();
2270 if (parser.parseRegion(dtorRegion, /*arguments=*/{}, /*argTypes=*/{}))
2271 return failure();
2272 if (ensureRegionTerm(parser, dtorRegion, parseLoc).failed())
2273 return failure();
2274 }
2275 }
2276
2277 typeAttr = TypeAttr::get(opTy);
2278 return success();
2279}
2280
2281//===----------------------------------------------------------------------===//
2282// GetGlobalOp
2283//===----------------------------------------------------------------------===//
2284
2285LogicalResult
2286cir::GetGlobalOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2287 // Verify that the result type underlying pointer type matches the type of
2288 // the referenced cir.global or cir.func op.
2289 mlir::Operation *op =
2290 symbolTable.lookupNearestSymbolFrom(*this, getNameAttr());
2291 if (op == nullptr || !(isa<GlobalOp>(op) || isa<FuncOp>(op)))
2292 return emitOpError("'")
2293 << getName()
2294 << "' does not reference a valid cir.global or cir.func";
2295
2296 mlir::Type symTy;
2297 mlir::ptr::MemorySpaceAttrInterface symAddrSpaceAttr{};
2298 if (auto g = dyn_cast<GlobalOp>(op)) {
2299 symTy = g.getSymType();
2300 symAddrSpaceAttr = g.getAddrSpaceAttr();
2301 // Verify that for thread local global access, the global needs to
2302 // be marked with tls bits.
2303 if (getTls() && !g.getTlsModel())
2304 return emitOpError("access to global not marked thread local");
2305
2306 // Verify that the static_local attribute on GetGlobalOp matches the
2307 // static_local_guard attribute on GlobalOp. GetGlobalOp uses a UnitAttr,
2308 // GlobalOp uses StaticLocalGuardAttr. Both should be present, or neither.
2309 bool getGlobalIsStaticLocal = getStaticLocal();
2310 bool globalIsStaticLocal = g.getStaticLocalGuard().has_value();
2311 if (getGlobalIsStaticLocal != globalIsStaticLocal &&
2312 !getOperation()->getParentOfType<cir::GlobalOp>())
2313 return emitOpError("static_local attribute mismatch");
2314 } else if (auto f = dyn_cast<FuncOp>(op)) {
2315 symTy = f.getFunctionType();
2316 } else {
2317 llvm_unreachable("Unexpected operation for GetGlobalOp");
2318 }
2319
2320 auto resultType = dyn_cast<PointerType>(getAddr().getType());
2321 if (!resultType || symTy != resultType.getPointee())
2322 return emitOpError("result type pointee type '")
2323 << resultType.getPointee() << "' does not match type " << symTy
2324 << " of the global @" << getName();
2325
2326 if (symAddrSpaceAttr != resultType.getAddrSpace()) {
2327 return emitOpError()
2328 << "result type address space does not match the address "
2329 "space of the global @"
2330 << getName();
2331 }
2332
2333 return success();
2334}
2335
2336//===----------------------------------------------------------------------===//
2337// VTableAddrPointOp
2338//===----------------------------------------------------------------------===//
2339
2340LogicalResult
2341cir::VTableAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2342 StringRef name = getName();
2343
2344 // Verify that the result type underlying pointer type matches the type of
2345 // the referenced cir.global.
2346 auto op =
2347 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*this, getNameAttr());
2348 if (!op)
2349 return emitOpError("'")
2350 << name << "' does not reference a valid cir.global";
2351 std::optional<mlir::Attribute> init = op.getInitialValue();
2352 if (!init)
2353 return success();
2354 if (!isa<cir::VTableAttr>(*init))
2355 return emitOpError("Expected #cir.vtable in initializer for global '")
2356 << name << "'";
2357 return success();
2358}
2359
2360//===----------------------------------------------------------------------===//
2361// VTTAddrPointOp
2362//===----------------------------------------------------------------------===//
2363
2364LogicalResult
2365cir::VTTAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2366 // VTT ptr is not coming from a symbol.
2367 if (!getName())
2368 return success();
2369 StringRef name = *getName();
2370
2371 // Verify that the result type underlying pointer type matches the type of
2372 // the referenced cir.global op.
2373 auto op =
2374 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*this, getNameAttr());
2375 if (!op)
2376 return emitOpError("'")
2377 << name << "' does not reference a valid cir.global";
2378 std::optional<mlir::Attribute> init = op.getInitialValue();
2379 if (!init)
2380 return success();
2381 if (!isa<cir::ConstArrayAttr>(*init))
2382 return emitOpError(
2383 "Expected constant array in initializer for global VTT '")
2384 << name << "'";
2385 return success();
2386}
2387
2388LogicalResult cir::VTTAddrPointOp::verify() {
2389 // The operation uses either a symbol or a value to operate, but not both
2390 if (getName() && getSymAddr())
2391 return emitOpError("should use either a symbol or value, but not both");
2392
2393 // If not a symbol, stick with the concrete type used for getSymAddr.
2394 if (getSymAddr())
2395 return success();
2396
2397 mlir::Type resultType = getAddr().getType();
2398 mlir::Type resTy = cir::PointerType::get(
2399 cir::PointerType::get(cir::VoidType::get(getContext())));
2400
2401 if (resultType != resTy)
2402 return emitOpError("result type must be ")
2403 << resTy << ", but provided result type is " << resultType;
2404 return success();
2405}
2406
2407//===----------------------------------------------------------------------===//
2408// FuncOp
2409//===----------------------------------------------------------------------===//
2410
2411/// Returns the name used for the linkage attribute. This *must* correspond to
2412/// the name of the attribute in ODS.
2413static llvm::StringRef getLinkageAttrNameString() { return "linkage"; }
2414
2415void cir::FuncOp::build(OpBuilder &builder, OperationState &result,
2416 StringRef name, FuncType type,
2417 GlobalLinkageKind linkage, CallingConv callingConv) {
2418 result.addRegion();
2419 result.addAttribute(SymbolTable::getSymbolAttrName(),
2420 builder.getStringAttr(name));
2421 result.addAttribute(getFunctionTypeAttrName(result.name),
2422 TypeAttr::get(type));
2423 result.addAttribute(
2425 GlobalLinkageKindAttr::get(builder.getContext(), linkage));
2426 result.addAttribute(getCallingConvAttrName(result.name),
2427 CallingConvAttr::get(builder.getContext(), callingConv));
2428}
2429
2430//===----------------------------------------------------------------------===//
2431// AnnotationAttr
2432//===----------------------------------------------------------------------===//
2433
2434LogicalResult
2435cir::AnnotationAttr::verify(function_ref<InFlightDiagnostic()> emitError,
2436 mlir::StringAttr name, mlir::ArrayAttr args) {
2437 if (!args)
2438 return success();
2439 for (mlir::Attribute arg : args) {
2440 if (!isa<mlir::StringAttr, mlir::IntegerAttr>(arg))
2441 return emitError() << "annotation args must be StringAttr or IntegerAttr,"
2442 << " got " << arg;
2443 }
2444 return success();
2445}
2446
2447ParseResult cir::FuncOp::parse(OpAsmParser &parser, OperationState &state) {
2448 llvm::SMLoc loc = parser.getCurrentLocation();
2449 mlir::Builder &builder = parser.getBuilder();
2450
2451 mlir::StringAttr builtinNameAttr = getBuiltinAttrName(state.name);
2452 mlir::StringAttr coroutineNameAttr = getCoroutineAttrName(state.name);
2453 mlir::StringAttr inlineKindNameAttr = getInlineKindAttrName(state.name);
2454 mlir::StringAttr lambdaNameAttr = getLambdaAttrName(state.name);
2455 mlir::StringAttr noProtoNameAttr = getNoProtoAttrName(state.name);
2456 mlir::StringAttr comdatNameAttr = getComdatAttrName(state.name);
2457 mlir::StringAttr visNameAttr = getSymVisibilityAttrName(state.name);
2458 mlir::StringAttr dsoLocalNameAttr = getDsoLocalAttrName(state.name);
2459 mlir::StringAttr funcInfoNameAttr = getFuncInfoAttrName(state.name);
2460
2461 if (::mlir::succeeded(parser.parseOptionalKeyword(builtinNameAttr.strref())))
2462 state.addAttribute(builtinNameAttr, parser.getBuilder().getUnitAttr());
2463 if (::mlir::succeeded(
2464 parser.parseOptionalKeyword(coroutineNameAttr.strref())))
2465 state.addAttribute(coroutineNameAttr, parser.getBuilder().getUnitAttr());
2466
2467 // Parse optional inline kind attribute
2468 cir::InlineKindAttr inlineKindAttr;
2469 if (failed(parseInlineKindAttr(parser, inlineKindAttr)))
2470 return failure();
2471 if (inlineKindAttr)
2472 state.addAttribute(inlineKindNameAttr, inlineKindAttr);
2473
2474 if (::mlir::succeeded(parser.parseOptionalKeyword(lambdaNameAttr.strref())))
2475 state.addAttribute(lambdaNameAttr, parser.getBuilder().getUnitAttr());
2476 if (parser.parseOptionalKeyword(noProtoNameAttr).succeeded())
2477 state.addAttribute(noProtoNameAttr, parser.getBuilder().getUnitAttr());
2478
2479 if (parser.parseOptionalKeyword(comdatNameAttr).succeeded())
2480 state.addAttribute(comdatNameAttr, parser.getBuilder().getUnitAttr());
2481
2482 // Default to external linkage if no keyword is provided.
2483 state.addAttribute(getLinkageAttrNameString(),
2484 GlobalLinkageKindAttr::get(
2485 parser.getContext(),
2487 parser, GlobalLinkageKind::ExternalLinkage)));
2488
2489 ::llvm::StringRef visAttrStr;
2490 if (parser.parseOptionalKeyword(&visAttrStr, {"private", "public", "nested"})
2491 .succeeded()) {
2492 state.addAttribute(visNameAttr,
2493 parser.getBuilder().getStringAttr(visAttrStr));
2494 }
2495
2496 state.getOrAddProperties<cir::FuncOp::Properties>().global_visibility =
2497 parseOptionalCIRKeyword(parser, cir::VisibilityKind::Default);
2498
2499 if (parser.parseOptionalKeyword(dsoLocalNameAttr).succeeded())
2500 state.addAttribute(dsoLocalNameAttr, parser.getBuilder().getUnitAttr());
2501
2502 StringAttr nameAttr;
2503 if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
2504 state.attributes))
2505 return failure();
2509 bool isVariadic = false;
2510 if (function_interface_impl::parseFunctionSignatureWithArguments(
2511 parser, /*allowVariadic=*/true, arguments, isVariadic, resultTypes,
2512 resultAttrs))
2513 return failure();
2516 bool argAttrsEmpty = true;
2517 for (OpAsmParser::Argument &arg : arguments) {
2518 argTypes.push_back(arg.type);
2519 // Add the 'empty' attribute anyway to make sure the arity matches, but we
2520 // only want to 'set' the attribute at the top level if there is SOME data
2521 // along the way.
2522 argAttrs.push_back(arg.attrs);
2523 if (arg.attrs)
2524 argAttrsEmpty = false;
2525 }
2526
2527 // These should be in sync anyway, but test both of them anyway.
2528 if (resultTypes.size() > 1 || resultAttrs.size() > 1)
2529 return parser.emitError(
2530 loc, "functions with multiple return types are not supported");
2531
2532 mlir::Type returnType =
2533 (resultTypes.empty() ? cir::VoidType::get(builder.getContext())
2534 : resultTypes.front());
2535
2536 cir::FuncType fnType = cir::FuncType::get(argTypes, returnType, isVariadic);
2537 if (!fnType)
2538 return failure();
2539
2540 state.addAttribute(getFunctionTypeAttrName(state.name),
2541 TypeAttr::get(fnType));
2542
2543 if (!resultAttrs.empty() && resultAttrs[0])
2544 state.addAttribute(
2545 getResAttrsAttrName(state.name),
2546 mlir::ArrayAttr::get(parser.getContext(), {resultAttrs[0]}));
2547
2548 if (!argAttrsEmpty)
2549 state.addAttribute(getArgAttrsAttrName(state.name),
2550 mlir::ArrayAttr::get(parser.getContext(), argAttrs));
2551
2552 bool hasAlias = false;
2553 mlir::StringAttr aliaseeNameAttr = getAliaseeAttrName(state.name);
2554 if (parser.parseOptionalKeyword("alias").succeeded()) {
2555 if (parser.parseLParen().failed())
2556 return failure();
2557 mlir::StringAttr aliaseeAttr;
2558 if (parser.parseOptionalSymbolName(aliaseeAttr).failed())
2559 return failure();
2560 state.addAttribute(aliaseeNameAttr, FlatSymbolRefAttr::get(aliaseeAttr));
2561 if (parser.parseRParen().failed())
2562 return failure();
2563 hasAlias = true;
2564 }
2565
2566 mlir::StringAttr personalityNameAttr = getPersonalityAttrName(state.name);
2567 if (parser.parseOptionalKeyword("personality").succeeded()) {
2568 if (parser.parseLParen().failed())
2569 return failure();
2570 mlir::StringAttr personalityAttr;
2571 if (parser.parseOptionalSymbolName(personalityAttr).failed())
2572 return failure();
2573 state.addAttribute(personalityNameAttr,
2574 FlatSymbolRefAttr::get(personalityAttr));
2575 if (parser.parseRParen().failed())
2576 return failure();
2577 }
2578
2579 // Default to C calling convention if no keyword is provided.
2580 mlir::StringAttr callConvNameAttr = getCallingConvAttrName(state.name);
2581 cir::CallingConv callConv = cir::CallingConv::C;
2582 if (parser.parseOptionalKeyword("cc").succeeded()) {
2583 if (parser.parseLParen().failed())
2584 return failure();
2585 if (parseCIRKeyword<cir::CallingConv>(parser, callConv).failed())
2586 return parser.emitError(loc) << "unknown calling convention";
2587 if (parser.parseRParen().failed())
2588 return failure();
2589 }
2590 state.addAttribute(callConvNameAttr,
2591 cir::CallingConvAttr::get(parser.getContext(), callConv));
2592
2593 auto parseGlobalDtorCtor =
2594 [&](StringRef keyword,
2595 llvm::function_ref<void(std::optional<int> prio)> createAttr)
2596 -> mlir::LogicalResult {
2597 if (mlir::succeeded(parser.parseOptionalKeyword(keyword))) {
2598 std::optional<int> priority;
2599 if (mlir::succeeded(parser.parseOptionalLParen())) {
2600 auto parsedPriority = mlir::FieldParser<int>::parse(parser);
2601 if (mlir::failed(parsedPriority))
2602 return parser.emitError(parser.getCurrentLocation(),
2603 "failed to parse 'priority', of type 'int'");
2604 priority = parsedPriority.value_or(int());
2605 // Parse literal ')'
2606 if (parser.parseRParen())
2607 return failure();
2608 }
2609 createAttr(priority);
2610 }
2611 return success();
2612 };
2613
2614 // Parse the func_info attribute
2615 if (parser.parseOptionalKeyword("func_info").succeeded()) {
2616 if (parser.parseLess().failed())
2617 return failure();
2618
2619 llvm::SMLoc attrLoc = parser.getCurrentLocation();
2620 mlir::Attribute attr;
2621 if (parser.parseAttribute(attr).failed())
2622 return failure();
2623 if (!mlir::isa<cir::CXXCtorAttr, cir::CXXDtorAttr, cir::CXXAssignAttr,
2624 cir::FuncIdentityAttr>(attr))
2625 return parser.emitError(attrLoc,
2626 "expected a function info attribute, got ")
2627 << attr;
2628 state.addAttribute(funcInfoNameAttr, attr);
2629
2630 if (parser.parseGreater().failed())
2631 return failure();
2632 }
2633
2634 if (parseGlobalDtorCtor("global_ctor", [&](std::optional<int> priority) {
2635 mlir::IntegerAttr globalCtorPriorityAttr =
2636 builder.getI32IntegerAttr(priority.value_or(65535));
2637 state.addAttribute(getGlobalCtorPriorityAttrName(state.name),
2638 globalCtorPriorityAttr);
2639 }).failed())
2640 return failure();
2641
2642 if (parseGlobalDtorCtor("global_dtor", [&](std::optional<int> priority) {
2643 mlir::IntegerAttr globalDtorPriorityAttr =
2644 builder.getI32IntegerAttr(priority.value_or(65535));
2645 state.addAttribute(getGlobalDtorPriorityAttrName(state.name),
2646 globalDtorPriorityAttr);
2647 }).failed())
2648 return failure();
2649
2650 if (parser.parseOptionalKeyword("side_effect").succeeded()) {
2651 cir::SideEffect sideEffect;
2652
2653 if (parser.parseLParen().failed() ||
2654 parseCIRKeyword<cir::SideEffect>(parser, sideEffect).failed() ||
2655 parser.parseRParen().failed())
2656 return failure();
2657
2658 auto attr = cir::SideEffectAttr::get(parser.getContext(), sideEffect);
2659 state.addAttribute(CIRDialect::getSideEffectAttrName(), attr);
2660 }
2661
2662 // Parse optional annotations attribute (an ArrayAttr of AnnotationAttr).
2663 mlir::StringAttr annotationsNameAttr = getAnnotationsAttrName(state.name);
2664 mlir::ArrayAttr annotationsAttr;
2665 if (parser.parseOptionalAttribute(annotationsAttr).has_value() &&
2666 annotationsAttr)
2667 state.addAttribute(annotationsNameAttr, annotationsAttr);
2668
2669 // Parse the rest of the attributes.
2670 NamedAttrList parsedAttrs;
2671 if (parser.parseOptionalAttrDictWithKeyword(parsedAttrs))
2672 return failure();
2673
2674 for (StringRef disallowed : cir::FuncOp::getAttributeNames()) {
2675 if (parsedAttrs.get(disallowed))
2676 return parser.emitError(loc, "attribute '")
2677 << disallowed
2678 << "' should not be specified in the explicit attribute list";
2679 }
2680
2681 state.attributes.append(parsedAttrs);
2682
2683 // Parse the optional function body.
2684 auto *body = state.addRegion();
2685 OptionalParseResult parseResult = parser.parseOptionalRegion(
2686 *body, arguments, /*enableNameShadowing=*/false);
2687 if (parseResult.has_value()) {
2688 if (hasAlias)
2689 return parser.emitError(loc, "function alias shall not have a body");
2690 if (failed(*parseResult))
2691 return failure();
2692 // Function body was parsed, make sure its not empty.
2693 if (body->empty())
2694 return parser.emitError(loc, "expected non-empty function body");
2695 }
2696
2697 return success();
2698}
2699
2700// This function corresponds to `llvm::GlobalValue::isDeclaration` and should
2701// have a similar implementation. We don't currently ifuncs or materializable
2702// functions, but those should be handled here as they are implemented.
2703bool cir::FuncOp::isDeclaration() {
2705
2706 std::optional<StringRef> aliasee = getAliasee();
2707 if (!aliasee)
2708 return getFunctionBody().empty();
2709
2710 // Aliases are always definitions.
2711 return false;
2712}
2713
2714bool cir::FuncOp::isCXXSpecialMemberFunction() {
2715 // The func_info union can grow forms that are not special members, so the
2716 // check names the concrete forms rather than testing for presence.
2717 mlir::Attribute attr = getFuncInfoAttr();
2718 return attr && mlir::isa<CXXCtorAttr, CXXDtorAttr, CXXAssignAttr>(attr);
2719}
2720
2721bool cir::FuncOp::isCxxConstructor() {
2722 auto attr = getFuncInfoAttr();
2723 return attr && dyn_cast<CXXCtorAttr>(attr);
2724}
2725
2726bool cir::FuncOp::isCxxDestructor() {
2727 auto attr = getFuncInfoAttr();
2728 return attr && dyn_cast<CXXDtorAttr>(attr);
2729}
2730
2731bool cir::FuncOp::isCxxSpecialAssignment() {
2732 auto attr = getFuncInfoAttr();
2733 return attr && dyn_cast<CXXAssignAttr>(attr);
2734}
2735
2736std::optional<CtorKind> cir::FuncOp::getCxxConstructorKind() {
2737 mlir::Attribute attr = getFuncInfoAttr();
2738 if (attr) {
2739 if (auto ctor = dyn_cast<CXXCtorAttr>(attr))
2740 return ctor.getCtorKind();
2741 }
2742 return std::nullopt;
2743}
2744
2745std::optional<AssignKind> cir::FuncOp::getCxxSpecialAssignKind() {
2746 mlir::Attribute attr = getFuncInfoAttr();
2747 if (attr) {
2748 if (auto assign = dyn_cast<CXXAssignAttr>(attr))
2749 return assign.getAssignKind();
2750 }
2751 return std::nullopt;
2752}
2753
2754bool cir::FuncOp::isCxxTrivialMemberFunction() {
2755 mlir::Attribute attr = getFuncInfoAttr();
2756 if (attr) {
2757 if (auto ctor = dyn_cast<CXXCtorAttr>(attr))
2758 return ctor.getIsTrivial();
2759 if (auto dtor = dyn_cast<CXXDtorAttr>(attr))
2760 return dtor.getIsTrivial();
2761 if (auto assign = dyn_cast<CXXAssignAttr>(attr))
2762 return assign.getIsTrivial();
2763 }
2764 return false;
2765}
2766
2767mlir::Region *cir::FuncOp::getCallableRegion() {
2768 // TODO(CIR): This function will have special handling for aliases and a
2769 // check for an external function, once those features have been upstreamed.
2770 return &getBody();
2771}
2772
2773void cir::FuncOp::print(OpAsmPrinter &p) {
2774 if (getBuiltin())
2775 p << " builtin";
2776
2777 if (getCoroutine())
2778 p << " coroutine";
2779
2780 printInlineKindAttr(p, getInlineKindAttr());
2781
2782 if (getLambda())
2783 p << " lambda";
2784
2785 if (getNoProto())
2786 p << " no_proto";
2787
2788 if (getComdat())
2789 p << " comdat";
2790
2791 if (getLinkage() != GlobalLinkageKind::ExternalLinkage)
2792 p << ' ' << stringifyGlobalLinkageKind(getLinkage());
2793
2794 mlir::SymbolTable::Visibility vis = getVisibility();
2795 if (vis != mlir::SymbolTable::Visibility::Public)
2796 p << ' ' << vis;
2797
2798 if (getGlobalVisibility() != cir::VisibilityKind::Default)
2799 p << ' ' << stringifyVisibilityKind(getGlobalVisibility());
2800
2801 if (getDsoLocal())
2802 p << " dso_local";
2803
2804 p << ' ';
2805 p.printSymbolName(getSymName());
2806 cir::FuncType fnType = getFunctionType();
2807 function_interface_impl::printFunctionSignature(
2808 p, *this, fnType.getInputs(), fnType.isVarArg(), fnType.getReturnTypes());
2809
2810 if (std::optional<StringRef> aliaseeName = getAliasee()) {
2811 p << " alias(";
2812 p.printSymbolName(*aliaseeName);
2813 p << ")";
2814 }
2815
2816 if (getCallingConv() != cir::CallingConv::C) {
2817 p << " cc(";
2818 p << stringifyCallingConv(getCallingConv());
2819 p << ")";
2820 }
2821
2822 if (std::optional<StringRef> personalityName = getPersonality()) {
2823 p << " personality(";
2824 p.printSymbolName(*personalityName);
2825 p << ")";
2826 }
2827
2828 if (mlir::Attribute funcInfo = getFuncInfoAttr()) {
2829 p << " func_info<";
2830 p.printAttribute(funcInfo);
2831 p << '>';
2832 }
2833
2834 if (auto globalCtorPriority = getGlobalCtorPriority()) {
2835 p << " global_ctor";
2836 if (globalCtorPriority.value() != 65535)
2837 p << "(" << globalCtorPriority.value() << ")";
2838 }
2839
2840 if (auto globalDtorPriority = getGlobalDtorPriority()) {
2841 p << " global_dtor";
2842 if (globalDtorPriority.value() != 65535)
2843 p << "(" << globalDtorPriority.value() << ")";
2844 }
2845
2846 if (std::optional<cir::SideEffect> sideEffect = getSideEffect();
2847 sideEffect && *sideEffect != cir::SideEffect::All) {
2848 p << " side_effect(";
2849 p << stringifySideEffect(*sideEffect);
2850 p << ")";
2851 }
2852
2853 if (mlir::ArrayAttr annotations = getAnnotationsAttr()) {
2854 p << ' ';
2855 p.printAttribute(annotations);
2856 }
2857
2858 function_interface_impl::printFunctionAttributes(
2859 p, *this, cir::FuncOp::getAttributeNames());
2860
2861 // Print the body if this is not an external function.
2862 Region &body = getOperation()->getRegion(0);
2863 if (!body.empty()) {
2864 p << ' ';
2865 p.printRegion(body, /*printEntryBlockArgs=*/false,
2866 /*printBlockTerminators=*/true);
2867 }
2868}
2869
2870mlir::LogicalResult cir::FuncOp::verify() {
2871
2872 if (!isDeclaration() && getCoroutine()) {
2873 bool foundAwait = false;
2874 int coroBodyCount = 0;
2875 this->walk([&](Operation *op) {
2876 if (auto await = dyn_cast<AwaitOp>(op)) {
2877 foundAwait = true;
2878 } else if (isa<CoroBodyOp>(op)) {
2879 coroBodyCount++;
2880 if (coroBodyCount > 1) {
2881 return mlir::WalkResult::interrupt();
2882 }
2883 }
2884 return mlir::WalkResult::advance();
2885 });
2886 if (!foundAwait)
2887 return emitOpError()
2888 << "coroutine body must use at least one cir.await op";
2889 if (coroBodyCount != 1)
2890 return emitOpError()
2891 << "coroutine function must have exactly one cir.body op";
2892 }
2893
2894 llvm::SmallSet<llvm::StringRef, 16> labels;
2895 llvm::SmallSet<llvm::StringRef, 16> gotos;
2896 llvm::SmallSet<llvm::StringRef, 16> blockAddresses;
2897 bool invalidBlockAddress = false;
2898 getOperation()->walk([&](mlir::Operation *op) {
2899 if (auto lab = dyn_cast<cir::LabelOp>(op)) {
2900 labels.insert(lab.getLabel());
2901 } else if (auto goTo = dyn_cast<cir::GotoOp>(op)) {
2902 gotos.insert(goTo.getLabel());
2903 } else if (auto blkAdd = dyn_cast<cir::BlockAddressOp>(op)) {
2904 if (blkAdd.getBlockAddrInfoAttr().getFunc().getAttr() != getSymName()) {
2905 // Stop the walk early, no need to continue
2906 invalidBlockAddress = true;
2907 return mlir::WalkResult::interrupt();
2908 }
2909 blockAddresses.insert(blkAdd.getBlockAddrInfoAttr().getLabel());
2910 }
2911 return mlir::WalkResult::advance();
2912 });
2913
2914 if (invalidBlockAddress)
2915 return emitOpError() << "blockaddress references a different function";
2916
2917 llvm::SmallSet<llvm::StringRef, 16> mismatched;
2918 if (!labels.empty() || !gotos.empty()) {
2919 mismatched = llvm::set_difference(gotos, labels);
2920
2921 if (!mismatched.empty())
2922 return emitOpError() << "goto/label mismatch";
2923 }
2924
2925 mismatched.clear();
2926
2927 if (!labels.empty() || !blockAddresses.empty()) {
2928 mismatched = llvm::set_difference(blockAddresses, labels);
2929
2930 if (!mismatched.empty())
2931 return emitOpError()
2932 << "expects an existing label target in the referenced function";
2933 }
2934
2935 return success();
2936}
2937
2938//===----------------------------------------------------------------------===//
2939// AddOp / SubOp
2940//===----------------------------------------------------------------------===//
2941
2942// The integer-only type constraint on these ops makes the nsw/nuw/sat flag
2943// type checks unnecessary. Only the mutual-exclusivity between nsw/nuw and
2944// sat needs to be verified.
2945
2946LogicalResult cir::AddOp::verify() {
2947 if (getSaturated() && (getNoSignedWrap() || getNoUnsignedWrap()))
2948 return emitOpError()
2949 << "the nsw/nuw flags and the saturated flag are mutually exclusive";
2950 return mlir::success();
2951}
2952
2953LogicalResult cir::SubOp::verify() {
2954 if (getSaturated() && (getNoSignedWrap() || getNoUnsignedWrap()))
2955 return emitOpError()
2956 << "the nsw/nuw flags and the saturated flag are mutually exclusive";
2957 return mlir::success();
2958}
2959
2960//===----------------------------------------------------------------------===//
2961// TernaryOp
2962//===----------------------------------------------------------------------===//
2963
2964/// Given the region at `point`, or the parent operation if `point` is None,
2965/// return the successor regions. These are the regions that may be selected
2966/// during the flow of control. `operands` is a set of optional attributes that
2967/// correspond to a constant value for each operand, or null if that operand is
2968/// not a constant.
2969void cir::TernaryOp::getSuccessorRegions(
2970 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &regions) {
2971 // The `true` and the `false` region branch back to the parent operation.
2972 if (!point.isParent()) {
2973 regions.emplace_back(getOperation());
2974 return;
2975 }
2976
2977 // When branching from the parent operation, both the true and false
2978 // regions are considered possible successors
2979 regions.push_back(RegionSuccessor(&getTrueRegion()));
2980 regions.push_back(RegionSuccessor(&getFalseRegion()));
2981}
2982
2983mlir::ValueRange cir::TernaryOp::getSuccessorInputs(RegionSuccessor successor) {
2984 return successor.isOperation() ? ValueRange(getOperation()->getResults())
2985 : ValueRange();
2986}
2987
2988void cir::TernaryOp::build(
2989 OpBuilder &builder, OperationState &result, Value cond,
2990 function_ref<void(OpBuilder &, Location)> trueBuilder,
2991 function_ref<void(OpBuilder &, Location)> falseBuilder) {
2992 result.addOperands(cond);
2993 OpBuilder::InsertionGuard guard(builder);
2994 Region *trueRegion = result.addRegion();
2995 builder.createBlock(trueRegion);
2996 trueBuilder(builder, result.location);
2997 Region *falseRegion = result.addRegion();
2998 builder.createBlock(falseRegion);
2999 falseBuilder(builder, result.location);
3000
3001 // Get result type from whichever branch has a yield (the other may have
3002 // unreachable from a throw expression)
3003 cir::YieldOp yield;
3004 if (trueRegion->back().mightHaveTerminator())
3005 yield = dyn_cast_or_null<cir::YieldOp>(trueRegion->back().getTerminator());
3006 if (!yield && falseRegion->back().mightHaveTerminator())
3007 yield = dyn_cast_or_null<cir::YieldOp>(falseRegion->back().getTerminator());
3008
3009 assert((!yield || yield.getNumOperands() <= 1) &&
3010 "expected zero or one result type");
3011 if (yield && yield.getNumOperands() == 1)
3012 result.addTypes(TypeRange{yield.getOperandTypes().front()});
3013}
3014
3015//===----------------------------------------------------------------------===//
3016// SelectOp
3017//===----------------------------------------------------------------------===//
3018
3019OpFoldResult cir::SelectOp::fold(FoldAdaptor adaptor) {
3020 mlir::Attribute condition = adaptor.getCondition();
3021 if (condition) {
3022 bool conditionValue = mlir::cast<cir::BoolAttr>(condition).getValue();
3023 return conditionValue ? getTrueValue() : getFalseValue();
3024 }
3025
3026 // cir.select if %0 then x else x -> x
3027 mlir::Attribute trueValue = adaptor.getTrueValue();
3028 mlir::Attribute falseValue = adaptor.getFalseValue();
3029 if (trueValue == falseValue)
3030 return trueValue;
3031 if (getTrueValue() == getFalseValue())
3032 return getTrueValue();
3033
3034 return {};
3035}
3036
3037LogicalResult cir::SelectOp::verify() {
3038 // AllTypesMatch already guarantees trueVal and falseVal have matching types.
3039 auto condTy = dyn_cast<cir::VectorType>(getCondition().getType());
3040
3041 // If condition is not a vector, no further checks are needed.
3042 if (!condTy)
3043 return success();
3044
3045 // When condition is a vector, both other operands must also be vectors.
3046 if (!isa<cir::VectorType>(getTrueValue().getType()) ||
3047 !isa<cir::VectorType>(getFalseValue().getType())) {
3048 return emitOpError()
3049 << "expected both true and false operands to be vector types "
3050 "when the condition is a vector boolean type";
3051 }
3052
3053 return success();
3054}
3055
3056//===----------------------------------------------------------------------===//
3057// ShiftOp
3058//===----------------------------------------------------------------------===//
3059LogicalResult cir::ShiftOp::verify() {
3060 mlir::Operation *op = getOperation();
3061 auto op0VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(0).getType());
3062 auto op1VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(1).getType());
3063 if (!op0VecTy ^ !op1VecTy)
3064 return emitOpError() << "input types cannot be one vector and one scalar";
3065
3066 if (op0VecTy) {
3067 if (op0VecTy.getSize() != op1VecTy.getSize())
3068 return emitOpError() << "input vector types must have the same size";
3069
3070 auto opResultTy = mlir::dyn_cast<cir::VectorType>(getType());
3071 if (!opResultTy)
3072 return emitOpError() << "the type of the result must be a vector "
3073 << "if it is vector shift";
3074
3075 auto op0VecEleTy = mlir::cast<cir::IntType>(op0VecTy.getElementType());
3076 auto op1VecEleTy = mlir::cast<cir::IntType>(op1VecTy.getElementType());
3077 if (op0VecEleTy.getWidth() != op1VecEleTy.getWidth())
3078 return emitOpError()
3079 << "vector operands do not have the same elements sizes";
3080
3081 auto resVecEleTy = mlir::cast<cir::IntType>(opResultTy.getElementType());
3082 if (op0VecEleTy.getWidth() != resVecEleTy.getWidth())
3083 return emitOpError() << "vector operands and result type do not have the "
3084 "same elements sizes";
3085 }
3086
3087 return mlir::success();
3088}
3089
3090//===----------------------------------------------------------------------===//
3091// LabelOp Definitions
3092//===----------------------------------------------------------------------===//
3093
3094LogicalResult cir::LabelOp::verify() {
3095 mlir::Operation *op = getOperation();
3096 mlir::Block *blk = op->getBlock();
3097 if (&blk->front() != op)
3098 return emitError() << "must be the first operation in a block";
3099
3100 return mlir::success();
3101}
3102
3103//===----------------------------------------------------------------------===//
3104// IncOp
3105//===----------------------------------------------------------------------===//
3106
3107OpFoldResult cir::IncOp::fold(FoldAdaptor adaptor) {
3108 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3109 return adaptor.getInput();
3110 return {};
3111}
3112
3113//===----------------------------------------------------------------------===//
3114// DecOp
3115//===----------------------------------------------------------------------===//
3116
3117OpFoldResult cir::DecOp::fold(FoldAdaptor adaptor) {
3118 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3119 return adaptor.getInput();
3120 return {};
3121}
3122
3123//===----------------------------------------------------------------------===//
3124// MinusOp
3125//===----------------------------------------------------------------------===//
3126
3127OpFoldResult cir::MinusOp::fold(FoldAdaptor adaptor) {
3128 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3129 return adaptor.getInput();
3130
3131 // Fold with constant inputs. Floating-point negation is handled by
3132 // cir::FNegOp.
3133 if (auto intAttr =
3134 mlir::dyn_cast_if_present<cir::IntAttr>(adaptor.getInput())) {
3135 APInt val = intAttr.getValue();
3136 val.negate();
3137 return cir::IntAttr::get(getType(), val);
3138 }
3139
3140 return {};
3141}
3142
3143//===----------------------------------------------------------------------===//
3144// FNegOp
3145//===----------------------------------------------------------------------===//
3146
3147OpFoldResult cir::FNegOp::fold(FoldAdaptor adaptor) {
3148 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3149 return adaptor.getInput();
3150
3151 // Fold with constant inputs.
3152 if (auto fpAttr =
3153 mlir::dyn_cast_if_present<cir::FPAttr>(adaptor.getInput())) {
3154 APFloat val = fpAttr.getValue();
3155 val.changeSign();
3156 return cir::FPAttr::get(getType(), val);
3157 }
3158
3159 return {};
3160}
3161
3162//===----------------------------------------------------------------------===//
3163// NotOp
3164//===----------------------------------------------------------------------===//
3165
3166OpFoldResult cir::NotOp::fold(FoldAdaptor adaptor) {
3167 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3168 return adaptor.getInput();
3169
3170 // not(not(x)) -> x is handled by the Involution trait.
3171
3172 // Fold with constant inputs.
3173 if (mlir::Attribute attr = adaptor.getInput()) {
3174 if (auto intAttr = mlir::dyn_cast<cir::IntAttr>(attr)) {
3175 APInt val = intAttr.getValue();
3176 val.flipAllBits();
3177 return cir::IntAttr::get(getType(), val);
3178 }
3179 if (auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr))
3180 return cir::BoolAttr::get(getContext(), !boolAttr.getValue());
3181 }
3182
3183 return {};
3184}
3185
3186//===----------------------------------------------------------------------===//
3187// BaseDataMemberOp & DerivedDataMemberOp
3188//===----------------------------------------------------------------------===//
3189
3190static LogicalResult verifyMemberPtrCast(Operation *op, mlir::Value src,
3191 mlir::Type resultTy) {
3192 // Let the operand type be T1 C1::*, let the result type be T2 C2::*.
3193 // Verify that T1 and T2 are the same type.
3194 mlir::Type inputMemberTy;
3195 mlir::Type resultMemberTy;
3196 if (mlir::isa<cir::DataMemberType>(src.getType())) {
3197 inputMemberTy =
3198 mlir::cast<cir::DataMemberType>(src.getType()).getMemberTy();
3199 resultMemberTy = mlir::cast<cir::DataMemberType>(resultTy).getMemberTy();
3200 }
3202 if (inputMemberTy != resultMemberTy)
3203 return op->emitOpError()
3204 << "member types of the operand and the result do not match";
3205
3206 return mlir::success();
3207}
3208
3209LogicalResult cir::BaseDataMemberOp::verify() {
3210 return verifyMemberPtrCast(getOperation(), getSrc(), getType());
3211}
3212
3213LogicalResult cir::DerivedDataMemberOp::verify() {
3214 return verifyMemberPtrCast(getOperation(), getSrc(), getType());
3215}
3216
3217//===----------------------------------------------------------------------===//
3218// BaseMethodOp & DerivedMethodOp
3219//===----------------------------------------------------------------------===//
3220
3221LogicalResult cir::BaseMethodOp::verify() {
3222 return verifyMemberPtrCast(getOperation(), getSrc(), getType());
3223}
3224
3225LogicalResult cir::DerivedMethodOp::verify() {
3226 return verifyMemberPtrCast(getOperation(), getSrc(), getType());
3227}
3228
3229//===----------------------------------------------------------------------===//
3230// AwaitOp
3231//===----------------------------------------------------------------------===//
3232
3233void cir::AwaitOp::build(OpBuilder &builder, OperationState &result,
3234 cir::AwaitKind kind, BuilderCallbackRef readyBuilder,
3235 BuilderCallbackRef suspendBuilder,
3236 BuilderCallbackRef resumeBuilder) {
3237 result.addAttribute(getKindAttrName(result.name),
3238 cir::AwaitKindAttr::get(builder.getContext(), kind));
3239 {
3240 OpBuilder::InsertionGuard guard(builder);
3241 Region *readyRegion = result.addRegion();
3242 builder.createBlock(readyRegion);
3243 readyBuilder(builder, result.location);
3244 }
3245
3246 {
3247 OpBuilder::InsertionGuard guard(builder);
3248 Region *suspendRegion = result.addRegion();
3249 builder.createBlock(suspendRegion);
3250 suspendBuilder(builder, result.location);
3251 }
3252
3253 {
3254 OpBuilder::InsertionGuard guard(builder);
3255 Region *resumeRegion = result.addRegion();
3256 builder.createBlock(resumeRegion);
3257 resumeBuilder(builder, result.location);
3258 }
3259}
3260
3261void cir::AwaitOp::getSuccessorRegions(
3262 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &regions) {
3263 // If any index all the underlying regions branch back to the parent
3264 // operation.
3265 if (!point.isParent()) {
3266 regions.emplace_back(getOperation());
3267 return;
3268 }
3269
3270 // TODO: retrieve information from the promise and only push the
3271 // necessary ones. Example: `std::suspend_never` on initial or final
3272 // await's might allow suspend region to be skipped.
3273 regions.push_back(RegionSuccessor(&this->getReady()));
3274 regions.push_back(RegionSuccessor(&this->getSuspend()));
3275 regions.push_back(RegionSuccessor(&this->getResume()));
3276}
3277
3278mlir::ValueRange cir::AwaitOp::getSuccessorInputs(RegionSuccessor successor) {
3279 if (successor.isOperation())
3280 return getOperation()->getResults();
3281 if (successor == &getReady())
3282 return getReady().getArguments();
3283 if (successor == &getSuspend())
3284 return getSuspend().getArguments();
3285 if (successor == &getResume())
3286 return getResume().getArguments();
3287 llvm_unreachable("invalid region successor");
3288}
3289
3290LogicalResult cir::AwaitOp::verify() {
3291 if (!isa<ConditionOp>(this->getReady().back().getTerminator()))
3292 return emitOpError("ready region must end with cir.condition");
3293 return success();
3294}
3295
3296//===----------------------------------------------------------------------===//
3297// CoroBody
3298//===----------------------------------------------------------------------===//
3299
3300void cir::CoroBodyOp::getSuccessorRegions(
3301 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &regions) {
3302 if (!point.isParent()) {
3303 regions.emplace_back(getOperation());
3304 return;
3305 }
3306
3307 regions.push_back(RegionSuccessor(&getBody()));
3308}
3309
3310mlir::ValueRange
3311cir::CoroBodyOp::getSuccessorInputs(RegionSuccessor successor) {
3312 return ValueRange();
3313}
3314
3315LogicalResult cir::CoroBodyOp::verify() {
3316 if (!getOperation()->getParentOfType<FuncOp>().getCoroutine())
3317 return emitOpError("enclosing function must be a coroutine");
3318 return success();
3319}
3320
3321void cir::CoroBodyOp::build(OpBuilder &builder, OperationState &result,
3322 BuilderCallbackRef bodyBuilder) {
3323 assert(bodyBuilder &&
3324 "the builder callback for 'CoroBodyOp' must be present");
3325 OpBuilder::InsertionGuard guard(builder);
3326
3327 Region *bodyRegion = result.addRegion();
3328 builder.createBlock(bodyRegion);
3329 bodyBuilder(builder, result.location);
3330}
3331
3332//===----------------------------------------------------------------------===//
3333// CopyOp Definitions
3334//===----------------------------------------------------------------------===//
3335
3336// Prints the pointer type(s) for a `cir.copy`. `src` and `dst` share the same
3337// pointee type but may differ in address space; a single type is printed when
3338// they match, otherwise both are printed (`src` first).
3339static void printCopyTypes(mlir::OpAsmPrinter &printer, mlir::Operation *,
3340 mlir::Type srcType, mlir::Type dstType) {
3341 printer.printType(srcType);
3342 if (srcType != dstType) {
3343 printer << ", ";
3344 printer.printType(dstType);
3345 }
3346}
3347
3348static mlir::ParseResult parseCopyTypes(mlir::OpAsmParser &parser,
3349 mlir::Type &srcType,
3350 mlir::Type &dstType) {
3351 if (parser.parseType(srcType))
3352 return mlir::failure();
3353 if (parser.parseOptionalComma().succeeded()) {
3354 if (parser.parseType(dstType))
3355 return mlir::failure();
3356 } else {
3357 dstType = srcType;
3358 }
3359 return mlir::success();
3360}
3361
3362LogicalResult cir::CopyOp::verify() {
3363 // The pointee types of `src` and `dst` are guaranteed to match by the
3364 // SameOperandsPointeeType trait; they may still differ in address space.
3365
3366 // A data layout is required for us to know the number of bytes to be copied.
3367 if (!getType().getPointee().hasTrait<DataLayoutTypeInterface::Trait>())
3368 return emitError() << "missing data layout for pointee type";
3369
3370 if (getSkipTailPadding() &&
3371 !mlir::isa<cir::RecordType>(getType().getPointee()))
3372 return emitError()
3373 << "skip_tail_padding is only valid for record pointee types";
3374
3375 return mlir::success();
3376}
3377
3378//===----------------------------------------------------------------------===//
3379// GetRuntimeMemberOp Definitions
3380//===----------------------------------------------------------------------===//
3381
3382LogicalResult cir::GetRuntimeMemberOp::verify() {
3383 cir::DataMemberType memberPtrTy = getMember().getType();
3384
3385 if (getAddr().getType().getPointee() != memberPtrTy.getClassTy())
3386 return emitError() << "record type does not match the member pointer type";
3387 if (getType().getPointee() != memberPtrTy.getMemberTy())
3388 return emitError() << "result type does not match the member pointer type";
3389 return mlir::success();
3390}
3391
3392//===----------------------------------------------------------------------===//
3393// GetMethodOp Definitions
3394//===----------------------------------------------------------------------===//
3395
3396LogicalResult cir::GetMethodOp::verify() {
3397 cir::MethodType methodTy = getMethod().getType();
3398
3399 // Assume objectTy is !cir.ptr<!T>
3400 cir::PointerType objectPtrTy = getObject().getType();
3401 mlir::Type objectTy = objectPtrTy.getPointee();
3402
3403 if (methodTy.getClassTy() != objectTy)
3404 return emitError() << "method class type and object type do not match";
3405
3406 // Assume methodFuncTy is !cir.func<!Ret (!Args)>
3407 auto calleeTy = mlir::cast<cir::FuncType>(getCallee().getType().getPointee());
3408 cir::FuncType methodFuncTy = methodTy.getMemberFuncTy();
3409
3410 // We verify at here that calleeTy is !cir.func<!Ret (!cir.ptr<!void>, !Args)>
3411 // Note that the first parameter type of the callee is !cir.ptr<!void> instead
3412 // of !cir.ptr<!T> because the "this" pointer may be adjusted before calling
3413 // the callee.
3414
3415 if (methodFuncTy.getReturnType() != calleeTy.getReturnType())
3416 return emitError()
3417 << "method return type and callee return type do not match";
3418
3419 llvm::ArrayRef<mlir::Type> calleeArgsTy = calleeTy.getInputs();
3420 llvm::ArrayRef<mlir::Type> methodFuncArgsTy = methodFuncTy.getInputs();
3421
3422 if (calleeArgsTy.empty())
3423 return emitError() << "callee parameter list lacks receiver object ptr";
3424
3425 auto calleeThisArgPtrTy = mlir::dyn_cast<cir::PointerType>(calleeArgsTy[0]);
3426 if (!calleeThisArgPtrTy ||
3427 !mlir::isa<cir::VoidType>(calleeThisArgPtrTy.getPointee())) {
3428 return emitError()
3429 << "the first parameter of callee must be a void pointer";
3430 }
3431
3432 if (calleeArgsTy.size() != methodFuncArgsTy.size())
3433 return emitError() << "callee and method parameter counts do not match";
3434
3435 if (calleeArgsTy.size() > 1 &&
3436 calleeArgsTy.slice(1) != methodFuncArgsTy.slice(1))
3437 return emitError()
3438 << "callee parameters and method parameters do not match";
3439
3440 return mlir::success();
3441}
3442
3443//===----------------------------------------------------------------------===//
3444// GetMemberOp Definitions
3445//===----------------------------------------------------------------------===//
3446
3447LogicalResult cir::GetMemberOp::verify() {
3448 const auto recordTy = dyn_cast<RecordType>(getAddrTy().getPointee());
3449 if (!recordTy)
3450 return emitError() << "expected pointer to a record type";
3451
3452 if (recordTy.getMembers().size() <= getIndex())
3453 return emitError() << "member index out of bounds";
3454
3455 if (recordTy.getMembers()[getIndex()] != getType().getPointee())
3456 return emitError() << "member type mismatch";
3457
3458 return mlir::success();
3459}
3460
3461//===----------------------------------------------------------------------===//
3462// ExtractMemberOp Definitions
3463//===----------------------------------------------------------------------===//
3464
3465LogicalResult cir::ExtractMemberOp::verify() {
3466 if (mlir::isa<cir::UnionType>(getRecord().getType()))
3467 return emitError()
3468 << "cir.extract_member currently does not support unions";
3469 auto structTy = mlir::cast<cir::StructType>(getRecord().getType());
3470 if (structTy.getMembers().size() <= getIndex())
3471 return emitError() << "member index out of bounds";
3472 if (structTy.getMembers()[getIndex()] != getType())
3473 return emitError() << "member type mismatch";
3474 return mlir::success();
3475}
3476
3477//===----------------------------------------------------------------------===//
3478// InsertMemberOp Definitions
3479//===----------------------------------------------------------------------===//
3480
3481LogicalResult cir::InsertMemberOp::verify() {
3482 if (mlir::isa<cir::UnionType>(getRecord().getType()))
3483 return emitError() << "cir.insert_member currently does not support unions";
3484 auto structTy = mlir::cast<cir::StructType>(getRecord().getType());
3485 if (structTy.getMembers().size() <= getIndex())
3486 return emitError() << "member index out of bounds";
3487 if (structTy.getMembers()[getIndex()] != getValue().getType())
3488 return emitError() << "member type mismatch";
3489 // The op trait already checks that the types of $result and $record match.
3490 return mlir::success();
3491}
3492
3493//===----------------------------------------------------------------------===//
3494// VecCreateOp
3495//===----------------------------------------------------------------------===//
3496
3497OpFoldResult cir::VecCreateOp::fold(FoldAdaptor adaptor) {
3498 if (llvm::any_of(getElements(), [](mlir::Value value) {
3499 return !value.getDefiningOp<cir::ConstantOp>();
3500 }))
3501 return {};
3502
3503 return cir::ConstVectorAttr::get(
3504 getType(), mlir::ArrayAttr::get(getContext(), adaptor.getElements()));
3505}
3506
3507LogicalResult cir::VecCreateOp::verify() {
3508 // Verify that the number of arguments matches the number of elements in the
3509 // vector, and that the type of all the arguments matches the type of the
3510 // elements in the vector.
3511 const cir::VectorType vecTy = getType();
3512 if (getElements().size() != vecTy.getSize()) {
3513 return emitOpError() << "operand count of " << getElements().size()
3514 << " doesn't match vector type " << vecTy
3515 << " element count of " << vecTy.getSize();
3516 }
3517
3518 const mlir::Type elementType = vecTy.getElementType();
3519 for (const mlir::Value element : getElements()) {
3520 if (element.getType() != elementType) {
3521 return emitOpError() << "operand type " << element.getType()
3522 << " doesn't match vector element type "
3523 << elementType;
3524 }
3525 }
3526
3527 return success();
3528}
3529
3530//===----------------------------------------------------------------------===//
3531// VecExtractOp
3532//===----------------------------------------------------------------------===//
3533
3534OpFoldResult cir::VecExtractOp::fold(FoldAdaptor adaptor) {
3535 const auto vectorAttr =
3536 llvm::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec());
3537 if (!vectorAttr)
3538 return {};
3539
3540 const auto indexAttr =
3541 llvm::dyn_cast_if_present<cir::IntAttr>(adaptor.getIndex());
3542 if (!indexAttr)
3543 return {};
3544
3545 const mlir::ArrayAttr elements = vectorAttr.getElts();
3546 const uint64_t index = indexAttr.getUInt();
3547 if (index >= elements.size())
3548 return {};
3549
3550 return elements[index];
3551}
3552
3553//===----------------------------------------------------------------------===//
3554// CmpOp
3555//===----------------------------------------------------------------------===//
3556
3557LogicalResult cir::CmpOp::verify() {
3558 if (getFenvAttr() && !cir::isAnyFloatingPointType(getLhs().getType()))
3559 return emitOpError()
3560 << "'fenv' is only valid for floating-point comparisons";
3561 return success();
3562}
3563
3564//===----------------------------------------------------------------------===//
3565// VecCmpOp
3566//===----------------------------------------------------------------------===//
3567
3568LogicalResult cir::VecCmpOp::verify() {
3569 if (getFenvAttr() && !cir::isFPOrVectorOfFPType(getLhs().getType()))
3570 return emitOpError()
3571 << "'fenv' is only valid for floating-point comparisons";
3572 return success();
3573}
3574
3575OpFoldResult cir::VecCmpOp::fold(FoldAdaptor adaptor) {
3576 // Do not fold when fenv is present.
3577 // TODO(cir): This is overly conservative. We could fold comparisons as long
3578 // as we can prove that the operation wouldn't raise exceptions or
3579 // when the fenv attribute does not require strict exception
3580 // semantics.
3581 if (getFenvAttr())
3582 return {};
3583
3584 auto lhsVecAttr =
3585 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getLhs());
3586 auto rhsVecAttr =
3587 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getRhs());
3588 if (!lhsVecAttr || !rhsVecAttr)
3589 return {};
3590
3591 mlir::Type inputElemTy =
3592 mlir::cast<cir::VectorType>(lhsVecAttr.getType()).getElementType();
3593 if (!isAnyIntegerOrFloatingPointType(inputElemTy))
3594 return {};
3595
3596 cir::CmpOpKind opKind = adaptor.getKind();
3597 mlir::ArrayAttr lhsVecElhs = lhsVecAttr.getElts();
3598 mlir::ArrayAttr rhsVecElhs = rhsVecAttr.getElts();
3599 uint64_t vecSize = lhsVecElhs.size();
3600
3601 SmallVector<mlir::Attribute, 16> elements(vecSize);
3602 bool isIntAttr = vecSize && mlir::isa<cir::IntAttr>(lhsVecElhs[0]);
3603 bool isUnsignedInt =
3604 isIntAttr && mlir::cast<cir::IntType>(inputElemTy).isUnsigned();
3605 for (uint64_t i = 0; i < vecSize; i++) {
3606 mlir::Attribute lhsAttr = lhsVecElhs[i];
3607 mlir::Attribute rhsAttr = rhsVecElhs[i];
3608 bool cmpResult = false;
3609 switch (opKind) {
3610 case cir::CmpOpKind::lt: {
3611 if (isIntAttr) {
3612 if (isUnsignedInt)
3613 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() <
3614 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
3615 else
3616 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <
3617 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3618 } else {
3619 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <
3620 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3621 }
3622 break;
3623 }
3624 case cir::CmpOpKind::le: {
3625 if (isIntAttr) {
3626 if (isUnsignedInt)
3627 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() <=
3628 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
3629 else
3630 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <=
3631 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3632 } else {
3633 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <=
3634 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3635 }
3636 break;
3637 }
3638 case cir::CmpOpKind::gt: {
3639 if (isIntAttr) {
3640 if (isUnsignedInt)
3641 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() >
3642 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
3643 else
3644 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >
3645 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3646 } else {
3647 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >
3648 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3649 }
3650 break;
3651 }
3652 case cir::CmpOpKind::ge: {
3653 if (isIntAttr) {
3654 if (isUnsignedInt)
3655 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() >=
3656 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
3657 else
3658 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >=
3659 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3660 } else {
3661 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >=
3662 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3663 }
3664 break;
3665 }
3666 case cir::CmpOpKind::eq: {
3667 if (isIntAttr) {
3668 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() ==
3669 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3670 } else {
3671 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() ==
3672 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3673 }
3674 break;
3675 }
3676 case cir::CmpOpKind::ne: {
3677 if (isIntAttr) {
3678 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() !=
3679 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3680 } else {
3681 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() !=
3682 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3683 }
3684 break;
3685 }
3686 case cir::CmpOpKind::one: {
3687 llvm::APFloat::cmpResult cr =
3688 mlir::cast<cir::FPAttr>(lhsAttr).getValue().compare(
3689 mlir::cast<cir::FPAttr>(rhsAttr).getValue());
3690 cmpResult =
3691 cr != llvm::APFloat::cmpUnordered && cr != llvm::APFloat::cmpEqual;
3692 break;
3693 }
3694 case cir::CmpOpKind::uno: {
3695 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue().compare(
3696 mlir::cast<cir::FPAttr>(rhsAttr).getValue()) ==
3697 llvm::APFloat::cmpUnordered;
3698 break;
3699 }
3700 }
3701
3702 // A true result is all bits set (-1 in two's complement), and a false
3703 // result is all bits clear. For a 1-bit element type these are the same
3704 // bit pattern as 1 and 0, respectively.
3705 elements[i] =
3706 cir::IntAttr::get(getType().getElementType(), cmpResult ? -1LL : 0LL);
3707 }
3708
3709 return cir::ConstVectorAttr::get(
3710 getType(), mlir::ArrayAttr::get(getContext(), elements));
3711}
3712
3713//===----------------------------------------------------------------------===//
3714// VecShuffleOp
3715//===----------------------------------------------------------------------===//
3716
3717OpFoldResult cir::VecShuffleOp::fold(FoldAdaptor adaptor) {
3718 auto vec1Attr =
3719 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec1());
3720 auto vec2Attr =
3721 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec2());
3722 if (!vec1Attr || !vec2Attr)
3723 return {};
3724
3725 mlir::Type vec1ElemTy =
3726 mlir::cast<cir::VectorType>(vec1Attr.getType()).getElementType();
3727
3728 mlir::ArrayAttr vec1Elts = vec1Attr.getElts();
3729 mlir::ArrayAttr vec2Elts = vec2Attr.getElts();
3730 mlir::ArrayAttr indicesElts = adaptor.getIndices();
3731
3733 elements.reserve(indicesElts.size());
3734
3735 uint64_t vec1Size = vec1Elts.size();
3736 for (const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
3737 if (idxAttr.getSInt() == -1) {
3738 elements.push_back(cir::UndefAttr::get(vec1ElemTy));
3739 continue;
3740 }
3741
3742 uint64_t idxValue = idxAttr.getUInt();
3743 elements.push_back(idxValue < vec1Size ? vec1Elts[idxValue]
3744 : vec2Elts[idxValue - vec1Size]);
3745 }
3746
3747 return cir::ConstVectorAttr::get(
3748 getType(), mlir::ArrayAttr::get(getContext(), elements));
3749}
3750
3751LogicalResult cir::VecShuffleOp::verify() {
3752 // The number of elements in the indices array must match the number of
3753 // elements in the result type.
3754 if (getIndices().size() != getResult().getType().getSize()) {
3755 return emitOpError() << ": the number of elements in " << getIndices()
3756 << " and " << getResult().getType() << " don't match";
3757 }
3758
3759 // The element types of the two input vectors and of the result type must
3760 // match.
3761 if (getVec1().getType().getElementType() !=
3762 getResult().getType().getElementType()) {
3763 return emitOpError() << ": element types of " << getVec1().getType()
3764 << " and " << getResult().getType() << " don't match";
3765 }
3766
3767 const uint64_t maxValidIndex =
3768 getVec1().getType().getSize() + getVec2().getType().getSize() - 1;
3769 if (llvm::any_of(
3770 getIndices().getAsRange<cir::IntAttr>(), [&](cir::IntAttr idxAttr) {
3771 return idxAttr.getSInt() != -1 && idxAttr.getUInt() > maxValidIndex;
3772 })) {
3773 return emitOpError() << ": index for __builtin_shufflevector must be "
3774 "less than the total number of vector elements";
3775 }
3776 return success();
3777}
3778
3779//===----------------------------------------------------------------------===//
3780// VecShuffleDynamicOp
3781//===----------------------------------------------------------------------===//
3782
3783OpFoldResult cir::VecShuffleDynamicOp::fold(FoldAdaptor adaptor) {
3784 mlir::Attribute vec = adaptor.getVec();
3785 mlir::Attribute indices = adaptor.getIndices();
3786 if (mlir::isa_and_nonnull<cir::ConstVectorAttr>(vec) &&
3787 mlir::isa_and_nonnull<cir::ConstVectorAttr>(indices)) {
3788 auto vecAttr = mlir::cast<cir::ConstVectorAttr>(vec);
3789 auto indicesAttr = mlir::cast<cir::ConstVectorAttr>(indices);
3790
3791 mlir::ArrayAttr vecElts = vecAttr.getElts();
3792 mlir::ArrayAttr indicesElts = indicesAttr.getElts();
3793
3794 const uint64_t numElements = vecElts.size();
3795
3797 elements.reserve(numElements);
3798
3799 const uint64_t maskBits = llvm::NextPowerOf2(numElements - 1) - 1;
3800 for (const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
3801 uint64_t idxValue = idxAttr.getUInt();
3802 uint64_t newIdx = idxValue & maskBits;
3803 elements.push_back(vecElts[newIdx]);
3804 }
3805
3806 return cir::ConstVectorAttr::get(
3807 getType(), mlir::ArrayAttr::get(getContext(), elements));
3808 }
3809
3810 return {};
3811}
3812
3813LogicalResult cir::VecShuffleDynamicOp::verify() {
3814 // The number of elements in the two input vectors must match.
3815 if (getVec().getType().getSize() !=
3816 mlir::cast<cir::VectorType>(getIndices().getType()).getSize()) {
3817 return emitOpError() << ": the number of elements in " << getVec().getType()
3818 << " and " << getIndices().getType() << " don't match";
3819 }
3820 return success();
3821}
3822
3823//===----------------------------------------------------------------------===//
3824// VecTernaryOp
3825//===----------------------------------------------------------------------===//
3826
3827LogicalResult cir::VecTernaryOp::verify() {
3828 // Verify that the condition operand has the same number of elements as the
3829 // other operands. (The automatic verification already checked that all
3830 // operands are vector types and that the second and third operands are the
3831 // same type.)
3832 if (getCond().getType().getSize() != getLhs().getType().getSize()) {
3833 return emitOpError() << ": the number of elements in "
3834 << getCond().getType() << " and " << getLhs().getType()
3835 << " don't match";
3836 }
3837 return success();
3838}
3839
3840OpFoldResult cir::VecTernaryOp::fold(FoldAdaptor adaptor) {
3841 mlir::Attribute cond = adaptor.getCond();
3842 mlir::Attribute lhs = adaptor.getLhs();
3843 mlir::Attribute rhs = adaptor.getRhs();
3844
3845 if (!mlir::isa_and_nonnull<cir::ConstVectorAttr>(cond) ||
3846 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(lhs) ||
3847 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(rhs))
3848 return {};
3849 auto condVec = mlir::cast<cir::ConstVectorAttr>(cond);
3850 auto lhsVec = mlir::cast<cir::ConstVectorAttr>(lhs);
3851 auto rhsVec = mlir::cast<cir::ConstVectorAttr>(rhs);
3852
3853 mlir::ArrayAttr condElts = condVec.getElts();
3854
3856 elements.reserve(condElts.size());
3857
3858 for (const auto &[idx, condAttr] :
3859 llvm::enumerate(condElts.getAsRange<cir::IntAttr>())) {
3860 if (condAttr.getSInt()) {
3861 elements.push_back(lhsVec.getElts()[idx]);
3862 } else {
3863 elements.push_back(rhsVec.getElts()[idx]);
3864 }
3865 }
3866
3867 cir::VectorType vecTy = getLhs().getType();
3868 return cir::ConstVectorAttr::get(
3869 vecTy, mlir::ArrayAttr::get(getContext(), elements));
3870}
3871
3872//===----------------------------------------------------------------------===//
3873// ComplexCreateOp
3874//===----------------------------------------------------------------------===//
3875
3876LogicalResult cir::ComplexCreateOp::verify() {
3877 if (getType().getElementType() != getReal().getType()) {
3878 emitOpError()
3879 << "operand type of cir.complex.create does not match its result type";
3880 return failure();
3881 }
3882
3883 return success();
3884}
3885
3886OpFoldResult cir::ComplexCreateOp::fold(FoldAdaptor adaptor) {
3887 mlir::Attribute real = adaptor.getReal();
3888 mlir::Attribute imag = adaptor.getImag();
3889 if (!real || !imag)
3890 return {};
3891
3892 // When both of real and imag are constants, we can fold the operation into an
3893 // `#cir.const_complex` operation.
3894 auto realAttr = mlir::cast<mlir::TypedAttr>(real);
3895 auto imagAttr = mlir::cast<mlir::TypedAttr>(imag);
3896 return cir::ConstComplexAttr::get(realAttr, imagAttr);
3897}
3898
3899//===----------------------------------------------------------------------===//
3900// ComplexRealOp
3901//===----------------------------------------------------------------------===//
3902
3903LogicalResult cir::ComplexRealOp::verify() {
3904 mlir::Type operandTy = getOperand().getType();
3905 if (auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
3906 operandTy = complexOperandTy.getElementType();
3907
3908 if (getType() != operandTy) {
3909 emitOpError() << ": result type does not match operand type";
3910 return failure();
3911 }
3912
3913 return success();
3914}
3915
3916OpFoldResult cir::ComplexRealOp::fold(FoldAdaptor adaptor) {
3917 if (!mlir::isa<cir::ComplexType>(getOperand().getType()))
3918 return nullptr;
3919
3920 if (auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
3921 return complexCreateOp.getOperand(0);
3922
3923 auto complex =
3924 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
3925 return complex ? complex.getReal() : nullptr;
3926}
3927
3928//===----------------------------------------------------------------------===//
3929// ComplexImagOp
3930//===----------------------------------------------------------------------===//
3931
3932LogicalResult cir::ComplexImagOp::verify() {
3933 mlir::Type operandTy = getOperand().getType();
3934 if (auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
3935 operandTy = complexOperandTy.getElementType();
3936
3937 if (getType() != operandTy) {
3938 emitOpError() << ": result type does not match operand type";
3939 return failure();
3940 }
3941
3942 return success();
3943}
3944
3945OpFoldResult cir::ComplexImagOp::fold(FoldAdaptor adaptor) {
3946 if (!mlir::isa<cir::ComplexType>(getOperand().getType()))
3947 return nullptr;
3948
3949 if (auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
3950 return complexCreateOp.getOperand(1);
3951
3952 auto complex =
3953 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
3954 return complex ? complex.getImag() : nullptr;
3955}
3956
3957//===----------------------------------------------------------------------===//
3958// ComplexRealPtrOp
3959//===----------------------------------------------------------------------===//
3960
3961LogicalResult cir::ComplexRealPtrOp::verify() {
3962 mlir::Type resultPointeeTy = getType().getPointee();
3963 cir::PointerType operandPtrTy = getOperand().getType();
3964 auto operandPointeeTy =
3965 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
3966
3967 if (resultPointeeTy != operandPointeeTy.getElementType()) {
3968 return emitOpError() << ": result type does not match operand type";
3969 }
3970
3971 return success();
3972}
3973
3974//===----------------------------------------------------------------------===//
3975// ComplexImagPtrOp
3976//===----------------------------------------------------------------------===//
3977
3978LogicalResult cir::ComplexImagPtrOp::verify() {
3979 mlir::Type resultPointeeTy = getType().getPointee();
3980 cir::PointerType operandPtrTy = getOperand().getType();
3981 auto operandPointeeTy =
3982 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
3983
3984 if (resultPointeeTy != operandPointeeTy.getElementType()) {
3985 return emitOpError()
3986 << "cir.complex.imag_ptr result type does not match operand type";
3987 }
3988 return success();
3989}
3990
3991//===----------------------------------------------------------------------===//
3992// Bit manipulation operations
3993//===----------------------------------------------------------------------===//
3994
3995static OpFoldResult
3996foldUnaryBitOp(mlir::Attribute inputAttr,
3997 llvm::function_ref<llvm::APInt(const llvm::APInt &)> func,
3998 bool poisonZero = false) {
3999 if (mlir::isa_and_present<cir::PoisonAttr>(inputAttr)) {
4000 // Propagate poison value
4001 return inputAttr;
4002 }
4003
4004 auto input = mlir::dyn_cast_if_present<IntAttr>(inputAttr);
4005 if (!input)
4006 return nullptr;
4007
4008 llvm::APInt inputValue = input.getValue();
4009 if (poisonZero && inputValue.isZero())
4010 return cir::PoisonAttr::get(input.getType());
4011
4012 llvm::APInt resultValue = func(inputValue);
4013 return IntAttr::get(input.getType(), resultValue);
4014}
4015
4016OpFoldResult BitClrsbOp::fold(FoldAdaptor adaptor) {
4017 return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
4018 unsigned resultValue =
4019 inputValue.getBitWidth() - inputValue.getSignificantBits();
4020 return llvm::APInt(inputValue.getBitWidth(), resultValue);
4021 });
4022}
4023
4024OpFoldResult BitClzOp::fold(FoldAdaptor adaptor) {
4025 return foldUnaryBitOp(
4026 adaptor.getInput(),
4027 [](const llvm::APInt &inputValue) {
4028 unsigned resultValue = inputValue.countLeadingZeros();
4029 return llvm::APInt(inputValue.getBitWidth(), resultValue);
4030 },
4031 getPoisonZero());
4032}
4033
4034OpFoldResult BitCtzOp::fold(FoldAdaptor adaptor) {
4035 return foldUnaryBitOp(
4036 adaptor.getInput(),
4037 [](const llvm::APInt &inputValue) {
4038 return llvm::APInt(inputValue.getBitWidth(),
4039 inputValue.countTrailingZeros());
4040 },
4041 getPoisonZero());
4042}
4043
4044OpFoldResult BitFfsOp::fold(FoldAdaptor adaptor) {
4045 return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
4046 unsigned trailingZeros = inputValue.countTrailingZeros();
4047 unsigned result =
4048 trailingZeros == inputValue.getBitWidth() ? 0 : trailingZeros + 1;
4049 return llvm::APInt(inputValue.getBitWidth(), result);
4050 });
4051}
4052
4053OpFoldResult BitParityOp::fold(FoldAdaptor adaptor) {
4054 return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
4055 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount() % 2);
4056 });
4057}
4058
4059OpFoldResult BitPopcountOp::fold(FoldAdaptor adaptor) {
4060 return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
4061 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount());
4062 });
4063}
4064
4065OpFoldResult BitReverseOp::fold(FoldAdaptor adaptor) {
4066 return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
4067 return inputValue.reverseBits();
4068 });
4069}
4070
4071OpFoldResult ByteSwapOp::fold(FoldAdaptor adaptor) {
4072 return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
4073 return inputValue.byteSwap();
4074 });
4075}
4076
4077OpFoldResult RotateOp::fold(FoldAdaptor adaptor) {
4078 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()) ||
4079 mlir::isa_and_present<cir::PoisonAttr>(adaptor.getAmount())) {
4080 // Propagate poison values
4081 return cir::PoisonAttr::get(getType());
4082 }
4083
4084 auto input = mlir::dyn_cast_if_present<IntAttr>(adaptor.getInput());
4085 auto amount = mlir::dyn_cast_if_present<IntAttr>(adaptor.getAmount());
4086 if (!input && !amount)
4087 return nullptr;
4088
4089 // We could fold cir.rotate even if one of its two operands is not a constant:
4090 // - `cir.rotate left/right %0, 0` could be folded into just %0 even if %0
4091 // is not a constant.
4092 // - `cir.rotate left/right 0/0b111...111, %0` could be folded into 0 or
4093 // 0b111...111 even if %0 is not a constant.
4094
4095 llvm::APInt inputValue;
4096 if (input) {
4097 inputValue = input.getValue();
4098 if (inputValue.isZero() || inputValue.isAllOnes()) {
4099 // An input value of all 0s or all 1s will not change after rotation
4100 return input;
4101 }
4102 }
4103
4104 uint64_t amountValue;
4105 if (amount) {
4106 amountValue = amount.getValue().urem(getInput().getType().getWidth());
4107 if (amountValue == 0) {
4108 // A shift amount of 0 will not change the input value
4109 return getInput();
4110 }
4111 }
4112
4113 if (!input || !amount)
4114 return nullptr;
4115
4116 assert(inputValue.getBitWidth() == getInput().getType().getWidth() &&
4117 "input value must have the same bit width as the input type");
4118
4119 llvm::APInt resultValue;
4120 if (isRotateLeft())
4121 resultValue = inputValue.rotl(amountValue);
4122 else
4123 resultValue = inputValue.rotr(amountValue);
4124
4125 return IntAttr::get(input.getContext(), input.getType(), resultValue);
4126}
4127
4128//===----------------------------------------------------------------------===//
4129// InlineAsmOp
4130//===----------------------------------------------------------------------===//
4131
4132void cir::InlineAsmOp::print(OpAsmPrinter &p) {
4133 p << '(' << getAsmFlavor() << ", ";
4134 p.increaseIndent();
4135 p.printNewline();
4136
4137 llvm::SmallVector<std::string, 3> names{"out", "in", "in_out"};
4138 auto *nameIt = names.begin();
4139 auto *attrIt = getOperandAttrs().begin();
4140
4141 for (mlir::OperandRange ops : getAsmOperands()) {
4142 p << *nameIt << " = ";
4143
4144 p << '[';
4145 llvm::interleaveComma(llvm::make_range(ops.begin(), ops.end()), p,
4146 [&](Value value) {
4147 p.printOperand(value);
4148 p << " : " << value.getType();
4149 if (mlir::isa<mlir::UnitAttr>(*attrIt))
4150 p << " (maybe_memory)";
4151 attrIt++;
4152 });
4153 p << "],";
4154 p.printNewline();
4155 ++nameIt;
4156 }
4157
4158 p << "{";
4159 p.printString(getAsmString());
4160 p << " ";
4161 p.printString(getConstraints());
4162 p << "}";
4163 p.decreaseIndent();
4164 p << ')';
4165 if (getSideEffects())
4166 p << " side_effects";
4167
4168 std::array elidedAttrs{
4169 llvm::StringRef("asm_flavor"), llvm::StringRef("asm_string"),
4170 llvm::StringRef("constraints"), llvm::StringRef("operand_attrs"),
4171 llvm::StringRef("operands_segments"), llvm::StringRef("side_effects")};
4172 p.printOptionalAttrDict(getOperation()->getAttrs(), elidedAttrs);
4173
4174 if (auto v = getRes())
4175 p << " -> " << v.getType();
4176}
4177
4178void cir::InlineAsmOp::build(OpBuilder &odsBuilder, OperationState &odsState,
4179 ArrayRef<ValueRange> asmOperands,
4180 StringRef asmString, StringRef constraints,
4181 bool sideEffects, cir::AsmFlavor asmFlavor,
4182 ArrayRef<Attribute> operandAttrs) {
4183 // Set up the operands_segments for VariadicOfVariadic
4184 SmallVector<int32_t> segments;
4185 for (auto operandRange : asmOperands) {
4186 segments.push_back(operandRange.size());
4187 odsState.addOperands(operandRange);
4188 }
4189
4190 odsState.addAttribute(
4191 "operands_segments",
4192 DenseI32ArrayAttr::get(odsBuilder.getContext(), segments));
4193 odsState.addAttribute("asm_string", odsBuilder.getStringAttr(asmString));
4194 odsState.addAttribute("constraints", odsBuilder.getStringAttr(constraints));
4195 odsState.addAttribute("asm_flavor",
4196 AsmFlavorAttr::get(odsBuilder.getContext(), asmFlavor));
4197
4198 if (sideEffects)
4199 odsState.addAttribute("side_effects", odsBuilder.getUnitAttr());
4200
4201 odsState.addAttribute("operand_attrs", odsBuilder.getArrayAttr(operandAttrs));
4202}
4203
4204ParseResult cir::InlineAsmOp::parse(OpAsmParser &parser,
4205 OperationState &result) {
4207 llvm::SmallVector<int32_t> operandsGroupSizes;
4208 std::string asmString, constraints;
4209 Type resType;
4210 MLIRContext *ctxt = parser.getBuilder().getContext();
4211
4212 auto error = [&](const Twine &msg) -> LogicalResult {
4213 return parser.emitError(parser.getCurrentLocation(), msg);
4214 };
4215
4216 auto expected = [&](const std::string &c) {
4217 return error("expected '" + c + "'");
4218 };
4219
4220 if (parser.parseLParen().failed())
4221 return expected("(");
4222
4223 auto flavor = FieldParser<AsmFlavor, AsmFlavor>::parse(parser);
4224 if (failed(flavor))
4225 return error("Unknown AsmFlavor");
4226
4227 if (parser.parseComma().failed())
4228 return expected(",");
4229
4230 auto parseValue = [&](Value &v) {
4231 OpAsmParser::UnresolvedOperand op;
4232
4233 if (parser.parseOperand(op) || parser.parseColon())
4234 return error("can't parse operand");
4235
4236 Type typ;
4237 if (parser.parseType(typ).failed())
4238 return error("can't parse operand type");
4240 if (parser.resolveOperand(op, typ, tmp))
4241 return error("can't resolve operand");
4242 v = tmp[0];
4243 return mlir::success();
4244 };
4245
4246 auto parseOperands = [&](llvm::StringRef name) {
4247 if (parser.parseKeyword(name).failed())
4248 return error("expected " + name + " operands here");
4249 if (parser.parseEqual().failed())
4250 return expected("=");
4251 if (parser.parseLSquare().failed())
4252 return expected("[");
4253
4254 int size = 0;
4255 if (parser.parseOptionalRSquare().succeeded()) {
4256 operandsGroupSizes.push_back(size);
4257 if (parser.parseComma())
4258 return expected(",");
4259 return mlir::success();
4260 }
4261
4262 auto parseOperand = [&]() {
4263 Value val;
4264 if (parseValue(val).succeeded()) {
4265 result.operands.push_back(val);
4266 size++;
4267
4268 if (parser.parseOptionalLParen().failed()) {
4269 operandAttrs.push_back(mlir::DictionaryAttr::get(ctxt));
4270 return mlir::success();
4271 }
4272
4273 if (parser.parseKeyword("maybe_memory").succeeded()) {
4274 operandAttrs.push_back(mlir::UnitAttr::get(ctxt));
4275 if (parser.parseRParen())
4276 return expected(")");
4277 return mlir::success();
4278 } else {
4279 return expected("maybe_memory");
4280 }
4281 }
4282 return mlir::failure();
4283 };
4284
4285 if (parser.parseCommaSeparatedList(parseOperand).failed())
4286 return mlir::failure();
4287
4288 if (parser.parseRSquare().failed() || parser.parseComma().failed())
4289 return expected("]");
4290 operandsGroupSizes.push_back(size);
4291 return mlir::success();
4292 };
4293
4294 if (parseOperands("out").failed() || parseOperands("in").failed() ||
4295 parseOperands("in_out").failed())
4296 return error("failed to parse operands");
4297
4298 if (parser.parseLBrace())
4299 return expected("{");
4300 if (parser.parseString(&asmString))
4301 return error("asm string parsing failed");
4302 if (parser.parseString(&constraints))
4303 return error("constraints string parsing failed");
4304 if (parser.parseRBrace())
4305 return expected("}");
4306 if (parser.parseRParen())
4307 return expected(")");
4308
4309 if (parser.parseOptionalKeyword("side_effects").succeeded())
4310 result.attributes.set("side_effects", UnitAttr::get(ctxt));
4311
4312 if (parser.parseOptionalAttrDict(result.attributes).failed())
4313 return mlir::failure();
4314
4315 if (parser.parseOptionalArrow().succeeded() &&
4316 parser.parseType(resType).failed())
4317 return mlir::failure();
4318
4319 result.attributes.set("asm_flavor", AsmFlavorAttr::get(ctxt, *flavor));
4320 result.attributes.set("asm_string", StringAttr::get(ctxt, asmString));
4321 result.attributes.set("constraints", StringAttr::get(ctxt, constraints));
4322 result.attributes.set("operand_attrs", ArrayAttr::get(ctxt, operandAttrs));
4323 result.getOrAddProperties<InlineAsmOp::Properties>().operands_segments =
4324 parser.getBuilder().getDenseI32ArrayAttr(operandsGroupSizes);
4325 if (resType)
4326 result.addTypes(TypeRange{resType});
4327
4328 return mlir::success();
4329}
4330
4331//===----------------------------------------------------------------------===//
4332// ThrowOp / TryThrowOp
4333//===----------------------------------------------------------------------===//
4334
4335template <typename ThrowOpTy>
4336static mlir::LogicalResult verifyThrowOpImpl(ThrowOpTy op) {
4337 if (op.rethrows())
4338 return mlir::success();
4339
4340 if (op.getNumOperands() != 0) {
4341 if (op.getTypeInfo())
4342 return mlir::success();
4343 return op.emitOpError() << "'type_info' symbol attribute missing";
4344 }
4345
4346 return mlir::failure();
4347}
4348
4349mlir::LogicalResult cir::ThrowOp::verify() { return verifyThrowOpImpl(*this); }
4350
4351mlir::LogicalResult cir::TryThrowOp::verify() {
4352 return verifyThrowOpImpl(*this);
4353}
4354
4355//===----------------------------------------------------------------------===//
4356// AtomicFetchOp
4357//===----------------------------------------------------------------------===//
4358
4359LogicalResult cir::AtomicFetchOp::verify() {
4360 if (getBinop() != cir::AtomicFetchKind::Add &&
4361 getBinop() != cir::AtomicFetchKind::Sub &&
4362 getBinop() != cir::AtomicFetchKind::Max &&
4363 getBinop() != cir::AtomicFetchKind::Min &&
4364 getBinop() != cir::AtomicFetchKind::Maximum &&
4365 getBinop() != cir::AtomicFetchKind::Minimum &&
4366 getBinop() != cir::AtomicFetchKind::MaximumNum &&
4367 getBinop() != cir::AtomicFetchKind::MinimumNum &&
4368 !mlir::isa<cir::IntType>(getVal().getType()))
4369 return emitError("only atomic add, sub, max, min, maximum, minimum, "
4370 "maximum_num, and minimum_num operation could operate on "
4371 "floating-point values");
4372
4373 if ((getBinop() == cir::AtomicFetchKind::Maximum ||
4374 getBinop() == cir::AtomicFetchKind::Minimum ||
4375 getBinop() == cir::AtomicFetchKind::MaximumNum ||
4376 getBinop() == cir::AtomicFetchKind::MinimumNum) &&
4377 !mlir::isa<cir::FPTypeInterface>(getVal().getType()))
4378 return emitError("atomic maximum, minimum, maximum_num, and minimum_num "
4379 "operation could only operate on floating-point values");
4380
4381 return success();
4382}
4383
4384//===----------------------------------------------------------------------===//
4385// TypeInfoAttr
4386//===----------------------------------------------------------------------===//
4387
4388LogicalResult cir::TypeInfoAttr::verify(
4389 ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError,
4390 ::mlir::Type type, ::mlir::ArrayAttr typeInfoData) {
4391
4392 if (cir::ConstRecordAttr::verify(emitError, type, typeInfoData).failed())
4393 return failure();
4394
4395 return success();
4396}
4397
4398//===----------------------------------------------------------------------===//
4399// TryOp
4400//===----------------------------------------------------------------------===//
4401
4402void cir::TryOp::getSuccessorRegions(
4403 mlir::RegionBranchPoint point,
4405 // The `try` and the `catchers` region branch back to the parent operation.
4406 if (!point.isParent()) {
4407 regions.emplace_back(getOperation());
4408 return;
4409 }
4410
4411 regions.push_back(mlir::RegionSuccessor(&getTryRegion()));
4412
4413 // TODO(CIR): If we know a target function never throws a specific type, we
4414 // can remove the catch handler.
4415 for (mlir::Region &handlerRegion : this->getHandlerRegions())
4416 regions.push_back(mlir::RegionSuccessor(&handlerRegion));
4417}
4418
4419mlir::ValueRange cir::TryOp::getSuccessorInputs(RegionSuccessor successor) {
4420 return successor.isOperation() ? ValueRange(getOperation()->getResults())
4421 : ValueRange();
4422}
4423
4424LogicalResult cir::TryOp::verify() {
4425 mlir::ArrayAttr handlerTypes = getHandlerTypes();
4426 if (!handlerTypes) {
4427 if (!getHandlerRegions().empty())
4428 return emitOpError(
4429 "handler regions must be empty when no handler types are present");
4430 return success();
4431 }
4432
4433 mlir::MutableArrayRef<mlir::Region> handlerRegions = getHandlerRegions();
4434
4435 // The parser and builder won't allow this to happen, but the loop below
4436 // relies on the sizes being the same, so we check it here.
4437 if (handlerRegions.size() != handlerTypes.size())
4438 return emitOpError(
4439 "number of handler regions and handler types must match");
4440
4441 for (const auto &[typeAttr, handlerRegion] :
4442 llvm::zip(handlerTypes, handlerRegions)) {
4443 // Verify that handler regions have a !cir.eh_token block argument.
4444 mlir::Block &entryBlock = handlerRegion.front();
4445 if (entryBlock.getNumArguments() != 1 ||
4446 !mlir::isa<cir::EhTokenType>(entryBlock.getArgument(0).getType()))
4447 return emitOpError(
4448 "handler region must have a single '!cir.eh_token' argument");
4449
4450 // The unwind region does not require a cir.begin_catch.
4451 if (mlir::isa<cir::UnwindAttr>(typeAttr))
4452 continue;
4453
4454 // A catch handler region must start with cir.begin_catch, optionally
4455 // preceded by a single cir.construct_catch_param that performs any
4456 // pre-begin_catch initialization for the catch parameter.
4457 if (entryBlock.empty())
4458 return emitOpError("catch handler region must not be empty");
4459 mlir::Operation *firstOp = &entryBlock.front();
4460 if (mlir::isa_and_present<cir::ConstructCatchParamOp>(firstOp))
4461 firstOp = firstOp->getNextNode();
4462 if (!firstOp || !mlir::isa<cir::BeginCatchOp>(firstOp))
4463 return emitOpError(
4464 "catch handler region must start with 'cir.begin_catch'");
4465 }
4466
4467 return success();
4468}
4469
4470static void
4471printTryHandlerRegions(mlir::OpAsmPrinter &printer, cir::TryOp op,
4472 mlir::MutableArrayRef<mlir::Region> handlerRegions,
4473 mlir::ArrayAttr handlerTypes) {
4474 if (!handlerTypes)
4475 return;
4476
4477 for (const auto [typeIdx, typeAttr] : llvm::enumerate(handlerTypes)) {
4478 if (typeIdx)
4479 printer << " ";
4480
4481 if (mlir::isa<cir::CatchAllAttr>(typeAttr)) {
4482 printer << "catch all ";
4483 } else if (mlir::isa<cir::UnwindAttr>(typeAttr)) {
4484 printer << "unwind ";
4485 } else {
4486 printer << "catch [type ";
4487 printer.printAttribute(typeAttr);
4488 printer << "] ";
4489 }
4490
4491 // Print the handler region's !cir.eh_token block argument.
4492 mlir::Region &region = handlerRegions[typeIdx];
4493 if (!region.empty() && region.front().getNumArguments() > 0) {
4494 printer << "(";
4495 printer.printRegionArgument(region.front().getArgument(0));
4496 printer << ") ";
4497 }
4498
4499 printer.printRegion(region,
4500 /*printEntryBLockArgs=*/false,
4501 /*printBlockTerminators=*/true);
4502 }
4503}
4504
4505static mlir::ParseResult parseTryHandlerRegions(
4506 mlir::OpAsmParser &parser,
4507 llvm::SmallVectorImpl<std::unique_ptr<mlir::Region>> &handlerRegions,
4508 mlir::ArrayAttr &handlerTypes) {
4509
4510 auto parseCheckedCatcherRegion = [&]() -> mlir::ParseResult {
4511 handlerRegions.emplace_back(new mlir::Region);
4512
4513 mlir::Region &currRegion = *handlerRegions.back();
4514
4515 // Parse the required region argument: (%eh_token : !cir.eh_token)
4517 if (parser.parseLParen())
4518 return failure();
4519 mlir::OpAsmParser::Argument arg;
4520 if (parser.parseArgument(arg, /*allowType=*/true))
4521 return failure();
4522 regionArgs.push_back(arg);
4523 if (parser.parseRParen())
4524 return failure();
4525
4526 mlir::SMLoc regionLoc = parser.getCurrentLocation();
4527 if (parser.parseRegion(currRegion, regionArgs)) {
4528 handlerRegions.clear();
4529 return failure();
4530 }
4531
4532 if (currRegion.empty())
4533 return parser.emitError(regionLoc, "handler region shall not be empty");
4534
4535 if (!(currRegion.back().mightHaveTerminator() &&
4536 currRegion.back().getTerminator()))
4537 return parser.emitError(
4538 regionLoc, "blocks are expected to be explicitly terminated");
4539
4540 return success();
4541 };
4542
4543 bool hasCatchAll = false;
4545 while (parser.parseOptionalKeyword("catch").succeeded()) {
4546 bool hasLSquare = parser.parseOptionalLSquare().succeeded();
4547
4548 llvm::StringRef attrStr;
4549 if (parser.parseOptionalKeyword(&attrStr, {"all", "type"}).failed())
4550 return parser.emitError(parser.getCurrentLocation(),
4551 "expected 'all' or 'type' keyword");
4552
4553 bool isCatchAll = attrStr == "all";
4554 if (isCatchAll) {
4555 if (hasCatchAll)
4556 return parser.emitError(parser.getCurrentLocation(),
4557 "can't have more than one catch all");
4558 hasCatchAll = true;
4559 }
4560
4561 mlir::Attribute exceptionRTTIAttr;
4562 if (!isCatchAll && parser.parseAttribute(exceptionRTTIAttr).failed())
4563 return parser.emitError(parser.getCurrentLocation(),
4564 "expected valid RTTI info attribute");
4565
4566 catcherAttrs.push_back(isCatchAll
4567 ? cir::CatchAllAttr::get(parser.getContext())
4568 : exceptionRTTIAttr);
4569
4570 if (hasLSquare && isCatchAll)
4571 return parser.emitError(parser.getCurrentLocation(),
4572 "catch all dosen't need RTTI info attribute");
4573
4574 if (hasLSquare && parser.parseRSquare().failed())
4575 return parser.emitError(parser.getCurrentLocation(),
4576 "expected `]` after RTTI info attribute");
4577
4578 if (parseCheckedCatcherRegion().failed())
4579 return mlir::failure();
4580 }
4581
4582 if (parser.parseOptionalKeyword("unwind").succeeded()) {
4583 if (hasCatchAll)
4584 return parser.emitError(parser.getCurrentLocation(),
4585 "unwind can't be used with catch all");
4586
4587 catcherAttrs.push_back(cir::UnwindAttr::get(parser.getContext()));
4588 if (parseCheckedCatcherRegion().failed())
4589 return mlir::failure();
4590 }
4591
4592 handlerTypes = parser.getBuilder().getArrayAttr(catcherAttrs);
4593 return mlir::success();
4594}
4595
4596//===----------------------------------------------------------------------===//
4597// EhTypeIdOp
4598//===----------------------------------------------------------------------===//
4599
4600LogicalResult
4601cir::EhTypeIdOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
4602 Operation *op = symbolTable.lookupNearestSymbolFrom(*this, getTypeSymAttr());
4603 if (!isa_and_nonnull<GlobalOp>(op))
4604 return emitOpError("'")
4605 << getTypeSym() << "' does not reference a valid cir.global";
4606 return success();
4607}
4608
4609//===----------------------------------------------------------------------===//
4610// LifetimeStartOp & LifetimeEndOp
4611//===----------------------------------------------------------------------===//
4612
4613LogicalResult cir::LifetimeStartOp::verify() {
4614 return verifyProducedBy<cir::AllocaOp>(*this, getPtr(), "ptr");
4615}
4616
4617LogicalResult cir::LifetimeEndOp::verify() {
4618 return verifyProducedBy<cir::AllocaOp>(*this, getPtr(), "ptr");
4619}
4620
4621//===----------------------------------------------------------------------===//
4622// ConstructCatchParamOp
4623//===----------------------------------------------------------------------===//
4624
4625LogicalResult cir::ConstructCatchParamOp::verifySymbolUses(
4626 SymbolTableCollection &symbolTable) {
4627 auto copyFnAttr = getCopyFnAttr();
4628 if (!copyFnAttr)
4629 return success();
4630 auto fn =
4631 symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(*this, getCopyFnAttr());
4632 if (!fn)
4633 return emitOpError("'")
4634 << *getCopyFn() << "' does not reference a valid cir.func";
4635
4636 if (!fn->hasAttr(cir::CIRDialect::getCatchCopyThunkAttrName()))
4637 return emitOpError("catch-init copy_fn must be tagged with the ")
4638 << cir::CIRDialect::getCatchCopyThunkAttrName() << " attribute";
4639
4640 cir::FuncType fnType = fn.getFunctionType();
4641 if (fnType.getNumInputs() != 2 || !fnType.hasVoidReturn())
4642 return emitOpError("catch-init copy_fn must take two pointer arguments and "
4643 "return void");
4644
4645 if (fnType.getInput(0) != getParamAddr().getType())
4646 return emitOpError("first argument of catch-init copy_fn must match the "
4647 "type of 'param_addr'");
4648
4649 if (fnType.getInput(1) != getParamAddr().getType())
4650 return emitOpError(
4651 "second argument of catch-init copy_fn must be a pointer "
4652 "to the catch type");
4653
4654 return success();
4655}
4656
4657//===----------------------------------------------------------------------===//
4658// EhDispatchOp
4659//===----------------------------------------------------------------------===//
4660
4661static ParseResult
4662parseEhDispatchDestinations(OpAsmParser &parser, mlir::ArrayAttr &catchTypes,
4663 SmallVectorImpl<Block *> &catchDestinations,
4664 Block *&defaultDestination,
4665 mlir::UnitAttr &defaultIsCatchAll) {
4666 // Parse: [ ... ]
4667 if (parser.parseLSquare())
4668 return failure();
4669
4670 SmallVector<Attribute> handlerTypes;
4671 bool hasCatchAll = false;
4672 bool hasUnwind = false;
4673
4674 // Parse handler list.
4675 auto parseHandler = [&]() -> ParseResult {
4676 // Check for 'catch_all' or 'unwind' keywords.
4677 if (succeeded(parser.parseOptionalKeyword("catch_all"))) {
4678 if (hasCatchAll)
4679 return parser.emitError(parser.getCurrentLocation(),
4680 "duplicate 'catch_all' handler");
4681 if (hasUnwind)
4682 return parser.emitError(parser.getCurrentLocation(),
4683 "cannot have both 'catch_all' and 'unwind'");
4684 hasCatchAll = true;
4685
4686 if (parser.parseColon().failed())
4687 return failure();
4688
4689 if (parser.parseSuccessor(defaultDestination).failed())
4690 return failure();
4691
4692 return success();
4693 }
4694
4695 if (succeeded(parser.parseOptionalKeyword("unwind"))) {
4696 if (hasUnwind)
4697 return parser.emitError(parser.getCurrentLocation(),
4698 "duplicate 'unwind' handler");
4699 if (hasCatchAll)
4700 return parser.emitError(parser.getCurrentLocation(),
4701 "cannot have both 'catch_all' and 'unwind'");
4702 hasUnwind = true;
4703
4704 if (parser.parseColon().failed())
4705 return failure();
4706
4707 if (parser.parseSuccessor(defaultDestination).failed())
4708 return failure();
4709 return success();
4710 }
4711
4712 // Otherwise, expect 'catch(<attr> : <type>) : ^block'.
4713 // The 'catch(...)' wrapper allows the attribute to include its type
4714 // without conflicting with the ':' used for the block destination.
4715 if (parser.parseKeyword("catch").failed())
4716 return failure();
4717
4718 if (parser.parseLParen().failed())
4719 return failure();
4720
4721 mlir::Attribute catchTypeAttr;
4722 if (parser.parseAttribute(catchTypeAttr).failed())
4723 return failure();
4724 handlerTypes.push_back(catchTypeAttr);
4725
4726 if (parser.parseRParen().failed())
4727 return failure();
4728
4729 if (parser.parseColon().failed())
4730 return failure();
4731
4732 Block *dest;
4733 if (parser.parseSuccessor(dest).failed())
4734 return failure();
4735 catchDestinations.push_back(dest);
4736 return success();
4737 };
4738
4739 if (parser.parseCommaSeparatedList(parseHandler).failed())
4740 return failure();
4741
4742 if (parser.parseRSquare().failed())
4743 return failure();
4744
4745 // Verify we have catch_all or unwind.
4746 if (!hasCatchAll && !hasUnwind)
4747 return parser.emitError(parser.getCurrentLocation(),
4748 "must have either 'catch_all' or 'unwind' handler");
4749
4750 // Add attributes and successors.
4751 if (!handlerTypes.empty())
4752 catchTypes = parser.getBuilder().getArrayAttr(handlerTypes);
4753
4754 if (hasCatchAll)
4755 defaultIsCatchAll = parser.getBuilder().getUnitAttr();
4756
4757 return success();
4758}
4759
4760static void printEhDispatchDestinations(OpAsmPrinter &p, cir::EhDispatchOp op,
4761 mlir::ArrayAttr catchTypes,
4762 SuccessorRange catchDestinations,
4763 Block *defaultDestination,
4764 mlir::UnitAttr defaultIsCatchAll) {
4765 p << " [";
4766 p.printNewline();
4767
4768 // If we have at least one catch type, print them.
4769 if (catchTypes) {
4770 // Print type handlers using 'catch(<attr>) : ^block' syntax.
4771 llvm::interleave(
4772 llvm::zip(catchTypes, catchDestinations),
4773 [&](auto i) {
4774 p << " catch(";
4775 p.printAttribute(std::get<0>(i));
4776 p << ") : ";
4777 p.printSuccessor(std::get<1>(i));
4778 },
4779 [&] {
4780 p << ',';
4781 p.printNewline();
4782 });
4783
4784 p << ", ";
4785 p.printNewline();
4786 }
4787
4788 // Print catch_all or unwind handler.
4789 if (defaultIsCatchAll)
4790 p << " catch_all : ";
4791 else
4792 p << " unwind : ";
4793 p.printSuccessor(defaultDestination);
4794 p.printNewline();
4795
4796 p << "]";
4797}
4798
4799//===----------------------------------------------------------------------===//
4800// Standard library op signature matching
4801//===----------------------------------------------------------------------===//
4802
4803bool cir::StdFindOp::signatureMatches(mlir::TypeRange operands,
4804 mlir::TypeRange results) {
4805 if (operands.size() != getNumArgs() || results.size() != 1)
4806 return false;
4807 mlir::Type iterTy = operands[0];
4808 return iterTy == operands[1] && iterTy == operands[2] && iterTy == results[0];
4809}
4810
4811//===----------------------------------------------------------------------===//
4812// TableGen'd op method definitions
4813//===----------------------------------------------------------------------===//
4814
4815#define GET_OP_CLASSES
4816#include "clang/CIR/Dialect/IR/CIROps.cpp.inc"
static const MemRegion * getRegion(const CallEvent &Call, const MutexDescriptor &Descriptor, bool IsLock)
static LogicalResult verifyLoopCleanup(LoopOpTy op)
static void printEhDispatchDestinations(OpAsmPrinter &p, cir::EhDispatchOp op, mlir::ArrayAttr catchTypes, SuccessorRange catchDestinations, Block *defaultDestination, mlir::UnitAttr defaultIsCatchAll)
static mlir::LogicalResult checkReturnAndFunction(cir::ReturnOp op, cir::FuncOp function)
static void printCopyTypes(mlir::OpAsmPrinter &printer, mlir::Operation *, mlir::Type srcType, mlir::Type dstType)
static bool isCirFunctionPointerType(mlir::Type ty)
static LogicalResult verifyMemberPtrCast(Operation *op, mlir::Value src, mlir::Type resultTy)
static bool isFloatingPointCastKind(cir::CastKind kind)
static mlir::ParseResult parseCallCommon(mlir::OpAsmParser &parser, mlir::OperationState &result, bool hasDestinationBlocks=false)
static bool isIntOrBoolCast(cir::CastOp op)
static ParseResult parseAssumeBundle(OpAsmParser &p, cir::AssumeBundleKindAttr &bundleKindAttr, llvm::SmallVector< mlir::OpAsmParser::UnresolvedOperand, 4 > &bundleArgs, llvm::SmallVector< mlir::Type, 1 > &bundleArgTypes)
static ParseResult parseEhDispatchDestinations(OpAsmParser &parser, mlir::ArrayAttr &catchTypes, SmallVectorImpl< Block * > &catchDestinations, Block *&defaultDestination, mlir::UnitAttr &defaultIsCatchAll)
static void printConstant(OpAsmPrinter &p, Attribute value)
static mlir::ParseResult parseOmittedTerminatorRegion(mlir::OpAsmParser &parser, mlir::Region &region)
static void printAssumeBundle(OpAsmPrinter &p, cir::AssumeOp op, cir::AssumeBundleKindAttr kindAttr, OperandRange bundleArgs, TypeRange bundleArgTypes)
ParseResult parseInlineKindAttr(OpAsmParser &parser, cir::InlineKindAttr &inlineKindAttr)
void printInlineKindAttr(OpAsmPrinter &p, cir::InlineKindAttr inlineKindAttr)
static ParseResult parseSwitchFlatOpCases(OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues, SmallVectorImpl< Block * > &caseDestinations, SmallVectorImpl< llvm::SmallVector< OpAsmParser::UnresolvedOperand > > &caseOperands, SmallVectorImpl< llvm::SmallVector< Type > > &caseOperandTypes)
<cases> ::= [ (case (, case )* )?
void printGlobalAddressSpaceValue(mlir::AsmPrinter &printer, cir::GlobalOp op, mlir::ptr::MemorySpaceAttrInterface attr)
static void printCallCommon(mlir::Operation *op, mlir::FlatSymbolRefAttr calleeSym, mlir::Value indirectCallee, mlir::OpAsmPrinter &printer, bool isNothrow, cir::SideEffect sideEffect, ArrayAttr argAttrs, ArrayAttr resAttrs, mlir::Block *normalDest=nullptr, mlir::Block *unwindDest=nullptr)
static LogicalResult verifyCallCommInSymbolUses(mlir::Operation *op, SymbolTableCollection &symbolTable)
static LogicalResult ensureRegionTerm(OpAsmParser &parser, Region &region, SMLoc errLoc)
static ParseResult parseGlobalOpTypeAndInitialValue(OpAsmParser &parser, TypeAttr &typeAttr, Attribute &initialValueAttr, mlir::Region &ctorRegion, mlir::Region &dtorRegion)
void printIndirectBrOpSucessors(OpAsmPrinter &p, cir::IndirectBrOp op, Type flagType, SuccessorRange succs, OperandRangeRange succOperands, const TypeRangeRange &succOperandsTypes)
static OpFoldResult foldUnaryBitOp(mlir::Attribute inputAttr, llvm::function_ref< llvm::APInt(const llvm::APInt &)> func, bool poisonZero=false)
static llvm::StringRef getLinkageAttrNameString()
Returns the name used for the linkage attribute.
static RetTy parseOptionalCIRKeyword(AsmParser &parser, EnumTy defaultValue)
Parse an enum from the keyword, or default to the provided default value.
mlir::OptionalParseResult parseGlobalAddressSpaceValue(mlir::AsmParser &p, mlir::ptr::MemorySpaceAttrInterface &attr)
static void printSwitchFlatOpCases(OpAsmPrinter &p, cir::SwitchFlatOp op, Type flagType, mlir::ArrayAttr caseValues, SuccessorRange caseDestinations, OperandRangeRange caseOperands, const TypeRangeRange &caseOperandTypes)
static LogicalResult verifyProducedBy(Operation *op, Value operand, StringRef operandName)
static mlir::ParseResult parseTryCallDestinations(mlir::OpAsmParser &parser, mlir::OperationState &result)
static void printGlobalOpTypeAndInitialValue(OpAsmPrinter &p, cir::GlobalOp op, TypeAttr type, Attribute initAttr, mlir::Region &ctorRegion, mlir::Region &dtorRegion)
static ParseResult parseCIRKeyword(AsmParser &parser, RetTy &result)
Parse an enum from the keyword, return failure if the keyword is not found.
static Value tryFoldCastChain(cir::CastOp op)
static void printTryHandlerRegions(mlir::OpAsmPrinter &printer, cir::TryOp op, mlir::MutableArrayRef< mlir::Region > handlerRegions, mlir::ArrayAttr handlerTypes)
ParseResult parseIndirectBrOpSucessors(OpAsmParser &parser, Type &flagType, SmallVectorImpl< Block * > &succOperandBlocks, SmallVectorImpl< SmallVector< OpAsmParser::UnresolvedOperand > > &succOperands, SmallVectorImpl< SmallVector< Type > > &succOperandsTypes)
static bool omitRegionTerm(mlir::Region &r)
static mlir::ParseResult parseCopyTypes(mlir::OpAsmParser &parser, mlir::Type &srcType, mlir::Type &dstType)
static void printOmittedTerminatorRegion(mlir::OpAsmPrinter &printer, cir::ScopeOp &op, mlir::Region &region)
static ParseResult parseConstantValue(OpAsmParser &parser, mlir::Attribute &valueAttr)
static LogicalResult verifyArrayCtorDtor(Op op)
static mlir::LogicalResult verifyThrowOpImpl(ThrowOpTy op)
static LogicalResult checkConstantTypes(mlir::Operation *op, mlir::Type opType, mlir::Attribute attrType)
static mlir::ParseResult parseTryHandlerRegions(mlir::OpAsmParser &parser, llvm::SmallVectorImpl< std::unique_ptr< mlir::Region > > &handlerRegions, mlir::ArrayAttr &handlerTypes)
#define REGISTER_ENUM_TYPE(Ty)
static int parseOptionalKeywordAlternative(AsmParser &parser, ArrayRef< llvm::StringRef > keywords)
llvm::function_ref< void(mlir::OpBuilder &, mlir::Location)> BuilderCallbackRef
Definition CIRDialect.h:37
llvm::function_ref< void( mlir::OpBuilder &, mlir::Location, mlir::OperationState &)> BuilderOpStateCallbackRef
Definition CIRDialect.h:39
static std::optional< NonLoc > getIndex(ProgramStateRef State, const ElementRegion *ER, CharKind CK)
static Decl::Kind getKind(const Decl *D)
TokenType getType() const
Returns the token's type, e.g.
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a an optional score condition
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
void buildTerminatedBody(mlir::OpBuilder &builder, mlir::Location loc)
mlir::ptr::MemorySpaceAttrInterface normalizeDefaultAddressSpace(mlir::ptr::MemorySpaceAttrInterface addrSpace)
Normalize LangAddressSpace::Default to null (empty attribute).
const AstTypeMatcher< BuiltinType > builtinType
const internal::VariadicAllOfMatcher< Attr > attr
const AstTypeMatcher< RecordType > recordType
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Clean up any erroneous/redundant code in the given Ranges in Code.
Definition Format.cpp:4468
StringRef getName(const HeaderType T)
Definition HeaderFile.h:38
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
static bool memberFuncPtrCast()
static bool opCallCallConv()
static bool opScopeCleanupRegion()
static bool supportIFuncAttr()