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