clang 24.0.0git
CIRDialect.cpp
Go to the documentation of this file.
1//===- CIRDialect.cpp - MLIR CIR ops implementation -----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the CIR dialect and its operations.
10//
11//===----------------------------------------------------------------------===//
12
14
19
20#include "mlir/IR/Attributes.h"
21#include "mlir/IR/BuiltinOps.h"
22#include "mlir/IR/BuiltinTypes.h"
23#include "mlir/IR/DialectImplementation.h"
24#include "mlir/IR/PatternMatch.h"
25#include "mlir/IR/Value.h"
26#include "mlir/Interfaces/ControlFlowInterfaces.h"
27#include "mlir/Interfaces/FunctionImplementation.h"
28#include "mlir/Support/LLVM.h"
29
31#include "clang/CIR/Dialect/IR/CIROpsDialect.cpp.inc"
32#include "clang/CIR/Dialect/IR/CIROpsEnums.cpp.inc"
34#include "llvm/ADT/SetOperations.h"
35#include "llvm/ADT/SmallSet.h"
36#include "llvm/ADT/TypeSwitch.h"
37#include "llvm/Support/Casting.h"
38#include "llvm/Support/LogicalResult.h"
39
40#include "CIRDialectBytecode.h"
41#include "CIROpDefinitions.h"
42
43using namespace mlir;
44using namespace cir;
45
46//===----------------------------------------------------------------------===//
47// CIR Dialect
48//===----------------------------------------------------------------------===//
49namespace {
50struct CIROpAsmDialectInterface : public OpAsmDialectInterface {
51 using OpAsmDialectInterface::OpAsmDialectInterface;
52
53 AliasResult getAlias(Type type, raw_ostream &os) const final {
54 if (auto recordType = dyn_cast<cir::RecordType>(type)) {
55 StringAttr nameAttr = recordType.getName();
56 if (!nameAttr)
57 os << "rec_anon_" << recordType.getKindAsStr();
58 else
59 os << "rec_" << nameAttr.getValue();
60 return AliasResult::OverridableAlias;
61 }
62 if (auto intType = dyn_cast<cir::IntType>(type)) {
63 // We only provide alias for standard integer types (i.e. integer types
64 // whose width is a power of 2 and at least 8).
65 unsigned width = intType.getWidth();
66 if (width < 8 || !llvm::isPowerOf2_32(width))
67 return AliasResult::NoAlias;
68 os << intType.getAlias();
69 return AliasResult::OverridableAlias;
70 }
71 if (auto voidType = dyn_cast<cir::VoidType>(type)) {
72 os << voidType.getAlias();
73 return AliasResult::OverridableAlias;
74 }
75
76 return AliasResult::NoAlias;
77 }
78
79 AliasResult getAlias(Attribute attr, raw_ostream &os) const final {
80 if (auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr)) {
81 os << (boolAttr.getValue() ? "true" : "false");
82 return AliasResult::FinalAlias;
83 }
84 if (auto bitfield = mlir::dyn_cast<cir::BitfieldInfoAttr>(attr)) {
85 os << "bfi_" << bitfield.getName().str();
86 return AliasResult::FinalAlias;
87 }
88 if (auto dynCastInfoAttr = mlir::dyn_cast<cir::DynamicCastInfoAttr>(attr)) {
89 os << dynCastInfoAttr.getAlias();
90 return AliasResult::FinalAlias;
91 }
92 if (auto cmpThreeWayInfoAttr =
93 mlir::dyn_cast<cir::CmpThreeWayInfoAttr>(attr)) {
94 os << cmpThreeWayInfoAttr.getAlias();
95 return AliasResult::FinalAlias;
96 }
97 return AliasResult::NoAlias;
98 }
99};
100} // namespace
101
102void cir::CIRDialect::initialize() {
103 registerTypes();
104 registerAttributes();
105 registerCIRDialectOperations(this);
106 addInterfaces<CIROpAsmDialectInterface>();
108}
109
110Operation *cir::CIRDialect::materializeConstant(mlir::OpBuilder &builder,
111 mlir::Attribute value,
112 mlir::Type type,
113 mlir::Location loc) {
114 return cir::ConstantOp::create(builder, loc, type,
115 mlir::cast<mlir::TypedAttr>(value));
116}
117
118static bool isOpenCLVersionAttrName(StringRef attrName) {
119 return attrName == CIRDialect::getOpenCLVersionAttrName() ||
120 attrName == CIRDialect::getOpenCLCXXVersionAttrName() ||
121 attrName == CIRDialect::getOpenCLSPIRVersionAttrName();
122}
123
124static LogicalResult verifyOpenCLVersionAttrPlacement(Operation *op,
125 NamedAttribute attr) {
126 StringRef attrName = attr.getName().getValue();
127 if (isa<ModuleOp>(op))
128 return success();
129
130 return op->emitError() << attrName
131 << " attribute must be attached to a module";
132}
133
134static bool areOpenCLVersionsCompatible(cir::OpenCLVersionAttr openCLVersion,
135 cir::OpenCLVersionAttr cxxVersion) {
136 return (openCLVersion.getMajorVersion() == 2 &&
137 openCLVersion.getMinorVersion() == 0 &&
138 cxxVersion.getMajorVersion() == 1 &&
139 cxxVersion.getMinorVersion() == 0) ||
140 (openCLVersion.getMajorVersion() == 3 &&
141 openCLVersion.getMinorVersion() == 0 &&
142 cxxVersion.getMajorVersion() == 2021 &&
143 cxxVersion.getMinorVersion() == 0);
144}
145
146static LogicalResult verifyOpenCLCXXVersion(ModuleOp module,
147 cir::OpenCLVersionAttr cxxVersion) {
148 Attribute openCLAttr =
149 module->getAttr(CIRDialect::getOpenCLVersionAttrName());
150 if (!openCLAttr)
151 return module.emitError()
152 << "module attribute '" << CIRDialect::getOpenCLCXXVersionAttrName()
153 << "' requires the companion attribute '"
154 << CIRDialect::getOpenCLVersionAttrName() << "'";
155
156 auto openCLVersion = dyn_cast<cir::OpenCLVersionAttr>(openCLAttr);
157 if (!openCLVersion)
158 return success();
159
160 if (!areOpenCLVersionsCompatible(openCLVersion, cxxVersion))
161 return module.emitError("incompatible OpenCL and C++ for OpenCL versions");
162
163 return success();
164}
165
166static LogicalResult verifyOpenCLVersionAttr(Operation *op,
167 NamedAttribute attr) {
168 if (failed(verifyOpenCLVersionAttrPlacement(op, attr)))
169 return failure();
170
171 StringRef attrName = attr.getName().getValue();
172 auto version = dyn_cast<cir::OpenCLVersionAttr>(attr.getValue());
173 if (!version) {
174 return op->emitError() << "expected " << attrName
175 << " to be #cir.cl.version";
176 }
177
178 if (attrName == CIRDialect::getOpenCLCXXVersionAttrName())
179 return verifyOpenCLCXXVersion(cast<ModuleOp>(op), version);
180
181 return success();
182}
183
184LogicalResult cir::CIRDialect::verifyRegionArgAttribute(
185 Operation *op, unsigned /*regionIndex*/, unsigned /*argIndex*/,
186 NamedAttribute attr) {
187 if (!isOpenCLVersionAttrName(attr.getName().getValue()))
188 return success();
189
190 return verifyOpenCLVersionAttrPlacement(op, attr);
191}
192
193LogicalResult cir::CIRDialect::verifyRegionResultAttribute(
194 Operation *op, unsigned /*regionIndex*/, unsigned /*resultIndex*/,
195 NamedAttribute attr) {
196 if (!isOpenCLVersionAttrName(attr.getName().getValue()))
197 return success();
198
199 return verifyOpenCLVersionAttrPlacement(op, attr);
200}
201
202//===----------------------------------------------------------------------===//
203// Dialect attribute verification
204//===----------------------------------------------------------------------===//
205
206static LogicalResult verifyOffloadKind(mlir::ModuleOp module,
207 cir::OffloadKind expected) {
208 auto attr = module->getAttrOfType<cir::OffloadKindAttr>(
209 cir::CIRDialect::getOffloadKindAttrName());
210 if (!attr)
211 return module.emitOpError()
212 << "expects '" << cir::CIRDialect::getOffloadKindAttrName()
213 << "' offload kind attribute";
214 if (attr.getValue() != expected)
215 return module.emitOpError()
216 << "expects '" << cir::CIRDialect::getOffloadKindAttrName()
217 << "' value '" << cir::stringifyOffloadKind(expected) << "'";
218 return success();
219}
220
221// A module marked with `cir.offload.container` holds the host module followed
222// by one or more device modules, each tagged with `cir.offload.kind`. Keeping
223// the host module first gives later offload passes a simple convention for
224// finding the host side while iterating the remaining device modules.
225static LogicalResult verifyOffloadContainer(mlir::Operation *op) {
226 auto container = mlir::dyn_cast<mlir::ModuleOp>(op);
227 if (!container)
228 return op->emitOpError()
229 << "expects '" << cir::CIRDialect::getOffloadContainerAttrName()
230 << "' attribute to be attached to '"
231 << mlir::ModuleOp::getOperationName() << "'";
232
233 mlir::Block &body = *container.getBody();
234 if (body.empty())
235 return container.emitOpError()
236 << "expects host module as the first nested op";
237
238 auto host = mlir::dyn_cast<mlir::ModuleOp>(body.front());
239 if (!host)
240 return container.emitOpError()
241 << "expects host module as the first nested op";
242 if (failed(verifyOffloadKind(host, cir::OffloadKind::Host)))
243 return failure();
244
245 // At least one device module is required after the host module.
246 if (std::next(body.begin()) == body.end())
247 return container.emitOpError() << "expects at least one device module";
248
249 for (auto &op : llvm::drop_begin(body)) {
250 auto module = mlir::dyn_cast<mlir::ModuleOp>(op);
251 if (!module)
252 return container.emitOpError()
253 << "expects only nested builtin.module ops";
254 if (failed(verifyOffloadKind(module, cir::OffloadKind::Device)))
255 return failure();
256 }
257 return success();
258}
259
260LogicalResult
261cir::CIRDialect::verifyOperationAttribute(mlir::Operation *op,
262 mlir::NamedAttribute attr) {
263 llvm::StringRef attrName = attr.getName().getValue();
264 if (isOpenCLVersionAttrName(attrName))
265 return verifyOpenCLVersionAttr(op, attr);
266
267 if (attrName == getCXXABIAttrName()) {
268 if (!mlir::isa<mlir::ModuleOp>(op))
269 return op->emitOpError() << "expects '" << getCXXABIAttrName()
270 << "' attribute to be attached to '"
271 << mlir::ModuleOp::getOperationName() << "'";
272 auto abi = mlir::dyn_cast<mlir::StringAttr>(attr.getValue());
273 if (!abi)
274 return op->emitOpError()
275 << "expects '" << getCXXABIAttrName() << "' to be a string";
276
277 StringRef abival = abi.getValue();
278 if (!clang::TargetCXXABI::isABI(abival))
279 return op->emitOpError() << "unknown C++ ABI '" << abi.getValue() << "'";
280
282 if (auto triple = op->getAttrOfType<mlir::StringAttr>(getTripleAttrName()))
284 llvm::Triple(triple.getValue()), kind))
285 return op->emitOpError()
286 << "C++ ABI '" << abi.getValue()
287 << "' is not supported on target '" << triple.getValue() << "'";
288
289 return success();
290 }
291
292 if (attrName == getOffloadContainerAttrName()) {
293 if (!mlir::isa<mlir::UnitAttr>(attr.getValue()))
294 return op->emitOpError() << "expects '" << getOffloadContainerAttrName()
295 << "' to be a unit attribute";
296 return verifyOffloadContainer(op);
297 }
298
299 // The container verifier owns the structural contract between a container
300 // and the modules it holds. All this can add is that the kind attribute
301 // never lands on something that is not a module.
302 if (attrName == getOffloadKindAttrName() && !mlir::isa<mlir::ModuleOp>(op))
303 return op->emitOpError() << "expects '" << getOffloadKindAttrName()
304 << "' attribute to be attached to '"
305 << mlir::ModuleOp::getOperationName() << "'";
306
307 if (attrName == getModuleFramePointerAttrName()) {
308 if (!mlir::isa<mlir::ModuleOp>(op))
309 return op->emitOpError() << "expects '" << getModuleFramePointerAttrName()
310 << "' attribute to be attached to '"
311 << mlir::ModuleOp::getOperationName() << "'";
312 if (!mlir::isa<cir::FramePointerKindAttr>(attr.getValue()))
313 return op->emitOpError() << "expects '" << getModuleFramePointerAttrName()
314 << "' to be a #cir.frame_pointer attribute";
315 return success();
316 }
317
318 // LoweringPrepare uses this attribute directly as the fatbin global's
319 // initializer, so it must be a valid #cir.const_array payload for its type.
320 if (attrName == getCUDADeviceBinaryAttrName()) {
321 auto bytes = mlir::dyn_cast<mlir::StringAttr>(attr.getValue());
322 auto arrayTy =
323 bytes ? mlir::dyn_cast<cir::ArrayType>(bytes.getType()) : nullptr;
324 if (!arrayTy || arrayTy.getSize() != bytes.size())
325 return op->emitOpError()
326 << "expects '" << getCUDADeviceBinaryAttrName()
327 << "' to be a string typed as an array of its length";
328 return cir::ConstArrayAttr::verify([&] { return op->emitOpError(); },
329 arrayTy, bytes,
330 /*trailingZerosNum=*/0);
331 }
332
333 if (attrName == getTripleAttrName()) {
334 if (!mlir::isa<mlir::ModuleOp>(op))
335 return op->emitOpError()
336 << "expects '" << getTripleAttrName() << "' attribute to be "
337 << "attached to '" << mlir::ModuleOp::getOperationName() << "'";
338
339 auto tripleStr = mlir::dyn_cast<mlir::StringAttr>(attr.getValue());
340 if (!tripleStr)
341 return op->emitOpError() << "expects '" << getTripleAttrName() << "' to "
342 << "be a string";
343 llvm::Triple triple(tripleStr.getValue());
344 // "Validate" our triple by checking if it has a known architecture;
345 // although not all triples have a corresponding clang TargetInfo.
346 if (triple.getArch() == llvm::Triple::UnknownArch)
347 return op->emitOpError()
348 << "unknown triple '" << tripleStr.getValue() << "' in '"
349 << getTripleAttrName() << "' attribute";
350 }
351
352 if (attrName == getOptInfoAttrName()) {
353 if (!mlir::isa<mlir::ModuleOp>(op))
354 return op->emitOpError()
355 << "expects '" << getOptInfoAttrName() << "' attribute to be "
356 << "attached to '" << mlir::ModuleOp::getOperationName() << "'";
357
358 auto optInfo = mlir::dyn_cast<cir::OptInfoAttr>(attr.getValue());
359 // Checks whether or not OptInfoAttr is even parseable; opt info range
360 // sanity checks are done in OptInfoAttr::verify.
361 if (!optInfo)
362 return op->emitOpError()
363 << "malformed " << cir::CIRDialect::getOptInfoAttrName()
364 << " attribute";
365 }
366
367 return success();
368}
369
370//===----------------------------------------------------------------------===//
371// Helpers
372//===----------------------------------------------------------------------===//
373
374// Parses one of the keywords provided in the list `keywords` and returns the
375// position of the parsed keyword in the list. If none of the keywords from the
376// list is parsed, returns -1.
377static int parseOptionalKeywordAlternative(AsmParser &parser,
378 ArrayRef<llvm::StringRef> keywords) {
379 for (auto en : llvm::enumerate(keywords)) {
380 if (succeeded(parser.parseOptionalKeyword(en.value())))
381 return en.index();
382 }
383 return -1;
384}
385
386namespace {
387template <typename Ty> struct EnumTraits {};
388
389#define REGISTER_ENUM_TYPE(Ty) \
390 template <> struct EnumTraits<cir::Ty> { \
391 static llvm::StringRef stringify(cir::Ty value) { \
392 return stringify##Ty(value); \
393 } \
394 static unsigned getMaxEnumVal() { return cir::getMaxEnumValFor##Ty(); } \
395 }
396
397REGISTER_ENUM_TYPE(GlobalLinkageKind);
398REGISTER_ENUM_TYPE(VisibilityKind);
399REGISTER_ENUM_TYPE(CallingConv);
400} // namespace
401
402/// Parse an enum from the keyword, or default to the provided default value.
403/// The return type is the enum type by default, unless overriden with the
404/// second template argument.
405template <typename EnumTy, typename RetTy = EnumTy>
406static RetTy parseOptionalCIRKeyword(AsmParser &parser, EnumTy defaultValue) {
408 for (unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
409 names.push_back(EnumTraits<EnumTy>::stringify(static_cast<EnumTy>(i)));
410
411 int index = parseOptionalKeywordAlternative(parser, names);
412 if (index == -1)
413 return static_cast<RetTy>(defaultValue);
414 return static_cast<RetTy>(index);
415}
416
417/// Parse an enum from the keyword, return failure if the keyword is not found.
418template <typename EnumTy, typename RetTy = EnumTy>
419static ParseResult parseCIRKeyword(AsmParser &parser, RetTy &result) {
421 for (unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
422 names.push_back(EnumTraits<EnumTy>::stringify(static_cast<EnumTy>(i)));
423
424 int index = parseOptionalKeywordAlternative(parser, names);
425 if (index == -1)
426 return failure();
427 result = static_cast<RetTy>(index);
428 return success();
429}
430
431// Check if a region's termination omission is valid and, if so, creates and
432// inserts the omitted terminator into the region.
433static LogicalResult ensureRegionTerm(OpAsmParser &parser, Region &region,
434 SMLoc errLoc) {
435 Location eLoc = parser.getEncodedSourceLoc(parser.getCurrentLocation());
436 OpBuilder builder(parser.getBuilder().getContext());
437
438 // Insert empty block in case the region is empty to ensure the terminator
439 // will be inserted
440 if (region.empty())
441 builder.createBlock(&region);
442
443 Block &block = region.back();
444 // Region is properly terminated: nothing to do.
445 if (!block.empty() && block.back().hasTrait<OpTrait::IsTerminator>())
446 return success();
447
448 // Check for invalid terminator omissions.
449 if (!region.hasOneBlock())
450 return parser.emitError(errLoc,
451 "multi-block region must not omit terminator");
452
453 // Terminator was omitted correctly: recreate it.
454 builder.setInsertionPointToEnd(&block);
455 cir::YieldOp::create(builder, eLoc);
456 return success();
457}
458
459// True if the region's terminator should be omitted.
460static bool omitRegionTerm(mlir::Region &r) {
461 const auto singleNonEmptyBlock = r.hasOneBlock() && !r.back().empty();
462 const auto yieldsNothing = [&r]() {
463 auto y = dyn_cast<cir::YieldOp>(r.back().getTerminator());
464 return y && y.getArgs().empty();
465 };
466 return singleNonEmptyBlock && yieldsNothing();
467}
468
469// Verifies that the given operand is produced by an operation of type
470// ExpectedProducerOp.
471template <typename ExpectedProducerOp>
472static LogicalResult verifyProducedBy(Operation *op, Value operand,
473 StringRef operandName) {
474 Operation *producer = operand.getDefiningOp();
475 if (!producer || !isa<ExpectedProducerOp>(producer))
476 return op->emitOpError()
477 << "operand '" << operandName << "' must be produced by '"
478 << ExpectedProducerOp::getOperationName() << "'";
479 return success();
480}
481
482std::optional<llvm::Triple> cir::getTripleFromModule(mlir::ModuleOp mod) {
483 auto tripleAttr =
484 mod->getAttrOfType<mlir::StringAttr>(CIRDialect::getTripleAttrName());
485 if (!tripleAttr)
486 return std::nullopt;
487
488 // Verifying the validity of the triple attribute happens in
489 // cir::CIRDialect::verifyOperationAttribute; verifyOperationAttribute
490 // should error first if we have an invalid attribute.
491 return llvm::Triple{tripleAttr.getValue()};
492}
493
494//===----------------------------------------------------------------------===//
495// InlineKindAttr (FIXME: remove once FuncOp uses assembly format)
496//===----------------------------------------------------------------------===//
497
498ParseResult parseInlineKindAttr(OpAsmParser &parser,
499 cir::InlineKindAttr &inlineKindAttr) {
500 // Static list of possible inline kind keywords
501 static constexpr llvm::StringRef keywords[] = {"no_inline", "always_inline",
502 "inline_hint"};
503
504 // Parse the inline kind keyword (optional)
505 llvm::StringRef keyword;
506 if (parser.parseOptionalKeyword(&keyword, keywords).failed()) {
507 // Not an inline kind keyword, leave inlineKindAttr empty
508 return success();
509 }
510
511 // Parse the enum value from the keyword
512 auto inlineKindResult = ::cir::symbolizeEnum<::cir::InlineKind>(keyword);
513 if (!inlineKindResult) {
514 return parser.emitError(parser.getCurrentLocation(), "expected one of [")
515 << llvm::join(llvm::ArrayRef(keywords), ", ")
516 << "] for inlineKind, got: " << keyword;
517 }
518
519 inlineKindAttr =
520 ::cir::InlineKindAttr::get(parser.getContext(), *inlineKindResult);
521 return success();
522}
523
524void printInlineKindAttr(OpAsmPrinter &p, cir::InlineKindAttr inlineKindAttr) {
525 if (inlineKindAttr) {
526 p << " " << stringifyInlineKind(inlineKindAttr.getValue());
527 }
528}
529
530//===----------------------------------------------------------------------===//
531// CIR Custom Parsers/Printers
532//===----------------------------------------------------------------------===//
533
534mlir::ParseResult cir::parseOmittedTerminatorRegion(mlir::OpAsmParser &parser,
535 mlir::Region &region) {
536 auto regionLoc = parser.getCurrentLocation();
537 if (parser.parseRegion(region))
538 return failure();
539 if (ensureRegionTerm(parser, region, regionLoc).failed())
540 return failure();
541 return success();
542}
543
544void cir::printOmittedTerminatorRegion(mlir::OpAsmPrinter &printer,
545 cir::ScopeOp &op, mlir::Region &region) {
546 printer.printRegion(region,
547 /*printEntryBlockArgs=*/false,
548 /*printBlockTerminators=*/!omitRegionTerm(region));
549}
550
551//===----------------------------------------------------------------------===//
552// AllocaOp
553//===----------------------------------------------------------------------===//
554
555void cir::AllocaOp::build(mlir::OpBuilder &odsBuilder,
556 mlir::OperationState &odsState, mlir::Type addr,
557 llvm::StringRef name, mlir::IntegerAttr alignment) {
558 odsState.addAttribute(getNameAttrName(odsState.name),
559 odsBuilder.getStringAttr(name));
560 if (alignment) {
561 odsState.addAttribute(getAlignmentAttrName(odsState.name), alignment);
562 }
563 odsState.addTypes(addr);
564}
565
566cir::AllocaOp cir::getUnderlyingAlloca(mlir::Value addr) {
567 mlir::Value ptr = addr;
568 while (cir::CastOp castOp = ptr.getDefiningOp<cir::CastOp>()) {
569 if (!castOp.isAllocaPreservingCast())
570 break;
571 ptr = castOp.getSrc();
572 }
573 return ptr.getDefiningOp<cir::AllocaOp>();
574}
575
576//===----------------------------------------------------------------------===//
577// ArrayCtor & ArrayDtor
578//===----------------------------------------------------------------------===//
579
580template <typename Op> static LogicalResult verifyArrayCtorDtor(Op op) {
581 auto ptrTy = mlir::cast<cir::PointerType>(op.getAddr().getType());
582 mlir::Type pointeeTy = ptrTy.getPointee();
583
584 mlir::Block &body = op.getBody().front();
585 if (body.getNumArguments() != 1)
586 return op.emitOpError("body must have exactly one block argument");
587
588 auto expectedEltPtrTy =
589 mlir::dyn_cast<cir::PointerType>(body.getArgument(0).getType());
590 if (!expectedEltPtrTy)
591 return op.emitOpError("block argument must be a !cir.ptr type");
592
593 if (op.getNumElements()) {
594 auto recTy = mlir::dyn_cast<cir::RecordType>(pointeeTy);
595 if (!recTy)
596 return op.emitOpError(
597 "when 'num_elements' is present, 'addr' must be a pointer to a "
598 "!cir.struct or !cir.union type");
599
600 if (expectedEltPtrTy != ptrTy)
601 return op.emitOpError("when 'num_elements' is present, 'addr' type must "
602 "match the block argument type");
603 } else {
604 auto arrayTy = mlir::dyn_cast<cir::ArrayType>(pointeeTy);
605 if (!arrayTy)
606 return op.emitOpError(
607 "when 'num_elements' is absent, 'addr' must be a pointer to a "
608 "!cir.array type");
609
610 mlir::Type innerEltTy = arrayTy.getElementType();
611 while (auto nested = mlir::dyn_cast<cir::ArrayType>(innerEltTy))
612 innerEltTy = nested.getElementType();
613
614 auto recTy = mlir::dyn_cast<cir::RecordType>(innerEltTy);
615 if (!recTy)
616 return op.emitOpError("the block argument type must be a pointer to a "
617 "!cir.struct or !cir.union type");
618
619 if (expectedEltPtrTy.getPointee() != innerEltTy)
620 return op.emitOpError(
621 "block argument pointee type must match the innermost array "
622 "element type");
623
624 if (expectedEltPtrTy.getAddrSpace() != ptrTy.getAddrSpace())
625 return op.emitOpError(
626 "block argument address space must match the 'addr' address space");
627 }
628
629 return success();
630}
631
632LogicalResult cir::ArrayCtor::verify() {
633 if (failed(verifyArrayCtorDtor(*this)))
634 return failure();
635
636 mlir::Region &partialDtor = getPartialDtor();
637 if (!partialDtor.empty()) {
638 mlir::Block &dtorBlock = partialDtor.front();
639 if (dtorBlock.getNumArguments() != 1)
640 return emitOpError("partial_dtor must have exactly one block argument");
641
642 auto bodyArgTy = getBody().front().getArgument(0).getType();
643 if (dtorBlock.getArgument(0).getType() != bodyArgTy)
644 return emitOpError("partial_dtor block argument type must match "
645 "the body block argument type");
646 }
647 return success();
648}
649LogicalResult cir::ArrayDtor::verify() { return verifyArrayCtorDtor(*this); }
650
651//===----------------------------------------------------------------------===//
652// DeleteArrayOp
653//===----------------------------------------------------------------------===//
654
655LogicalResult cir::DeleteArrayOp::verify() {
656 if (getDtorMayThrow() && !getElementDtorAttr())
657 return emitOpError(
658 "'dtor_may_throw' requires an 'element_dtor' to be present");
659 return success();
660}
661
662//===----------------------------------------------------------------------===//
663// AssumeOp
664//===----------------------------------------------------------------------===//
665
666void cir::printAssumeBundle(OpAsmPrinter &p, cir::AssumeOp op,
667 cir::AssumeBundleKindAttr kindAttr,
668 OperandRange bundleArgs, TypeRange bundleArgTypes) {
669 cir::AssumeBundleKind kind = kindAttr.getValue();
670 if (kind == cir::AssumeBundleKind::None)
671 return;
672
673 p << " " << cir::stringifyAssumeBundleKind(kind);
674 if (bundleArgs.empty())
675 return;
676
677 p << "(";
678 p.printOperands(bundleArgs);
679 p << " : ";
680 llvm::interleaveComma(bundleArgTypes, p);
681 p << ")";
682}
683
684ParseResult cir::parseAssumeBundle(
685 OpAsmParser &p, cir::AssumeBundleKindAttr &bundleKindAttr,
687 llvm::SmallVector<mlir::Type, 1> &bundleArgTypes) {
688 StringRef keyword;
689 auto loc = p.getCurrentLocation();
690 if (failed(p.parseOptionalKeyword(&keyword))) {
691 bundleKindAttr = cir::AssumeBundleKindAttr::get(
692 p.getContext(), cir::AssumeBundleKind::None);
693 return success();
694 }
695
696 std::optional<cir::AssumeBundleKind> parsedKind =
697 cir::symbolizeAssumeBundleKind(keyword);
698 if (!parsedKind)
699 return p.emitError(loc, "unknown assume bundle kind '") << keyword << "'";
700
701 bundleKindAttr = cir::AssumeBundleKindAttr::get(p.getContext(), *parsedKind);
702
703 if (p.parseOptionalLParen())
704 return success();
705
706 if (p.parseOperandList(bundleArgs) || p.parseColon() ||
707 p.parseTypeList(bundleArgTypes) || p.parseRParen())
708 return failure();
709
710 return success();
711}
712
713LogicalResult cir::AssumeOp::verify() {
714 cir::AssumeBundleKind kind = getBundleKind();
715 size_t numArgs = getBundleArgs().size();
716
717 if (kind == cir::AssumeBundleKind::None) {
718 if (numArgs != 0)
719 return emitOpError("unexpected bundle operands for kind 'none'");
720 return success();
721 }
722
723 if (numArgs == 0)
724 return emitOpError("expected bundle operands for kind '")
725 << cir::stringifyAssumeBundleKind(kind) << "'";
726
727 switch (kind) {
728 case cir::AssumeBundleKind::Align:
729 if (numArgs != 2 && numArgs != 3)
730 return emitOpError("align bundle expects 2 or 3 operands");
731 break;
732 case cir::AssumeBundleKind::SeparateStorage:
733 if (numArgs != 2)
734 return emitOpError("separate_storage bundle expects 2 operands");
735 break;
736 case cir::AssumeBundleKind::Dereferenceable:
737 if (numArgs != 2)
738 return emitOpError("dereferenceable bundle expects 2 operands");
739 break;
740 default:
741 break;
742 }
743 return success();
744}
745
746//===----------------------------------------------------------------------===//
747// LocalInitOp
748//===----------------------------------------------------------------------===//
749
750LogicalResult
751cir::LocalInitOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
752 cir::GlobalOp global = getReferencedGlobal(symbolTable);
753 if (!global)
754 return emitOpError("'")
755 << getGlobalName() << "' does not reference a valid cir.global";
756
757 if (getTls() && !global.getTlsModel())
758 return emitOpError("access to global not marked thread local");
759
760 if (!global.getDynamicInitGuard().has_value())
761 return emitOpError("static_local attribute mismatch");
762
763 return success();
764}
765
766//===----------------------------------------------------------------------===//
767// RegisterExitDtorOp
768//===----------------------------------------------------------------------===//
769
770/// Returns true if \p op is nested in the ctor region of a cir.global or
771/// cir.local_init without crossing a cir.func or a cir.register_exit_dtor.
772static bool isInVarCtorRegion(mlir::Operation *op) {
773 for (mlir::Operation *parent = op->getParentOp(); parent;
774 parent = parent->getParentOp()) {
775 mlir::Region *ctorRegion = nullptr;
776 if (auto global = mlir::dyn_cast<cir::GlobalOp>(parent))
777 ctorRegion = &global.getCtorRegion();
778 else if (auto localInit = mlir::dyn_cast<cir::LocalInitOp>(parent))
779 ctorRegion = &localInit.getCtorRegion();
780 else if (mlir::isa<cir::FuncOp, cir::RegisterExitDtorOp>(parent))
781 return false;
782 if (ctorRegion)
783 return ctorRegion->isAncestor(op->getParentRegion());
784 }
785 return false;
786}
787
788LogicalResult cir::RegisterExitDtorOp::verify() {
789 mlir::Block &body = getBody().front();
790 if (body.without_terminator().empty())
791 return emitOpError("body must destroy the object");
792 if (body.getTerminator()->getNumOperands())
793 return emitOpError("body must not yield a value");
794 if (!isInVarCtorRegion(*this))
795 return emitOpError("must be in the ctor region of a cir.global or "
796 "cir.local_init");
797 return success();
798}
799
800LogicalResult
801cir::RegisterExitDtorOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
802 auto global = symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(
803 *this, getObjectAttr());
804 if (!global)
805 return emitOpError("'")
806 << getObject() << "' does not reference a valid cir.global";
807 if (!global.getCtorRegion().empty() || !global.getDtorRegion().empty())
808 return emitOpError("object must not have ctor or dtor regions");
809 return success();
810}
811
812//===----------------------------------------------------------------------===//
813// ConditionOp
814//===----------------------------------------------------------------------===//
815
816//===----------------------------------
817// BranchOpTerminatorInterface Methods
818//===----------------------------------
819
820void cir::ConditionOp::getSuccessorRegions(
821 ArrayRef<Attribute> operands, SmallVectorImpl<RegionSuccessor> &regions) {
822 // TODO(cir): The condition value may be folded to a constant, narrowing
823 // down its list of possible successors.
824
825 // Parent is a loop: condition may branch to the body, or on the false edge
826 // to the per-iteration cleanup region if present, otherwise to the parent op.
827 if (auto loopOp = dyn_cast<LoopOpInterface>(getOperation()->getParentOp())) {
828 regions.emplace_back(&loopOp.getBody());
829 if (mlir::Region *cleanup = loopOp.maybeGetCleanup())
830 regions.emplace_back(cleanup);
831 else
832 regions.emplace_back(getOperation());
833 return;
834 }
835
836 // Parent is an await: condition may branch to resume or suspend regions.
837 auto await = cast<AwaitOp>(getOperation()->getParentOp());
838 regions.emplace_back(&await.getResume());
839 regions.emplace_back(&await.getSuspend());
840}
841
842MutableOperandRange
843cir::ConditionOp::getMutableSuccessorOperands(RegionSuccessor point) {
844 // No values are yielded to the successor region.
845 return MutableOperandRange(getOperation(), 0, 0);
846}
847
848MutableOperandRange
849cir::ResumeOp::getMutableSuccessorOperands(RegionSuccessor point) {
850 // The eh_token operand is not modeled as forwarded to any successor.
851 return MutableOperandRange(getOperation(), 0, 0);
852}
853
854MutableOperandRange
855cir::CoroSuspendPoint::getMutableSuccessorOperands(RegionSuccessor point) {
856 // The condition operand is not forwarded to successor regions.
857 return MutableOperandRange(getOperation(), 0, 0);
858}
859
860LogicalResult cir::ConditionOp::verify() {
861 if (!isa<LoopOpInterface, AwaitOp>(getOperation()->getParentOp()))
862 return emitOpError("condition must be within a conditional region");
863 return success();
864}
865
866//===----------------------------------------------------------------------===//
867// WhileOp & ForOp
868//===----------------------------------------------------------------------===//
869
870template <typename LoopOpTy>
871static LogicalResult verifyLoopCleanup(LoopOpTy op) {
872 std::optional<cir::CleanupKind> cleanupKind = op.getCleanupKind();
873
874 // The cleanup kind attribute must be present exactly when a (non-empty)
875 // cleanup region is present.
876 if (cleanupKind.has_value() == op.getCleanup().empty())
877 return op.emitOpError("cleanup kind must be present if and only if the "
878 "cleanup region is non-empty");
879
880 // A loop's per-iteration cleanup runs on every normal exit edge (loop exit,
881 // end of iteration, break/continue), so an EH-only cleanup is meaningless.
882 // Only 'normal' (exceptions disabled) and 'all' (normal + EH unwind) apply.
883 if (cleanupKind == cir::CleanupKind::EH)
884 return op.emitOpError("loop cleanup kind must be 'normal' or 'all', "
885 "not 'eh'");
886
887 return success();
888}
889
890LogicalResult cir::WhileOp::verify() { return verifyLoopCleanup(*this); }
891
892LogicalResult cir::ForOp::verify() { return verifyLoopCleanup(*this); }
893
894//===----------------------------------------------------------------------===//
895// ConstantOp
896//===----------------------------------------------------------------------===//
897
898static LogicalResult checkConstantTypes(mlir::Operation *op, mlir::Type opType,
899 mlir::Attribute attrType) {
900 if (isa<cir::ConstPtrAttr>(attrType)) {
901 if (!mlir::isa<cir::PointerType>(opType))
902 return op->emitOpError(
903 "pointer constant initializing a non-pointer type");
904 return success();
905 }
906
907 if (isa<cir::DataMemberAttr, cir::DataMemberOffsetAttr, cir::MethodAttr>(
908 attrType)) {
909 // More detailed type verifications are already done in
910 // DataMemberAttr::verify or MethodAttr::verify. Don't need to repeat here.
911 return success();
912 }
913
914 if (isa<cir::ZeroAttr>(attrType)) {
915 if (isa<cir::RecordType, cir::ArrayType, cir::MatrixType, cir::VectorType,
916 cir::ComplexType>(opType))
917 return success();
918 return op->emitOpError(
919 "zero expects struct, array, vector, or complex type");
920 }
921
922 if (mlir::isa<cir::UndefAttr>(attrType)) {
923 if (!mlir::isa<cir::VoidType>(opType))
924 return success();
925 return op->emitOpError("undef expects non-void type");
926 }
927
928 if (mlir::isa<cir::BoolAttr>(attrType)) {
929 if (!mlir::isa<cir::BoolType>(opType))
930 return op->emitOpError("result type (")
931 << opType << ") must be '!cir.bool' for '" << attrType << "'";
932 return success();
933 }
934
935 if (mlir::isa<cir::IntAttr, cir::FPAttr>(attrType)) {
936 auto at = cast<TypedAttr>(attrType);
937 if (at.getType() != opType) {
938 return op->emitOpError("result type (")
939 << opType << ") does not match value type (" << at.getType()
940 << ")";
941 }
942 return success();
943 }
944
945 if (mlir::isa<cir::BlockAddrDiffAttr, cir::BlockAddrInfoAttr,
946 cir::ConstArrayAttr, cir::ConstVectorAttr,
947 cir::ConstComplexAttr, cir::ConstRecordAttr,
948 cir::GlobalOffsetAttr, cir::GlobalViewAttr, cir::PoisonAttr,
949 cir::TypeInfoAttr, cir::VTableAttr>(attrType))
950 return success();
951
952 assert(isa<TypedAttr>(attrType) && "What else could we be looking at here?");
953 return op->emitOpError("global with type ")
954 << cast<TypedAttr>(attrType).getType() << " not yet supported";
955}
956
957LogicalResult cir::ConstantOp::verify() {
958 // ODS already generates checks to make sure the result type is valid. We just
959 // need to additionally check that the value's attribute type is consistent
960 // with the result type.
961 return checkConstantTypes(getOperation(), getType(), getValue());
962}
963
964OpFoldResult cir::ConstantOp::fold(FoldAdaptor /*adaptor*/) {
965 return getValue();
966}
967
968//===----------------------------------------------------------------------===//
969// CastOp
970//===----------------------------------------------------------------------===//
971
972static bool isFloatingPointCastKind(cir::CastKind kind) {
973 switch (kind) {
974 case cir::CastKind::floating:
975 case cir::CastKind::int_to_float:
976 case cir::CastKind::float_to_int:
977 case cir::CastKind::float_to_bool:
978 case cir::CastKind::bool_to_float:
979 case cir::CastKind::float_to_complex:
980 case cir::CastKind::float_complex_to_real:
981 case cir::CastKind::float_complex_to_bool:
982 case cir::CastKind::float_complex:
983 case cir::CastKind::float_complex_to_int_complex:
984 case cir::CastKind::int_complex_to_float_complex:
985 return true;
986 default:
987 return false;
988 }
989}
990
991LogicalResult cir::CastOp::verify() {
992 mlir::Type resType = getType();
993 mlir::Type srcType = getSrc().getType();
994 cir::CastKind kind = getKind();
995
996 if (getFenvAttr() && !isFloatingPointCastKind(kind))
997 return emitOpError()
998 << "'fenv' is only valid for floating-point cast kinds";
999
1000 // Verify address space casts for pointer types. given that
1001 // casts for within a different address space are illegal.
1002 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
1003 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
1004 if (srcPtrTy && resPtrTy && (kind != cir::CastKind::address_space))
1005 if (srcPtrTy.getAddrSpace() != resPtrTy.getAddrSpace()) {
1006 return emitOpError() << "result type address space does not match the "
1007 "address space of the operand";
1008 }
1009
1010 auto srcVTy = mlir::dyn_cast<cir::VectorType>(srcType);
1011 auto resVTy = mlir::dyn_cast<cir::VectorType>(resType);
1012 if (srcVTy && resVTy) {
1013 if ((kind == cir::CastKind::int_to_float ||
1014 kind == cir::CastKind::float_to_int) &&
1015 srcVTy.getSize() != resVTy.getSize()) {
1016 return emitOpError()
1017 << "vector float-to-int and int-to-float casts require "
1018 "source and destination vectors to have the same number of "
1019 "elements";
1020 }
1021 // Use the element type of the vector to verify the cast kind. (Except for
1022 // bitcast, see below.)
1023 srcType = srcVTy.getElementType();
1024 resType = resVTy.getElementType();
1025 }
1026
1027 switch (kind) {
1028 case cir::CastKind::int_to_bool: {
1029 if (!mlir::isa<cir::BoolType>(resType))
1030 return emitOpError() << "requires !cir.bool type for result";
1031 if (!mlir::isa<cir::IntType>(srcType))
1032 return emitOpError() << "requires !cir.int type for source";
1033 return success();
1034 }
1035 case cir::CastKind::ptr_to_bool: {
1036 if (!mlir::isa<cir::BoolType>(resType))
1037 return emitOpError() << "requires !cir.bool type for result";
1038 if (!mlir::isa<cir::PointerType>(srcType))
1039 return emitOpError() << "requires !cir.ptr type for source";
1040 return success();
1041 }
1042 case cir::CastKind::integral: {
1043 if (!mlir::isa<cir::IntType>(resType))
1044 return emitOpError() << "requires !cir.int type for result";
1045 if (!mlir::isa<cir::IntType>(srcType))
1046 return emitOpError() << "requires !cir.int type for source";
1047 return success();
1048 }
1049 case cir::CastKind::array_to_ptrdecay: {
1050 const auto arrayPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
1051 const auto flatPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
1052 if (!arrayPtrTy || !flatPtrTy)
1053 return emitOpError() << "requires !cir.ptr type for source and result";
1054
1055 // TODO(CIR): Make sure the AddrSpace of both types are equals
1056 return success();
1057 }
1058 case cir::CastKind::bitcast: {
1059 // Handle the pointer types first.
1060 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
1061 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
1062
1063 if (srcPtrTy && resPtrTy) {
1064 return success();
1065 }
1066
1067 return success();
1068 }
1069 case cir::CastKind::floating: {
1070 if (!mlir::isa<cir::FPTypeInterface>(srcType) ||
1071 !mlir::isa<cir::FPTypeInterface>(resType))
1072 return emitOpError() << "requires !cir.float type for source and result";
1073 return success();
1074 }
1075 case cir::CastKind::float_to_int: {
1076 if (!mlir::isa<cir::FPTypeInterface>(srcType))
1077 return emitOpError() << "requires !cir.float type for source";
1078 if (!mlir::dyn_cast<cir::IntType>(resType))
1079 return emitOpError() << "requires !cir.int type for result";
1080 return success();
1081 }
1082 case cir::CastKind::int_to_ptr: {
1083 if (!mlir::dyn_cast<cir::IntType>(srcType))
1084 return emitOpError() << "requires !cir.int type for source";
1085 if (!mlir::dyn_cast<cir::PointerType>(resType))
1086 return emitOpError() << "requires !cir.ptr type for result";
1087 return success();
1088 }
1089 case cir::CastKind::ptr_to_int: {
1090 if (!mlir::dyn_cast<cir::PointerType>(srcType))
1091 return emitOpError() << "requires !cir.ptr type for source";
1092 if (!mlir::dyn_cast<cir::IntType>(resType))
1093 return emitOpError() << "requires !cir.int type for result";
1094 return success();
1095 }
1096 case cir::CastKind::float_to_bool: {
1097 if (!mlir::isa<cir::FPTypeInterface>(srcType))
1098 return emitOpError() << "requires !cir.float type for source";
1099 if (!mlir::isa<cir::BoolType>(resType))
1100 return emitOpError() << "requires !cir.bool type for result";
1101 return success();
1102 }
1103 case cir::CastKind::bool_to_int: {
1104 if (!mlir::isa<cir::BoolType>(srcType))
1105 return emitOpError() << "requires !cir.bool type for source";
1106 if (!mlir::isa<cir::IntType>(resType))
1107 return emitOpError() << "requires !cir.int type for result";
1108 return success();
1109 }
1110 case cir::CastKind::int_to_float: {
1111 if (!mlir::isa<cir::IntType>(srcType))
1112 return emitOpError() << "requires !cir.int type for source";
1113 if (!mlir::isa<cir::FPTypeInterface>(resType))
1114 return emitOpError() << "requires !cir.float type for result";
1115 return success();
1116 }
1117 case cir::CastKind::bool_to_float: {
1118 if (!mlir::isa<cir::BoolType>(srcType))
1119 return emitOpError() << "requires !cir.bool type for source";
1120 if (!mlir::isa<cir::FPTypeInterface>(resType))
1121 return emitOpError() << "requires !cir.float type for result";
1122 return success();
1123 }
1124 case cir::CastKind::address_space: {
1125 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
1126 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
1127 if (!srcPtrTy || !resPtrTy)
1128 return emitOpError() << "requires !cir.ptr type for source and result";
1129 if (srcPtrTy.getPointee() != resPtrTy.getPointee())
1130 return emitOpError() << "requires two types differ in addrspace only";
1131 return success();
1132 }
1133 case cir::CastKind::float_to_complex: {
1134 if (!mlir::isa<cir::FPTypeInterface>(srcType))
1135 return emitOpError() << "requires !cir.float type for source";
1136 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
1137 if (!resComplexTy)
1138 return emitOpError() << "requires !cir.complex type for result";
1139 if (srcType != resComplexTy.getElementType())
1140 return emitOpError() << "requires source type match result element type";
1141 return success();
1142 }
1143 case cir::CastKind::int_to_complex: {
1144 if (!mlir::isa<cir::IntType>(srcType))
1145 return emitOpError() << "requires !cir.int type for source";
1146 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
1147 if (!resComplexTy)
1148 return emitOpError() << "requires !cir.complex type for result";
1149 if (srcType != resComplexTy.getElementType())
1150 return emitOpError() << "requires source type match result element type";
1151 return success();
1152 }
1153 case cir::CastKind::float_complex_to_real: {
1154 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1155 if (!srcComplexTy)
1156 return emitOpError() << "requires !cir.complex type for source";
1157 if (!mlir::isa<cir::FPTypeInterface>(resType))
1158 return emitOpError() << "requires !cir.float type for result";
1159 if (srcComplexTy.getElementType() != resType)
1160 return emitOpError() << "requires source element type match result type";
1161 return success();
1162 }
1163 case cir::CastKind::int_complex_to_real: {
1164 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1165 if (!srcComplexTy)
1166 return emitOpError() << "requires !cir.complex type for source";
1167 if (!mlir::isa<cir::IntType>(resType))
1168 return emitOpError() << "requires !cir.int type for result";
1169 if (srcComplexTy.getElementType() != resType)
1170 return emitOpError() << "requires source element type match result type";
1171 return success();
1172 }
1173 case cir::CastKind::float_complex_to_bool: {
1174 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1175 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
1176 return emitOpError()
1177 << "requires floating point !cir.complex type for source";
1178 if (!mlir::isa<cir::BoolType>(resType))
1179 return emitOpError() << "requires !cir.bool type for result";
1180 return success();
1181 }
1182 case cir::CastKind::int_complex_to_bool: {
1183 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1184 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
1185 return emitOpError()
1186 << "requires floating point !cir.complex type for source";
1187 if (!mlir::isa<cir::BoolType>(resType))
1188 return emitOpError() << "requires !cir.bool type for result";
1189 return success();
1190 }
1191 case cir::CastKind::float_complex: {
1192 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1193 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
1194 return emitOpError()
1195 << "requires floating point !cir.complex type for source";
1196 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
1197 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
1198 return emitOpError()
1199 << "requires floating point !cir.complex type for result";
1200 return success();
1201 }
1202 case cir::CastKind::float_complex_to_int_complex: {
1203 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1204 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
1205 return emitOpError()
1206 << "requires floating point !cir.complex type for source";
1207 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
1208 if (!resComplexTy || !resComplexTy.isIntegerComplex())
1209 return emitOpError() << "requires integer !cir.complex type for result";
1210 return success();
1211 }
1212 case cir::CastKind::int_complex: {
1213 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1214 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
1215 return emitOpError() << "requires integer !cir.complex type for source";
1216 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
1217 if (!resComplexTy || !resComplexTy.isIntegerComplex())
1218 return emitOpError() << "requires integer !cir.complex type for result";
1219 return success();
1220 }
1221 case cir::CastKind::int_complex_to_float_complex: {
1222 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1223 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
1224 return emitOpError() << "requires integer !cir.complex type for source";
1225 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
1226 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
1227 return emitOpError()
1228 << "requires floating point !cir.complex type for result";
1229 return success();
1230 }
1231 case cir::CastKind::member_ptr_to_bool: {
1232 if (!mlir::isa<cir::DataMemberType, cir::MethodType>(srcType))
1233 return emitOpError()
1234 << "requires !cir.data_member or !cir.method type for source";
1235 if (!mlir::isa<cir::BoolType>(resType))
1236 return emitOpError() << "requires !cir.bool type for result";
1237 return success();
1238 }
1239 }
1240 llvm_unreachable("Unknown CastOp kind?");
1241}
1242
1243static bool isIntOrBoolCast(cir::CastOp op) {
1244 auto kind = op.getKind();
1245 return kind == cir::CastKind::bool_to_int ||
1246 kind == cir::CastKind::int_to_bool || kind == cir::CastKind::integral;
1247}
1248
1249static bool isCirFunctionPointerType(mlir::Type ty) {
1250 const auto ptrTy = mlir::dyn_cast<cir::PointerType>(ty);
1251 return ptrTy && mlir::isa<cir::FuncType>(ptrTy.getPointee());
1252}
1253
1254static Value tryFoldCastChain(cir::CastOp op) {
1255 cir::CastOp head = op, tail = op;
1256
1257 while (op) {
1258 if (!isIntOrBoolCast(op))
1259 break;
1260 head = op;
1261 op = head.getSrc().getDefiningOp<cir::CastOp>();
1262 }
1263
1264 if (head != tail) {
1265 // if bool_to_int -> ... -> int_to_bool: take the bool
1266 // as we had it was before all casts
1267 if (head.getKind() == cir::CastKind::bool_to_int &&
1268 tail.getKind() == cir::CastKind::int_to_bool)
1269 return head.getSrc();
1270
1271 // if int_to_bool -> ... -> int_to_bool: take the result
1272 // of the first one, as no other casts (and ext casts as well)
1273 // don't change the first result
1274 if (head.getKind() == cir::CastKind::int_to_bool &&
1275 tail.getKind() == cir::CastKind::int_to_bool)
1276 return head.getResult();
1277
1278 return {};
1279 }
1280
1281 // Bitcast round-trip on function pointers: T0 -> T1 -> T0 (e.g. no-proto
1282 // redeclaration vs. actual prototype). Restrict to function pointers so
1283 // other pointer bitcast chains are unchanged.
1284 if (tail.getKind() == cir::CastKind::bitcast) {
1285 auto *inner = tail.getSrc().getDefiningOp();
1286 if (inner && isCirFunctionPointerType(tail.getType())) {
1287 auto innerCast = mlir::dyn_cast<cir::CastOp>(inner);
1288 if (innerCast && innerCast.getKind() == cir::CastKind::bitcast &&
1289 innerCast.getSrc().getType() == tail.getType() &&
1290 innerCast.getType() == tail.getSrc().getType()) {
1291 return innerCast.getSrc();
1292 }
1293 }
1294 }
1295
1296 return {};
1297}
1298
1299OpFoldResult cir::CastOp::fold(FoldAdaptor adaptor) {
1300 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getSrc())) {
1301 // Propagate poison value
1302 return cir::PoisonAttr::get(getContext(), getType());
1303 }
1304
1305 // Propagate Undef value
1306 if (mlir::isa_and_present<cir::UndefAttr>(adaptor.getSrc()))
1307 return cir::UndefAttr::get(getType());
1308
1309 if (getSrc().getType() == getType()) {
1310 switch (getKind()) {
1311 case cir::CastKind::integral:
1312 case cir::CastKind::bitcast:
1313 case cir::CastKind::address_space:
1314 case cir::CastKind::float_complex:
1315 case cir::CastKind::int_complex: {
1316 return getSrc();
1317 }
1318 default:
1319 return {};
1320 }
1321 }
1322
1323 // Handle cases where a chain of casts cancel out.
1324 Value result = tryFoldCastChain(*this);
1325 if (result)
1326 return result;
1327
1328 // Handle simple constant casts.
1329 if (auto srcConst = getSrc().getDefiningOp<cir::ConstantOp>()) {
1330 switch (getKind()) {
1331 case cir::CastKind::integral: {
1332 mlir::Type srcTy = getSrc().getType();
1333 // Don't try to fold vector casts for now.
1334 assert(mlir::isa<cir::VectorType>(srcTy) ==
1335 mlir::isa<cir::VectorType>(getType()));
1336 if (mlir::isa<cir::VectorType>(srcTy))
1337 break;
1338
1339 auto srcIntTy = mlir::cast<cir::IntType>(srcTy);
1340 auto dstIntTy = mlir::cast<cir::IntType>(getType());
1341 auto constIntAttr = srcConst.getValueAttr<cir::IntAttr>();
1342 if (!constIntAttr)
1343 return {};
1344
1345 APInt srcValue = constIntAttr.getValue();
1346 APInt newVal = srcIntTy.isSigned()
1347 ? srcValue.sextOrTrunc(dstIntTy.getWidth())
1348 : srcValue.zextOrTrunc(dstIntTy.getWidth());
1349 return cir::IntAttr::get(dstIntTy, newVal);
1350 }
1351 default:
1352 break;
1353 }
1354 }
1355 return {};
1356}
1357
1358//===----------------------------------------------------------------------===//
1359// BuiltinIntCastOp
1360//===----------------------------------------------------------------------===//
1361
1362LogicalResult cir::BuiltinIntCastOp::verify() {
1363 mlir::Type srcType = getSrc().getType();
1364 mlir::Type resType = getType();
1365
1366 auto srcCirInt = mlir::dyn_cast<cir::IntType>(srcType);
1367 auto resCirInt = mlir::dyn_cast<cir::IntType>(resType);
1368
1369 // One side must be a CIR integer the other must be a builtin
1370 // integer or index type.
1371 if (static_cast<bool>(srcCirInt) == static_cast<bool>(resCirInt))
1372 return emitOpError()
1373 << "requires exactly one '!cir.int' operand or result; the other "
1374 "must be a builtin integer or 'index' type";
1375
1376 mlir::Type builtinType = srcCirInt ? resType : srcType;
1377 if (!mlir::isa<mlir::IntegerType, mlir::IndexType>(builtinType))
1378 return emitOpError() << "requires a builtin integer or 'index' type on the "
1379 "non-CIR side";
1380
1381 // The cast preserves bit width. 'index' has no fixed width, so only check
1382 // when the builtin side is a fixed-width integer.
1383 if (auto builtinInt = mlir::dyn_cast<mlir::IntegerType>(builtinType)) {
1384 cir::IntType cirInt = srcCirInt ? srcCirInt : resCirInt;
1385 if (cirInt.getWidth() != builtinInt.getWidth())
1386 return emitOpError()
1387 << "requires the CIR and builtin integer types to have the same "
1388 "width; use 'cir.cast' for width conversions";
1389 }
1390
1391 return success();
1392}
1393
1394OpFoldResult cir::BuiltinIntCastOp::fold(FoldAdaptor adaptor) {
1395 // Fold: builtin_int_cast(builtin_int_cast(x)) -> x
1396 // Inner source type must match the cast's result type.
1397 if (auto inner = getSrc().getDefiningOp<cir::BuiltinIntCastOp>())
1398 if (inner.getSrc().getType() == getType())
1399 return inner.getSrc();
1400 return {};
1401}
1402
1403//===----------------------------------------------------------------------===//
1404// CallOp
1405//===----------------------------------------------------------------------===//
1406
1407mlir::OperandRange cir::CallOp::getArgOperands() {
1408 if (isIndirect())
1409 return getArgs().drop_front(1);
1410 return getArgs();
1411}
1412
1413mlir::MutableOperandRange cir::CallOp::getArgOperandsMutable() {
1414 mlir::MutableOperandRange args = getArgsMutable();
1415 if (isIndirect())
1416 return args.slice(1, args.size() - 1);
1417 return args;
1418}
1419
1420mlir::Value cir::CallOp::getIndirectCall() {
1421 assert(isIndirect());
1422 return getOperand(0);
1423}
1424
1425/// Return the operand at index 'i'.
1426Value cir::CallOp::getArgOperand(unsigned i) {
1427 if (isIndirect())
1428 ++i;
1429 return getOperand(i);
1430}
1431
1432/// Return the number of operands.
1433unsigned cir::CallOp::getNumArgOperands() {
1434 if (isIndirect())
1435 return this->getOperation()->getNumOperands() - 1;
1436 return this->getOperation()->getNumOperands();
1437}
1438
1439static mlir::ParseResult
1440parseTryCallDestinations(mlir::OpAsmParser &parser,
1441 mlir::OperationState &result) {
1442 mlir::Block *normalDestSuccessor;
1443 if (parser.parseSuccessor(normalDestSuccessor))
1444 return mlir::failure();
1445
1446 if (parser.parseComma())
1447 return mlir::failure();
1448
1449 mlir::Block *unwindDestSuccessor;
1450 if (parser.parseSuccessor(unwindDestSuccessor))
1451 return mlir::failure();
1452
1453 result.addSuccessors(normalDestSuccessor);
1454 result.addSuccessors(unwindDestSuccessor);
1455 return mlir::success();
1456}
1457
1458/// Reject an attribute in an explicit attribute dictionary whose value is not
1459/// the attribute class expected for its name. Where an op declares the
1460/// attribute it is stored as a property, so a value of the wrong class would
1461/// be dropped without a diagnostic.
1462static ParseResult checkEffectAttrKinds(mlir::OpAsmParser &parser,
1463 llvm::SMLoc loc,
1464 const mlir::NamedAttrList &attrs) {
1465 if (mlir::Attribute effects =
1466 attrs.get(CIRDialect::getMemoryEffectsAttrName()))
1467 if (!mlir::isa<cir::MemoryEffectsAttr>(effects))
1468 return parser.emitError(loc, "attribute '")
1469 << CIRDialect::getMemoryEffectsAttrName()
1470 << "' must be a #cir.memory_effects attribute";
1471
1472 if (mlir::Attribute uwtable = attrs.get(CIRDialect::getUwtableAttrName()))
1473 if (!mlir::isa<cir::UnwindTableKindAttr>(uwtable))
1474 return parser.emitError(loc, "attribute '")
1475 << CIRDialect::getUwtableAttrName()
1476 << "' must be a #cir.uwtable attribute";
1477
1478 if (mlir::Attribute framePointer =
1479 attrs.get(CIRDialect::getFramePointerAttrName()))
1480 if (!mlir::isa<cir::FramePointerKindAttr>(framePointer))
1481 return parser.emitError(loc, "attribute '")
1482 << CIRDialect::getFramePointerAttrName()
1483 << "' must be a #cir.frame_pointer attribute";
1484
1485 for (llvm::StringRef name :
1486 {CIRDialect::getNoUnwindAttrName(), CIRDialect::getWillReturnAttrName(),
1487 CIRDialect::getMustProgressAttrName()})
1488 if (mlir::Attribute flag = attrs.get(name))
1489 if (!mlir::isa<mlir::UnitAttr>(flag))
1490 return parser.emitError(loc, "attribute '")
1491 << name << "' must be a unit attribute";
1492
1493 return mlir::success();
1494}
1495
1496static mlir::ParseResult parseCallCommon(mlir::OpAsmParser &parser,
1497 mlir::OperationState &result,
1498 bool hasDestinationBlocks = false) {
1500 llvm::SMLoc opsLoc;
1501 mlir::FlatSymbolRefAttr calleeAttr;
1502
1503 // If we cannot parse a string callee, it means this is an indirect call.
1504 if (!parser
1505 .parseOptionalAttribute(calleeAttr, CIRDialect::getCalleeAttrName(),
1506 result.attributes)
1507 .has_value()) {
1508 OpAsmParser::UnresolvedOperand indirectVal;
1509 // Do not resolve right now, since we need to figure out the type
1510 if (parser.parseOperand(indirectVal).failed())
1511 return failure();
1512 ops.push_back(indirectVal);
1513 }
1514
1515 if (parser.parseLParen())
1516 return mlir::failure();
1517
1518 opsLoc = parser.getCurrentLocation();
1519 if (parser.parseOperandList(ops))
1520 return mlir::failure();
1521 if (parser.parseRParen())
1522 return mlir::failure();
1523
1524 if (hasDestinationBlocks &&
1525 parseTryCallDestinations(parser, result).failed()) {
1526 return ::mlir::failure();
1527 }
1528
1529 if (parser.parseOptionalKeyword("cc").succeeded()) {
1530 cir::CallingConv callingConv;
1531 if (parser.parseLParen().failed())
1532 return failure();
1533 if (parseCIRKeyword<cir::CallingConv>(parser, callingConv).failed())
1534 return parser.emitError(parser.getCurrentLocation(),
1535 "unknown calling convention");
1536 if (parser.parseRParen().failed())
1537 return failure();
1538 result.addAttribute(
1539 CIRDialect::getCallingConvAttrName(),
1540 cir::CallingConvAttr::get(parser.getContext(), callingConv));
1541 }
1542
1543 if (parser.parseOptionalKeyword("musttail").succeeded())
1544 result.addAttribute(CIRDialect::getMustTailAttrName(),
1545 mlir::UnitAttr::get(parser.getContext()));
1546
1547 if (parser.parseOptionalKeyword("nothrow").succeeded())
1548 result.addAttribute(CIRDialect::getNoThrowAttrName(),
1549 mlir::UnitAttr::get(parser.getContext()));
1550
1551 if (parser.parseOptionalKeyword("nounwind").succeeded())
1552 result.addAttribute(CIRDialect::getNoUnwindAttrName(),
1553 mlir::UnitAttr::get(parser.getContext()));
1554
1555 if (parser.parseOptionalKeyword("willreturn").succeeded())
1556 result.addAttribute(CIRDialect::getWillReturnAttrName(),
1557 mlir::UnitAttr::get(parser.getContext()));
1558
1559 llvm::SMLoc attrsLoc = parser.getCurrentLocation();
1560 if (parser.parseOptionalAttrDict(result.attributes))
1561 return ::mlir::failure();
1562
1563 if (checkEffectAttrKinds(parser, attrsLoc, result.attributes).failed())
1564 return ::mlir::failure();
1565
1566 if (parser.parseColon())
1567 return ::mlir::failure();
1568
1569 SmallVector<Type> argTypes;
1571 SmallVector<Type> resultTypes;
1572 SmallVector<DictionaryAttr> resultAttrs;
1573 if (call_interface_impl::parseFunctionSignature(parser, argTypes, argAttrs,
1574 resultTypes, resultAttrs))
1575 return mlir::failure();
1576
1577 if (resultTypes.size() > 1 || resultAttrs.size() > 1)
1578 return parser.emitError(
1579 parser.getCurrentLocation(),
1580 "functions with multiple return types are not supported");
1581
1582 result.addTypes(resultTypes);
1583
1584 if (parser.resolveOperands(ops, argTypes, opsLoc, result.operands))
1585 return mlir::failure();
1586
1587 if (!resultAttrs.empty() && resultAttrs[0])
1588 result.addAttribute(
1589 CIRDialect::getResAttrsAttrName(),
1590 mlir::ArrayAttr::get(parser.getContext(), {resultAttrs[0]}));
1591
1592 // ArrayAttr requires a vector of 'Attribute', so we have to do the conversion
1593 // here into a separate collection.
1594 llvm::SmallVector<Attribute> convertedArgAttrs;
1595 bool argAttrsEmpty = true;
1596
1597 llvm::transform(argAttrs, std::back_inserter(convertedArgAttrs),
1598 [&](DictionaryAttr da) -> mlir::Attribute {
1599 if (da)
1600 argAttrsEmpty = false;
1601 return da;
1602 });
1603
1604 if (!argAttrsEmpty) {
1605 llvm::ArrayRef argAttrsRef = convertedArgAttrs;
1606 if (!calleeAttr) {
1607 // Fixup for indirect calls, which get an extra entry in the 'args' for
1608 // the indirect type, which doesn't get attributes.
1609 argAttrsRef = argAttrsRef.drop_front();
1610 }
1611 result.addAttribute(CIRDialect::getArgAttrsAttrName(),
1612 mlir::ArrayAttr::get(parser.getContext(), argAttrsRef));
1613 }
1614
1615 return mlir::success();
1616}
1617
1618static void printCallCommon(mlir::Operation *op,
1619 mlir::FlatSymbolRefAttr calleeSym,
1620 mlir::Value indirectCallee,
1621 mlir::OpAsmPrinter &printer, bool isNothrow,
1622 ArrayAttr argAttrs, ArrayAttr resAttrs,
1623 mlir::Block *normalDest = nullptr,
1624 mlir::Block *unwindDest = nullptr) {
1625 printer << ' ';
1626
1627 auto callLikeOp = mlir::cast<cir::CIRCallOpInterface>(op);
1628 auto ops = callLikeOp.getArgOperands();
1629
1630 if (calleeSym) {
1631 // Direct calls
1632 printer.printAttributeWithoutType(calleeSym);
1633 } else {
1634 // Indirect calls
1635 assert(indirectCallee);
1636 printer << indirectCallee;
1637 }
1638
1639 printer << "(" << ops << ")";
1640
1641 if (normalDest) {
1642 assert(unwindDest && "expected two successors");
1643 auto tryCall = cast<cir::TryCallOp>(op);
1644 printer << ' ' << tryCall.getNormalDest();
1645 printer << ",";
1646 printer << ' ';
1647 printer << tryCall.getUnwindDest();
1648 }
1649
1650 cir::CallingConv callingConv = callLikeOp.getCallingConv();
1651 if (callingConv != cir::CallingConv::C)
1652 printer << " cc(" << stringifyCallingConv(callingConv) << ")";
1653
1654 if (op->hasAttr(CIRDialect::getMustTailAttrName()))
1655 printer << " musttail";
1656
1657 if (isNothrow)
1658 printer << " nothrow";
1659
1660 if (op->hasAttr(CIRDialect::getNoUnwindAttrName()))
1661 printer << " nounwind";
1662
1663 if (op->hasAttr(CIRDialect::getWillReturnAttrName()))
1664 printer << " willreturn";
1665
1666 llvm::StringRef elidedAttrs[] = {
1667 CIRDialect::getCalleeAttrName(),
1668 CIRDialect::getCallingConvAttrName(),
1669 CIRDialect::getMustTailAttrName(),
1670 CIRDialect::getNoThrowAttrName(),
1671 CIRDialect::getNoUnwindAttrName(),
1672 CIRDialect::getWillReturnAttrName(),
1673 CIRDialect::getOperandSegmentSizesAttrName(),
1674 "res_attrs",
1675 "arg_attrs",
1676 };
1677 // TODO: Split inherent and discardable attribute printing instead of
1678 // materializing a single dictionary that mixes the two storage classes.
1680 for (mlir::NamedAttribute attr : op->getDiscardableAttrs())
1681 if (!llvm::is_contained(elidedAttrs, attr.getName()))
1682 attrs.push_back(attr);
1683 op->getName().walkInherentAttrs(op, [&](llvm::StringRef name,
1684 mlir::Attribute &attr) {
1685 if (!llvm::is_contained(elidedAttrs, name))
1686 attrs.emplace_back(mlir::StringAttr::get(op->getContext(), name), attr);
1687 });
1688 llvm::sort(attrs, [](mlir::NamedAttribute lhs, mlir::NamedAttribute rhs) {
1689 return lhs.getName().strref() < rhs.getName().strref();
1690 });
1691 printer.printOptionalAttrDict(attrs);
1692 printer << " : ";
1693 if (calleeSym || !argAttrs) {
1694 call_interface_impl::printFunctionSignature(
1695 printer, op->getOperands().getTypes(), argAttrs,
1696 /*isVariadic=*/false, op->getResultTypes(), resAttrs);
1697 } else {
1698 // indirect function calls use an 'arg' type for the type of its indirect
1699 // argument. However, we don't store a similar attribute collection. In
1700 // order to make `printFunctionSignature` have the attributes line up, we
1701 // have to make a 'shimmed' copy of the attributes that have a blank set of
1702 // attributes for the indirect argument.
1703 llvm::SmallVector<Attribute> shimmedArgAttrs;
1704 shimmedArgAttrs.push_back(mlir::DictionaryAttr::get(op->getContext(), {}));
1705 shimmedArgAttrs.append(argAttrs.begin(), argAttrs.end());
1706 call_interface_impl::printFunctionSignature(
1707 printer, op->getOperands().getTypes(),
1708 mlir::ArrayAttr::get(op->getContext(), shimmedArgAttrs),
1709 /*isVariadic=*/false, op->getResultTypes(), resAttrs);
1710 }
1711}
1712
1713mlir::ParseResult cir::CallOp::parse(mlir::OpAsmParser &parser,
1714 mlir::OperationState &result) {
1715 return parseCallCommon(parser, result);
1716}
1717
1718void cir::CallOp::print(mlir::OpAsmPrinter &p) {
1719 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() : nullptr;
1720 printCallCommon(*this, getCalleeAttr(), indirectCallee, p, getNothrow(),
1721 getArgAttrsAttr(), getResAttrsAttr());
1722}
1723
1724static LogicalResult
1725verifyCallCommInSymbolUses(mlir::Operation *op,
1726 SymbolTableCollection &symbolTable) {
1727 auto callIf = cast<cir::CIRCallOpInterface>(op);
1728
1729 // An indirect call is checked against the function type its callee pointer
1730 // points to, and a direct call against its callee's declaration.
1731 cir::FuncType fnType;
1732 bool hasPrototype = true;
1733 auto fnAttr =
1734 op->getAttrOfType<FlatSymbolRefAttr>(CIRDialect::getCalleeAttrName());
1735 if (!fnAttr) {
1736 if (op->getNumOperands() == 0)
1737 return op->emitOpError("indirect call requires a callee operand");
1738 mlir::Type calleeTy = callIf.getIndirectCall().getType();
1739 if (auto ptrTy = mlir::dyn_cast<cir::PointerType>(calleeTy))
1740 fnType = mlir::dyn_cast<cir::FuncType>(ptrTy.getPointee());
1741 if (!fnType)
1742 return op->emitOpError()
1743 << "indirect callee must be a pointer to a function, but has type "
1744 << calleeTy;
1745 } else {
1746 auto fn = symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(op, fnAttr);
1747 if (!fn)
1748 return op->emitOpError() << "'" << fnAttr.getValue()
1749 << "' does not reference a valid function";
1750 fnType = fn.getFunctionType();
1751 hasPrototype = !fn.getNoProto();
1752 }
1753
1754 // Verify that the operand and result types match the callee. Operands are
1755 // not checked for a direct call to a function declared no_proto.
1756 if (hasPrototype) {
1757 unsigned numCallOperands = callIf.getNumArgOperands();
1758 unsigned numFnOpOperands = fnType.getNumInputs();
1759
1760 if (!fnType.isVarArg() && numCallOperands != numFnOpOperands)
1761 return op->emitOpError("incorrect number of operands for callee");
1762 if (fnType.isVarArg() && numCallOperands < numFnOpOperands)
1763 return op->emitOpError("too few operands for callee");
1764
1765 for (unsigned i = 0, e = numFnOpOperands; i != e; ++i)
1766 if (callIf.getArgOperand(i).getType() != fnType.getInput(i))
1767 return op->emitOpError("operand type mismatch: expected operand type ")
1768 << fnType.getInput(i) << ", but provided "
1769 << callIf.getArgOperand(i).getType() << " for operand number "
1770 << i;
1771 }
1772
1774
1775 // Void function must not return any results.
1776 if (fnType.hasVoidReturn() && op->getNumResults() != 0)
1777 return op->emitOpError("callee returns void but call has results");
1778
1779 // Non-void function calls must return exactly one result.
1780 if (!fnType.hasVoidReturn() && op->getNumResults() != 1)
1781 return op->emitOpError("incorrect number of results for callee");
1782
1783 // Parent function and return value types must match.
1784 if (!fnType.hasVoidReturn() &&
1785 op->getResultTypes().front() != fnType.getReturnType()) {
1786 return op->emitOpError("result type mismatch: expected ")
1787 << fnType.getReturnType() << ", but provided "
1788 << op->getResult(0).getType();
1789 }
1790
1791 return mlir::success();
1792}
1793
1794LogicalResult
1795cir::CallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1796 return verifyCallCommInSymbolUses(*this, symbolTable);
1797}
1798
1799//===----------------------------------------------------------------------===//
1800// TryCallOp
1801//===----------------------------------------------------------------------===//
1802
1803mlir::OperandRange cir::TryCallOp::getArgOperands() {
1804 if (isIndirect())
1805 return getArgs().drop_front(1);
1806 return getArgs();
1807}
1808
1809mlir::MutableOperandRange cir::TryCallOp::getArgOperandsMutable() {
1810 mlir::MutableOperandRange args = getArgsMutable();
1811 if (isIndirect())
1812 return args.slice(1, args.size() - 1);
1813 return args;
1814}
1815
1816mlir::Value cir::TryCallOp::getIndirectCall() {
1817 assert(isIndirect());
1818 return getOperand(0);
1819}
1820
1821/// Return the operand at index 'i'.
1822Value cir::TryCallOp::getArgOperand(unsigned i) {
1823 if (isIndirect())
1824 ++i;
1825 return getOperand(i);
1826}
1827
1828/// Return the number of operands.
1829unsigned cir::TryCallOp::getNumArgOperands() {
1830 if (isIndirect())
1831 return this->getOperation()->getNumOperands() - 1;
1832 return this->getOperation()->getNumOperands();
1833}
1834
1835LogicalResult
1836cir::TryCallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1837 return verifyCallCommInSymbolUses(*this, symbolTable);
1838}
1839
1840mlir::ParseResult cir::TryCallOp::parse(mlir::OpAsmParser &parser,
1841 mlir::OperationState &result) {
1842 return parseCallCommon(parser, result, /*hasDestinationBlocks=*/true);
1843}
1844
1845void cir::TryCallOp::print(::mlir::OpAsmPrinter &p) {
1846 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() : nullptr;
1847 printCallCommon(*this, getCalleeAttr(), indirectCallee, p, getNothrow(),
1848 getArgAttrsAttr(), getResAttrsAttr(), getNormalDest(),
1849 getUnwindDest());
1850}
1851
1852//===----------------------------------------------------------------------===//
1853// ReturnOp
1854//===----------------------------------------------------------------------===//
1855
1856static mlir::LogicalResult checkReturnAndFunction(cir::ReturnOp op,
1857 cir::FuncOp function) {
1858 // ReturnOps currently only have a single optional operand.
1859 if (op.getNumOperands() > 1)
1860 return op.emitOpError() << "expects at most 1 return operand";
1861
1862 // Ensure returned type matches the function signature.
1863 auto expectedTy = function.getFunctionType().getReturnType();
1864 auto actualTy =
1865 (op.getNumOperands() == 0 ? cir::VoidType::get(op.getContext())
1866 : op.getOperand(0).getType());
1867 if (actualTy != expectedTy)
1868 return op.emitOpError() << "returns " << actualTy
1869 << " but enclosing function returns " << expectedTy;
1870
1871 return mlir::success();
1872}
1873
1874mlir::LogicalResult cir::ReturnOp::verify() {
1875 // Returns can be present in multiple different scopes, get the
1876 // wrapping function and start from there.
1877 auto *fnOp = getOperation()->getParentOp();
1878 while (!isa<cir::FuncOp>(fnOp))
1879 fnOp = fnOp->getParentOp();
1880
1881 // Make sure return types match function return type.
1882 if (checkReturnAndFunction(*this, cast<cir::FuncOp>(fnOp)).failed())
1883 return failure();
1884
1885 return success();
1886}
1887
1888//===----------------------------------------------------------------------===//
1889// IfOp
1890//===----------------------------------------------------------------------===//
1891
1892ParseResult cir::IfOp::parse(OpAsmParser &parser, OperationState &result) {
1893 // create the regions for 'then'.
1894 result.regions.reserve(2);
1895 Region *thenRegion = result.addRegion();
1896 Region *elseRegion = result.addRegion();
1897
1898 mlir::Builder &builder = parser.getBuilder();
1899 OpAsmParser::UnresolvedOperand cond;
1900 Type boolType = cir::BoolType::get(builder.getContext());
1901
1902 if (parser.parseOperand(cond) ||
1903 parser.resolveOperand(cond, boolType, result.operands))
1904 return failure();
1905
1906 // Parse 'then' region.
1907 mlir::SMLoc parseThenLoc = parser.getCurrentLocation();
1908 if (parser.parseRegion(*thenRegion, /*arguments=*/{}, /*argTypes=*/{}))
1909 return failure();
1910
1911 if (ensureRegionTerm(parser, *thenRegion, parseThenLoc).failed())
1912 return failure();
1913
1914 // If we find an 'else' keyword, parse the 'else' region.
1915 if (!parser.parseOptionalKeyword("else")) {
1916 mlir::SMLoc parseElseLoc = parser.getCurrentLocation();
1917 if (parser.parseRegion(*elseRegion, /*arguments=*/{}, /*argTypes=*/{}))
1918 return failure();
1919 if (ensureRegionTerm(parser, *elseRegion, parseElseLoc).failed())
1920 return failure();
1921 }
1922
1923 // Parse the optional attribute list.
1924 if (parser.parseOptionalAttrDict(result.attributes))
1925 return failure();
1926 return success();
1927}
1928
1929void cir::IfOp::print(OpAsmPrinter &p) {
1930 p << " " << getCondition() << " ";
1931 mlir::Region &thenRegion = this->getThenRegion();
1932 p.printRegion(thenRegion,
1933 /*printEntryBlockArgs=*/false,
1934 /*printBlockTerminators=*/!omitRegionTerm(thenRegion));
1935
1936 // Print the 'else' regions if it exists and has a block.
1937 mlir::Region &elseRegion = this->getElseRegion();
1938 if (!elseRegion.empty()) {
1939 p << " else ";
1940 p.printRegion(elseRegion,
1941 /*printEntryBlockArgs=*/false,
1942 /*printBlockTerminators=*/!omitRegionTerm(elseRegion));
1943 }
1944
1945 p.printOptionalAttrDict(
1946 getOperation()->getDiscardableAttrDictionary().getValue());
1947}
1948
1949/// Default callback for IfOp builders.
1950void cir::buildTerminatedBody(OpBuilder &builder, Location loc) {
1951 // add cir.yield to end of the block
1952 cir::YieldOp::create(builder, loc);
1953}
1954
1955/// Given the region at `index`, or the parent operation if `index` is None,
1956/// return the successor regions. These are the regions that may be selected
1957/// during the flow of control. `operands` is a set of optional attributes that
1958/// correspond to a constant value for each operand, or null if that operand is
1959/// not a constant.
1960void cir::IfOp::getSuccessorRegions(mlir::RegionBranchPoint point,
1961 SmallVectorImpl<RegionSuccessor> &regions) {
1962 // The `then` and the `else` region branch back to the parent operation.
1963 if (!point.isParent()) {
1964 regions.emplace_back(getOperation());
1965 return;
1966 }
1967
1968 // Don't consider the else region if it is empty.
1969 Region *elseRegion = &this->getElseRegion();
1970 if (elseRegion->empty())
1971 elseRegion = nullptr;
1972
1973 // If the condition isn't constant, both regions may be executed.
1974 regions.push_back(RegionSuccessor(&getThenRegion()));
1975 if (elseRegion)
1976 regions.push_back(RegionSuccessor(elseRegion));
1977 else
1978 regions.emplace_back(getOperation());
1979}
1980
1981void cir::IfOp::build(OpBuilder &builder, OperationState &result, Value cond,
1982 bool withElseRegion, BuilderCallbackRef thenBuilder,
1983 BuilderCallbackRef elseBuilder) {
1984 assert(thenBuilder && "the builder callback for 'then' must be present");
1985 result.addOperands(cond);
1986
1987 OpBuilder::InsertionGuard guard(builder);
1988 Region *thenRegion = result.addRegion();
1989 builder.createBlock(thenRegion);
1990 thenBuilder(builder, result.location);
1991
1992 Region *elseRegion = result.addRegion();
1993 if (!withElseRegion)
1994 return;
1995
1996 builder.createBlock(elseRegion);
1997 elseBuilder(builder, result.location);
1998}
1999
2000//===----------------------------------------------------------------------===//
2001// ScopeOp
2002//===----------------------------------------------------------------------===//
2003
2004void cir::ScopeOp::build(
2005 OpBuilder &builder, OperationState &result,
2006 function_ref<void(OpBuilder &, Type &, Location)> scopeBuilder) {
2007 assert(scopeBuilder && "the builder callback for 'then' must be present");
2008
2009 OpBuilder::InsertionGuard guard(builder);
2010 Region *scopeRegion = result.addRegion();
2011 builder.createBlock(scopeRegion);
2013
2014 mlir::Type yieldTy;
2015 scopeBuilder(builder, yieldTy, result.location);
2016
2017 if (yieldTy)
2018 result.addTypes(TypeRange{yieldTy});
2019}
2020
2021void cir::ScopeOp::build(
2022 OpBuilder &builder, OperationState &result,
2023 function_ref<void(OpBuilder &, Location)> scopeBuilder) {
2024 assert(scopeBuilder && "the builder callback for 'then' must be present");
2025 OpBuilder::InsertionGuard guard(builder);
2026 Region *scopeRegion = result.addRegion();
2027 builder.createBlock(scopeRegion);
2029 scopeBuilder(builder, result.location);
2030}
2031
2032LogicalResult cir::ScopeOp::verify() {
2033 if (getRegion().empty()) {
2034 return emitOpError() << "cir.scope must not be empty since it should "
2035 "include at least an implicit cir.yield ";
2036 }
2037
2038 mlir::Block &lastBlock = getRegion().back();
2039 if (lastBlock.empty() || !lastBlock.mightHaveTerminator() ||
2040 !lastBlock.getTerminator()->hasTrait<OpTrait::IsTerminator>())
2041 return emitOpError() << "last block of cir.scope must be terminated";
2042 return success();
2043}
2044
2045LogicalResult cir::ScopeOp::fold(FoldAdaptor /*adaptor*/,
2046 SmallVectorImpl<OpFoldResult> &results) {
2047 // Only fold "trivial" scopes: a single block containing only a `cir.yield`.
2048 if (!getRegion().hasOneBlock())
2049 return failure();
2050 Block &block = getRegion().front();
2051 if (block.getOperations().size() != 1)
2052 return failure();
2053
2054 auto yield = dyn_cast<cir::YieldOp>(block.front());
2055 if (!yield)
2056 return failure();
2057
2058 // Only fold when the scope produces a value.
2059 if (getNumResults() != 1 || yield.getNumOperands() != 1)
2060 return failure();
2061
2062 results.push_back(yield.getOperand(0));
2063 return success();
2064}
2065
2066//===----------------------------------------------------------------------===//
2067// CleanupScopeOp
2068//===----------------------------------------------------------------------===//
2069
2070static bool isRedundantBeforeReturn(mlir::Region &cleanupRegion) {
2071 for (mlir::Block &block : cleanupRegion) {
2072 for (mlir::Operation &op : block) {
2073 if (isa<cir::YieldOp, cir::LifetimeEndOp, cir::StackRestoreOp>(op))
2074 continue;
2075 // The stack restore reloads the pointer saved before the VLA.
2076 auto loadOp = dyn_cast<cir::LoadOp>(op);
2077 if (loadOp && loadOp.getResult().hasOneUse() &&
2078 isa<cir::StackRestoreOp>(*loadOp.getResult().getUsers().begin()))
2079 continue;
2080 return false;
2081 }
2082 }
2083 return true;
2084}
2085
2086LogicalResult cir::CleanupScopeOp::verify() {
2087 // If the cleanup contains a musttail call, it must be a cleanup that can be
2088 // skipped on return (such as a lifetime end or a stack restore). Other
2089 // cleanups must never contain musttail calls.
2090 cir::CallOp mustTailCall;
2091 getBodyRegion().walk([&](cir::CallOp callOp) {
2092 if (!callOp.getMusttail())
2093 return WalkResult::advance();
2094 mustTailCall = callOp;
2095 return WalkResult::interrupt();
2096 });
2097 if (!mustTailCall)
2098 return success();
2099
2100 if (isRedundantBeforeReturn(getCleanupRegion()))
2101 return success();
2102
2103 InFlightDiagnostic diag =
2104 emitOpError("cleanup is not redundant before a return, so it cannot be "
2105 "skipped by a musttail call");
2106 diag.attachNote(mustTailCall.getLoc()) << "musttail call is here";
2107 return diag;
2108}
2109
2110void cir::CleanupScopeOp::getSuccessorRegions(
2111 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &regions) {
2112 // The cleanup can also run from the middle of the body, on an unwind out of
2113 // a call or on a cir.return, cir.break, cir.continue or cir.goto. None of
2114 // these is a branch point, so the cleanup region is a successor of the
2115 // parent and of every body exit to stand in for them.
2116 if (point.isParent()) {
2117 regions.reserve(regions.size() + 2);
2118 regions.emplace_back(&getBodyRegion());
2119 regions.emplace_back(&getCleanupRegion());
2120 return;
2121 }
2122
2123 mlir::Operation *term = point.getTerminatorPredecessorOrNull();
2124 if (term->getParentRegion() == &getCleanupRegion()) {
2125 regions.emplace_back(getOperation());
2126 return;
2127 }
2128
2129 regions.emplace_back(&getCleanupRegion());
2130
2131 // cir.resume unwinds out of the body, and every other terminator is a
2132 // normal exit. An exit that the cleanup kind does not cover can also leave
2133 // the operation directly.
2134 cir::CleanupKindAttr kind = getCleanupKindAttr();
2135 if (isa<cir::ResumeOp>(term) ? !kind.isEH() : !kind.isNormal())
2136 regions.emplace_back(getOperation());
2137}
2138
2139LogicalResult cir::CleanupScopeOp::canonicalize(CleanupScopeOp op,
2140 PatternRewriter &rewriter) {
2141 auto isRegionTrivial = [](Region &region) {
2142 assert(!region.empty() && "CleanupScopeOp regions must not be empty");
2143 if (!region.hasOneBlock())
2144 return false;
2145 Block &block = llvm::getSingleElement(region);
2146 return llvm::hasSingleElement(block) &&
2147 isa<cir::YieldOp>(llvm::getSingleElement(block));
2148 };
2149
2150 Region &body = op.getBodyRegion();
2151 Region &cleanup = op.getCleanupRegion();
2152
2153 // An EH-only cleanup scope with an empty body can never trigger its cleanup
2154 // region — there are no operations in the body that could throw. Erase it.
2155 if (op.getCleanupKind() == CleanupKind::EH && isRegionTrivial(body)) {
2156 rewriter.eraseOp(op);
2157 return success();
2158 }
2159
2160 // A cleanup scope with a trivial cleanup region has no cleanup to perform.
2161 // Inline the body into the parent block and erase the scope.
2162 if (!isRegionTrivial(cleanup) || !body.hasOneBlock())
2163 return failure();
2164
2165 Block &bodyBlock = body.front();
2166 if (!isa<cir::YieldOp>(bodyBlock.getTerminator()))
2167 return failure();
2168
2169 Operation *yield = bodyBlock.getTerminator();
2170 rewriter.inlineBlockBefore(&bodyBlock, op);
2171 rewriter.eraseOp(yield);
2172 rewriter.eraseOp(op);
2173 return success();
2174}
2175
2176void cir::CleanupScopeOp::build(
2177 OpBuilder &builder, OperationState &result, CleanupKind cleanupKind,
2178 function_ref<void(OpBuilder &, Location)> bodyBuilder,
2179 function_ref<void(OpBuilder &, Location)> cleanupBuilder) {
2180 result.addAttribute(getCleanupKindAttrName(result.name),
2181 CleanupKindAttr::get(builder.getContext(), cleanupKind));
2182
2183 OpBuilder::InsertionGuard guard(builder);
2184
2185 // Build body region.
2186 Region *bodyRegion = result.addRegion();
2187 builder.createBlock(bodyRegion);
2188 if (bodyBuilder)
2189 bodyBuilder(builder, result.location);
2190
2191 // Build cleanup region.
2192 Region *cleanupRegion = result.addRegion();
2193 builder.createBlock(cleanupRegion);
2194 if (cleanupBuilder)
2195 cleanupBuilder(builder, result.location);
2196}
2197
2198//===----------------------------------------------------------------------===//
2199// BrOp
2200//===----------------------------------------------------------------------===//
2201
2202/// Merges blocks connected by a unique unconditional branch.
2203///
2204/// ^bb0: ^bb0:
2205/// ... ...
2206/// cir.br ^bb1 => ...
2207/// ^bb1: cir.return
2208/// ...
2209/// cir.return
2210LogicalResult cir::BrOp::canonicalize(BrOp op, PatternRewriter &rewriter) {
2211 Block *src = op->getBlock();
2212 Block *dst = op.getDest();
2213
2214 // Do not fold self-loops.
2215 if (src == dst)
2216 return failure();
2217
2218 // Only merge when this is the unique edge between the blocks.
2219 if (src->getNumSuccessors() != 1 || dst->getSinglePredecessor() != src)
2220 return failure();
2221
2222 // Don't merge blocks that start with LabelOp or IndirectBrOp.
2223 // This is to avoid merging blocks that have an indirect predecessor.
2224 if (isa<cir::LabelOp, cir::IndirectBrOp>(dst->front()))
2225 return failure();
2226
2227 // An operand that is an argument of the destination itself (possible in an
2228 // unreachable cycle) would be replaced by itself, leaving its other uses
2229 // dangling once the destination is erased.
2230 if (llvm::any_of(op.getDestOperands(), [&](Value operand) {
2231 auto arg = dyn_cast<BlockArgument>(operand);
2232 return arg && arg.getOwner() == dst;
2233 }))
2234 return failure();
2235
2236 // Copy the operands out: erasing the branch frees its operand storage.
2237 SmallVector<Value> operands(op.getDestOperands());
2238 rewriter.eraseOp(op);
2239 rewriter.mergeBlocks(dst, src, operands);
2240 return success();
2241}
2242
2243mlir::SuccessorOperands cir::BrOp::getSuccessorOperands(unsigned index) {
2244 assert(index == 0 && "invalid successor index");
2245 return mlir::SuccessorOperands(getDestOperandsMutable());
2246}
2247
2248Block *cir::BrOp::getSuccessorForOperands(ArrayRef<Attribute>) {
2249 return getDest();
2250}
2251
2252//===----------------------------------------------------------------------===//
2253// IndirectBrCondOp
2254//===----------------------------------------------------------------------===//
2255
2256mlir::SuccessorOperands
2257cir::IndirectBrOp::getSuccessorOperands(unsigned index) {
2258 assert(index < getNumSuccessors() && "invalid successor index");
2259 return mlir::SuccessorOperands(getSuccOperandsMutable()[index]);
2260}
2261
2263 OpAsmParser &parser, Type &flagType,
2264 SmallVectorImpl<Block *> &succOperandBlocks,
2265 SmallVectorImpl<SmallVector<OpAsmParser::UnresolvedOperand>> &succOperands,
2266 SmallVectorImpl<SmallVector<Type>> &succOperandsTypes) {
2267 if (failed(parser.parseCommaSeparatedList(
2268 OpAsmParser::Delimiter::Square,
2269 [&]() {
2270 Block *destination = nullptr;
2271 SmallVector<OpAsmParser::UnresolvedOperand> operands;
2272 SmallVector<Type> operandTypes;
2273
2274 if (parser.parseSuccessor(destination).failed())
2275 return failure();
2276
2277 if (succeeded(parser.parseOptionalLParen())) {
2278 if (failed(parser.parseOperandList(
2279 operands, OpAsmParser::Delimiter::None)) ||
2280 failed(parser.parseColonTypeList(operandTypes)) ||
2281 failed(parser.parseRParen()))
2282 return failure();
2283 }
2284 succOperandBlocks.push_back(destination);
2285 succOperands.emplace_back(operands);
2286 succOperandsTypes.emplace_back(operandTypes);
2287 return success();
2288 },
2289 "successor blocks")))
2290 return failure();
2291 return success();
2292}
2293
2294void cir::printIndirectBrOpSucessors(OpAsmPrinter &p, cir::IndirectBrOp op,
2295 Type flagType, SuccessorRange succs,
2296 OperandRangeRange succOperands,
2297 const TypeRangeRange &succOperandsTypes) {
2298 p << "[";
2299 llvm::interleave(
2300 llvm::zip(succs, succOperands),
2301 [&](auto i) {
2302 p.printNewline();
2303 p.printSuccessorAndUseList(std::get<0>(i), std::get<1>(i));
2304 },
2305 [&] { p << ','; });
2306 if (!succOperands.empty())
2307 p.printNewline();
2308 p << "]";
2309}
2310
2311//===----------------------------------------------------------------------===//
2312// BrCondOp
2313//===----------------------------------------------------------------------===//
2314
2315mlir::SuccessorOperands cir::BrCondOp::getSuccessorOperands(unsigned index) {
2316 assert(index < getNumSuccessors() && "invalid successor index");
2317 return SuccessorOperands(index == 0 ? getDestOperandsTrueMutable()
2318 : getDestOperandsFalseMutable());
2319}
2320
2321Block *cir::BrCondOp::getSuccessorForOperands(ArrayRef<Attribute> operands) {
2322 if (IntegerAttr condAttr = dyn_cast_if_present<IntegerAttr>(operands.front()))
2323 return condAttr.getValue().isOne() ? getDestTrue() : getDestFalse();
2324 return nullptr;
2325}
2326
2327//===----------------------------------------------------------------------===//
2328// CaseOp
2329//===----------------------------------------------------------------------===//
2330
2331void cir::CaseOp::build(OpBuilder &builder, OperationState &result,
2332 ArrayAttr value, CaseOpKind kind,
2333 OpBuilder::InsertPoint &insertPoint) {
2334 OpBuilder::InsertionGuard guardSwitch(builder);
2335 result.addAttribute("value", value);
2336 result.getOrAddProperties<Properties>().kind =
2337 cir::CaseOpKindAttr::get(builder.getContext(), kind);
2338 Region *caseRegion = result.addRegion();
2339 builder.createBlock(caseRegion);
2340
2341 insertPoint = builder.saveInsertionPoint();
2342}
2343
2344//===----------------------------------------------------------------------===//
2345// SwitchOp
2346//===----------------------------------------------------------------------===//
2347
2348void cir::SwitchOp::build(OpBuilder &builder, OperationState &result,
2349 Value cond, BuilderOpStateCallbackRef switchBuilder) {
2350 assert(switchBuilder && "the builder callback for regions must be present");
2351 OpBuilder::InsertionGuard guardSwitch(builder);
2352 Region *switchRegion = result.addRegion();
2353 builder.createBlock(switchRegion);
2354 result.addOperands({cond});
2355 switchBuilder(builder, result.location, result);
2356}
2357
2358void cir::SwitchOp::collectCases(llvm::SmallVectorImpl<CaseOp> &cases) {
2359 walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
2360 // Don't walk in nested switch op.
2361 if (isa<cir::SwitchOp>(op) && op != *this)
2362 return WalkResult::skip();
2363
2364 if (auto caseOp = dyn_cast<cir::CaseOp>(op))
2365 cases.push_back(caseOp);
2366
2367 return WalkResult::advance();
2368 });
2369}
2370
2371bool cir::SwitchOp::isSimpleForm(llvm::SmallVectorImpl<CaseOp> &cases) {
2372 collectCases(cases);
2373
2374 if (getBody().empty())
2375 return false;
2376
2377 if (!isa<YieldOp>(getBody().front().back()))
2378 return false;
2379
2380 if (!llvm::all_of(getBody().front(),
2381 [](Operation &op) { return isa<CaseOp, YieldOp>(op); }))
2382 return false;
2383
2384 return llvm::all_of(cases, [this](CaseOp op) {
2385 return op->getParentOfType<SwitchOp>() == *this;
2386 });
2387}
2388
2389//===----------------------------------------------------------------------===//
2390// SwitchFlatOp
2391//===----------------------------------------------------------------------===//
2392
2393void cir::SwitchFlatOp::build(OpBuilder &builder, OperationState &result,
2394 Value value, Block *defaultDestination,
2395 ValueRange defaultOperands,
2396 ArrayRef<APInt> caseValues,
2397 BlockRange caseDestinations,
2398 ArrayRef<ValueRange> caseOperands) {
2399
2400 std::vector<mlir::Attribute> caseValuesAttrs;
2401 for (const APInt &val : caseValues)
2402 caseValuesAttrs.push_back(cir::IntAttr::get(value.getType(), val));
2403 mlir::ArrayAttr attrs = ArrayAttr::get(builder.getContext(), caseValuesAttrs);
2404
2405 build(builder, result, value, defaultOperands, caseOperands, attrs,
2406 defaultDestination, caseDestinations);
2407}
2408
2409SuccessorOperands cir::SwitchFlatOp::getSuccessorOperands(unsigned index) {
2410 assert(index < getNumSuccessors() && "invalid successor index");
2411 if (index == 0)
2412 return SuccessorOperands(getDefaultOperandsMutable());
2413 return SuccessorOperands(getCaseOperandsMutable()[index - 1]);
2414}
2415
2416Block *
2417cir::SwitchFlatOp::getSuccessorForOperands(ArrayRef<Attribute> operands) {
2418 auto cond = dyn_cast_if_present<cir::IntAttr>(operands.front());
2419 if (!cond)
2420 return nullptr;
2421 for (auto [value, dest] : llvm::zip(getCaseValues(), getCaseDestinations())) {
2422 const APInt &caseValue = cast<cir::IntAttr>(value).getValue();
2423 if (caseValue == cond.getValue())
2424 return dest;
2425 }
2426 return getDefaultDestination();
2427}
2428
2429/// <cases> ::= `[` (case (`,` case )* )? `]`
2430/// <case> ::= integer `:` bb-id (`(` ssa-use-and-type-list `)`)?
2431ParseResult cir::parseSwitchFlatOpCases(
2432 OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues,
2433 SmallVectorImpl<Block *> &caseDestinations,
2435 &caseOperands,
2436 SmallVectorImpl<llvm::SmallVector<Type>> &caseOperandTypes) {
2437 if (failed(parser.parseLSquare()))
2438 return failure();
2439 if (succeeded(parser.parseOptionalRSquare()))
2440 return success();
2442
2443 auto parseCase = [&]() {
2444 int64_t value = 0;
2445 if (failed(parser.parseInteger(value)))
2446 return failure();
2447
2448 values.push_back(cir::IntAttr::get(flagType, value));
2449
2450 Block *destination;
2452 llvm::SmallVector<Type> operandTypes;
2453 if (parser.parseColon() || parser.parseSuccessor(destination))
2454 return failure();
2455 if (!parser.parseOptionalLParen()) {
2456 if (parser.parseOperandList(operands, OpAsmParser::Delimiter::None,
2457 /*allowResultNumber=*/false) ||
2458 parser.parseColonTypeList(operandTypes) || parser.parseRParen())
2459 return failure();
2460 }
2461 caseDestinations.push_back(destination);
2462 caseOperands.emplace_back(operands);
2463 caseOperandTypes.emplace_back(operandTypes);
2464 return success();
2465 };
2466 if (failed(parser.parseCommaSeparatedList(parseCase)))
2467 return failure();
2468
2469 caseValues = ArrayAttr::get(flagType.getContext(), values);
2470
2471 return parser.parseRSquare();
2472}
2473
2474void cir::printSwitchFlatOpCases(OpAsmPrinter &p, cir::SwitchFlatOp op,
2475 Type flagType, mlir::ArrayAttr caseValues,
2476 SuccessorRange caseDestinations,
2477 OperandRangeRange caseOperands,
2478 const TypeRangeRange &caseOperandTypes) {
2479 p << '[';
2480 p.printNewline();
2481 if (!caseValues) {
2482 p << ']';
2483 return;
2484 }
2485
2486 size_t index = 0;
2487 llvm::interleave(
2488 llvm::zip(caseValues, caseDestinations),
2489 [&](auto i) {
2490 p << " ";
2491 mlir::Attribute a = std::get<0>(i);
2492 p << mlir::cast<cir::IntAttr>(a).getValue();
2493 p << ": ";
2494 p.printSuccessorAndUseList(std::get<1>(i), caseOperands[index++]);
2495 },
2496 [&] {
2497 p << ',';
2498 p.printNewline();
2499 });
2500 p.printNewline();
2501 p << ']';
2502}
2503
2504//===----------------------------------------------------------------------===//
2505// GlobalOp
2506//===----------------------------------------------------------------------===//
2507
2508static ParseResult parseConstantValue(OpAsmParser &parser,
2509 mlir::Attribute &valueAttr) {
2510 NamedAttrList attr;
2511 return parser.parseAttribute(valueAttr, "value", attr);
2512}
2513
2514static void printConstant(OpAsmPrinter &p, Attribute value) {
2515 p.printAttribute(value);
2516}
2517
2518mlir::LogicalResult cir::GlobalOp::verify() {
2519 // A function is not an object, so it cannot be the type of a global. A
2520 // global that holds a function's address carries a pointer type instead.
2521 if (mlir::isa<cir::FuncType>(getSymType()))
2522 return emitOpError("global type cannot be a function type");
2523
2524 // Verify that the initial value, if present, is either a unit attribute or
2525 // an attribute CIR supports.
2526 if (getInitialValue().has_value()) {
2527 if (checkConstantTypes(getOperation(), getSymType(), *getInitialValue())
2528 .failed())
2529 return failure();
2530 }
2531
2532 // The initial value can't be recomputed from the type once the ctor is
2533 // lowered (e.g. a null member pointer becomes -1 after CXXABILowering).
2534 if (!getCtorRegion().empty() && !getInitialValue().has_value())
2535 return emitOpError(
2536 "cannot have a constructor region without an initial value");
2537
2538 std::optional<DynamicInitInfoAttr> info = getDynamicInitInfo();
2539
2540 if ((getDynamicInitGuard().has_value()) && (!info || info->getLocal()) &&
2541 (!getCtorRegion().empty() || !getDtorRegion().empty()))
2542 return emitOpError(
2543 "Cannot have a static-local global-op with a constructor or "
2544 "destructor, they require in-function initialization via LocalInitOp");
2545
2546 // CIRGen emits 'dynamic_init_guard' and 'dynamic_init_info' together and
2547 // they are only meaningful together: the guard drives lowering, which reads
2548 // the info. Require both or neither so malformed .cir can carry neither a
2549 // guard without info nor a dangling info nothing will read.
2550 if (getDynamicInitGuard().has_value() != getDynamicInitInfo().has_value())
2551 return emitOpError("'dynamic_init_guard' and 'dynamic_init_info' must be "
2552 "present together");
2553
2554 if (getTlsRefs()) {
2555 // 'Unordered' TLS globals (variable template instantiations) legitimately
2556 // carry both: they can't use the shared __tls_init guard, so CIRGen also
2557 // gives them their own dynamic-init guard, mangled the same as
2558 // 'tls_refs's own guard name. 'Ordered' TLS globals share __tls_init and
2559 // have no per-variable guard name, so a dynamic-init guard there would be
2560 // a mismatch.
2561 if (getDynamicInitGuard().has_value() && !getTlsRefs()->getGuardName())
2562 return emitOpError("cannot have a dynamic-init guard combined with "
2563 "ordered tls references");
2564 if (!getTlsModel())
2565 return emitOpError("'tls_refs' only valid for tls");
2566 }
2567
2568 if (getAliasee().has_value()) {
2569 if (getInitialValue().has_value() || !getCtorRegion().empty() ||
2570 !getDtorRegion().empty())
2571 return emitOpError("global alias shall not have an initializer or "
2572 "constructor/destructor regions");
2573 }
2574
2575 // TODO(CIR): Many other checks for properties that haven't been upstreamed
2576 // yet.
2577
2578 return success();
2579}
2580
2581void cir::GlobalOp::build(
2582 OpBuilder &odsBuilder, OperationState &odsState, llvm::StringRef sym_name,
2583 mlir::Type sym_type, bool isConstant,
2584 mlir::ptr::MemorySpaceAttrInterface addrSpace,
2585 cir::GlobalLinkageKind linkage,
2586 function_ref<void(OpBuilder &, Location)> ctorBuilder,
2587 function_ref<void(OpBuilder &, Location)> dtorBuilder) {
2588 odsState.addAttribute(getSymNameAttrName(odsState.name),
2589 odsBuilder.getStringAttr(sym_name));
2590 odsState.addAttribute(getSymTypeAttrName(odsState.name),
2591 mlir::TypeAttr::get(sym_type));
2592 auto &properties = odsState.getOrAddProperties<cir::GlobalOp::Properties>();
2593 properties.setConstant(isConstant);
2594
2595 addrSpace = normalizeDefaultAddressSpace(addrSpace);
2596 if (addrSpace)
2597 odsState.addAttribute(getAddrSpaceAttrName(odsState.name), addrSpace);
2598
2599 cir::GlobalLinkageKindAttr linkageAttr =
2600 cir::GlobalLinkageKindAttr::get(odsBuilder.getContext(), linkage);
2601 odsState.addAttribute(getLinkageAttrName(odsState.name), linkageAttr);
2602
2603 Region *ctorRegion = odsState.addRegion();
2604 if (ctorBuilder) {
2605 odsBuilder.createBlock(ctorRegion);
2606 ctorBuilder(odsBuilder, odsState.location);
2607 }
2608
2609 Region *dtorRegion = odsState.addRegion();
2610 if (dtorBuilder) {
2611 odsBuilder.createBlock(dtorRegion);
2612 dtorBuilder(odsBuilder, odsState.location);
2613 }
2614}
2615
2616/// Given the region at `index`, or the parent operation if `index` is None,
2617/// return the successor regions. These are the regions that may be selected
2618/// during the flow of control. `operands` is a set of optional attributes that
2619/// correspond to a constant value for each operand, or null if that operand is
2620/// not a constant.
2621void cir::GlobalOp::getSuccessorRegions(
2622 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &regions) {
2623 // The `ctor` and `dtor` regions always branch back to the parent operation.
2624 if (!point.isParent()) {
2625 regions.emplace_back(getOperation());
2626 return;
2627 }
2628
2629 // Don't consider the ctor region if it is empty.
2630 Region *ctorRegion = &this->getCtorRegion();
2631 if (ctorRegion->empty())
2632 ctorRegion = nullptr;
2633
2634 // Don't consider the dtor region if it is empty.
2635 Region *dtorRegion = &this->getDtorRegion();
2636 if (dtorRegion->empty())
2637 dtorRegion = nullptr;
2638
2639 // If the condition isn't constant, both regions may be executed.
2640 if (ctorRegion)
2641 regions.push_back(RegionSuccessor(ctorRegion));
2642 if (dtorRegion)
2643 regions.push_back(RegionSuccessor(dtorRegion));
2644}
2645
2646static void printComdatName(OpAsmPrinter &p, StringAttr comdat) {
2647 if (!comdat)
2648 return;
2649 p << "comdat";
2650 if (!comdat.getValue().empty())
2651 p << "(\"" << comdat.getValue() << "\")";
2652}
2653
2654void cir::printComdatName(OpAsmPrinter &p, cir::GlobalOp op,
2655 StringAttr comdat) {
2656 ::printComdatName(p, comdat);
2657}
2658
2659ParseResult cir::parseComdatName(OpAsmParser &parser, StringAttr &comdatAttr) {
2660 if (parser.parseOptionalKeyword("comdat").failed())
2661 return success();
2662 std::string comdatKey;
2663 if (succeeded(parser.parseOptionalLParen())) {
2664 if (parser.parseString(&comdatKey).failed() ||
2665 parser.parseRParen().failed())
2666 return failure();
2667 }
2668 comdatAttr = parser.getBuilder().getStringAttr(comdatKey);
2669 return success();
2670}
2671
2672void cir::printGlobalOpTypeAndInitialValue(OpAsmPrinter &p, cir::GlobalOp op,
2673 TypeAttr type, Attribute initAttr,
2674 mlir::Region &ctorRegion,
2675 mlir::Region &dtorRegion) {
2676 auto printType = [&]() { p << ": " << type; };
2677 // Aliases are definitions but they have no initial value or ctor/dtor; the
2678 // assembly prints them like declarations (`: type`).
2679 if (op.isDeclaration() || op.getAliasee()) {
2680 printType();
2681 return;
2682 }
2683
2684 p << "= ";
2685 if (initAttr)
2686 printConstant(p, initAttr);
2687
2688 if (!ctorRegion.empty()) {
2689 p << " ctor ";
2690 p.printRegion(ctorRegion,
2691 /*printEntryBlockArgs=*/false,
2692 /*printBlockTerminators=*/false);
2693 }
2694
2695 if (!dtorRegion.empty()) {
2696 p << " dtor ";
2697 p.printRegion(dtorRegion,
2698 /*printEntryBlockArgs=*/false,
2699 /*printBlockTerminators=*/false);
2700 }
2701}
2702
2703ParseResult cir::parseGlobalOpTypeAndInitialValue(OpAsmParser &parser,
2704 TypeAttr &typeAttr,
2705 Attribute &initialValueAttr,
2706 mlir::Region &ctorRegion,
2707 mlir::Region &dtorRegion) {
2708 mlir::Type opTy;
2709 if (parser.parseOptionalEqual().failed()) {
2710 // Absence of equal means a declaration, so we need to parse the type.
2711 // cir.global @a : !cir.int<s, 32>
2712 if (parser.parseColonType(opTy))
2713 return failure();
2714 } else {
2715 // Parse constant with initializer, examples:
2716 // cir.global @y = 3.400000e+00 : f32
2717 // cir.global @rgb = #cir.const_array<[...] : !cir.array<!s8i x 3>>
2718 if (parseConstantValue(parser, initialValueAttr).failed())
2719 return failure();
2720
2721 assert(mlir::isa<mlir::TypedAttr>(initialValueAttr) &&
2722 "Non-typed attrs shouldn't appear here.");
2723 opTy = mlir::cast<mlir::TypedAttr>(initialValueAttr).getType();
2724
2725 // Parse constructor, example:
2726 // cir.global @rgb = #cir.zero : type ctor { ... }
2727 if (!parser.parseOptionalKeyword("ctor")) {
2728 auto parseLoc = parser.getCurrentLocation();
2729 if (parser.parseRegion(ctorRegion, /*arguments=*/{}, /*argTypes=*/{}))
2730 return failure();
2731 if (ensureRegionTerm(parser, ctorRegion, parseLoc).failed())
2732 return failure();
2733 }
2734
2735 // Parse destructor, example:
2736 // dtor { ... }
2737 if (!parser.parseOptionalKeyword("dtor")) {
2738 auto parseLoc = parser.getCurrentLocation();
2739 if (parser.parseRegion(dtorRegion, /*arguments=*/{}, /*argTypes=*/{}))
2740 return failure();
2741 if (ensureRegionTerm(parser, dtorRegion, parseLoc).failed())
2742 return failure();
2743 }
2744 }
2745
2746 typeAttr = TypeAttr::get(opTy);
2747 return success();
2748}
2749
2750//===----------------------------------------------------------------------===//
2751// GetGlobalOp
2752//===----------------------------------------------------------------------===//
2753
2754LogicalResult
2755cir::GetGlobalOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2756 // Verify that the result type underlying pointer type matches the type of
2757 // the referenced cir.global or cir.func op.
2758 mlir::Operation *op =
2759 symbolTable.lookupNearestSymbolFrom(*this, getNameAttr());
2760 if (op == nullptr || !(isa<GlobalOp>(op) || isa<FuncOp>(op)))
2761 return emitOpError("'")
2762 << getName()
2763 << "' does not reference a valid cir.global or cir.func";
2764
2765 mlir::Type symTy;
2766 mlir::ptr::MemorySpaceAttrInterface symAddrSpaceAttr{};
2767 if (auto g = dyn_cast<GlobalOp>(op)) {
2768 symTy = g.getSymType();
2769 symAddrSpaceAttr = g.getAddrSpaceAttr();
2770 // Verify that for thread local global access, the global needs to
2771 // be marked with tls bits.
2772 if (getTls() && !g.getTlsModel())
2773 return emitOpError("access to global not marked thread local");
2774
2775 // Verify that the static_local attribute on GetGlobalOp matches the
2776 // dynamic_init_guard attribute on GlobalOp. GetGlobalOp uses a UnitAttr,
2777 // GlobalOp uses DynamicInitGuardAttr. Both should be present, or neither.
2778 bool getGlobalIsStaticLocal = getStaticLocal();
2779 bool globalIsStaticLocal =
2780 g.getDynamicInitGuard().has_value() &&
2781 (!g.getDynamicInitInfo() || g.getDynamicInitInfo()->getLocal());
2782
2783 if (getGlobalIsStaticLocal != globalIsStaticLocal &&
2784 !getOperation()->getParentOfType<cir::GlobalOp>())
2785 return emitOpError("static_local attribute mismatch");
2786 } else if (auto f = dyn_cast<FuncOp>(op)) {
2787 symTy = f.getFunctionType();
2788 } else {
2789 llvm_unreachable("Unexpected operation for GetGlobalOp");
2790 }
2791
2792 auto resultType = dyn_cast<PointerType>(getAddr().getType());
2793 if (!resultType || symTy != resultType.getPointee())
2794 return emitOpError("result type pointee type '")
2795 << resultType.getPointee() << "' does not match type " << symTy
2796 << " of the global @" << getName();
2797
2798 // A function address may also be taken in the program address space.
2799 auto targetAS =
2800 dyn_cast_if_present<TargetAddressSpaceAttr>(resultType.getAddrSpace());
2801 bool isProgramAS =
2802 isa<FuncOp>(op) && targetAS &&
2803 targetAS.getValue() ==
2804 CIRDataLayout(getOperation()->getParentOfType<ModuleOp>())
2806 if (!isProgramAS && symAddrSpaceAttr != resultType.getAddrSpace()) {
2807 return emitOpError()
2808 << "result type address space does not match the address "
2809 "space of the global @"
2810 << getName();
2811 }
2812
2813 return success();
2814}
2815
2816//===----------------------------------------------------------------------===//
2817// VTableAddrPointOp
2818//===----------------------------------------------------------------------===//
2819
2820LogicalResult
2821cir::VTableAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2822 StringRef name = getName();
2823
2824 // Verify that the result type underlying pointer type matches the type of
2825 // the referenced cir.global.
2826 auto op =
2827 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*this, getNameAttr());
2828 if (!op)
2829 return emitOpError("'")
2830 << name << "' does not reference a valid cir.global";
2831 std::optional<mlir::Attribute> init = op.getInitialValue();
2832 if (!init)
2833 return success();
2834 if (!isa<cir::VTableAttr>(*init))
2835 return emitOpError("Expected #cir.vtable in initializer for global '")
2836 << name << "'";
2837 return success();
2838}
2839
2840//===----------------------------------------------------------------------===//
2841// VTTAddrPointOp
2842//===----------------------------------------------------------------------===//
2843
2844LogicalResult
2845cir::VTTAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2846 // VTT ptr is not coming from a symbol.
2847 if (!getName())
2848 return success();
2849 StringRef name = *getName();
2850
2851 // Verify that the result type underlying pointer type matches the type of
2852 // the referenced cir.global op.
2853 auto op =
2854 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*this, getNameAttr());
2855 if (!op)
2856 return emitOpError("'")
2857 << name << "' does not reference a valid cir.global";
2858 std::optional<mlir::Attribute> init = op.getInitialValue();
2859 if (!init)
2860 return success();
2861 if (!isa<cir::ConstArrayAttr>(*init))
2862 return emitOpError(
2863 "Expected constant array in initializer for global VTT '")
2864 << name << "'";
2865 return success();
2866}
2867
2868LogicalResult cir::VTTAddrPointOp::verify() {
2869 // The operation uses either a symbol or a value to operate, but not both
2870 if (getName() && getSymAddr())
2871 return emitOpError("should use either a symbol or value, but not both");
2872
2873 // If not a symbol, stick with the concrete type used for getSymAddr.
2874 if (getSymAddr())
2875 return success();
2876
2877 mlir::Type resultType = getAddr().getType();
2878 mlir::Type resTy = cir::PointerType::get(
2879 cir::PointerType::get(cir::VoidType::get(getContext())));
2880
2881 if (resultType != resTy)
2882 return emitOpError("result type must be ")
2883 << resTy << ", but provided result type is " << resultType;
2884 return success();
2885}
2886
2887//===----------------------------------------------------------------------===//
2888// FuncOp
2889//===----------------------------------------------------------------------===//
2890
2891/// Returns the name used for the linkage attribute. This *must* correspond to
2892/// the name of the attribute in ODS.
2893static llvm::StringRef getLinkageAttrNameString() { return "linkage"; }
2894
2895/// Declared cir.func attributes with no dedicated syntax, which print in and
2896/// parse from the attribute dictionary instead.
2897static bool isFuncAttrInDict(llvm::StringRef name) {
2898 return name == CIRDialect::getMemoryEffectsAttrName() ||
2899 name == CIRDialect::getUwtableAttrName() ||
2900 name == CIRDialect::getFramePointerAttrName();
2901}
2902
2903void cir::FuncOp::build(OpBuilder &builder, OperationState &result,
2904 StringRef name, FuncType type,
2905 GlobalLinkageKind linkage, CallingConv callingConv) {
2906 result.addRegion();
2907 result.addAttribute(getSymNameAttrName(result.name),
2908 builder.getStringAttr(name));
2909 result.addAttribute(getFunctionTypeAttrName(result.name),
2910 TypeAttr::get(type));
2911 result.addAttribute(
2913 GlobalLinkageKindAttr::get(builder.getContext(), linkage));
2914 result.addAttribute(getCallingConvAttrName(result.name),
2915 CallingConvAttr::get(builder.getContext(), callingConv));
2916 // A function starts out written in source-level types, and CallConvLowering
2917 // rewrites it to the target ABI later.
2918 result.addAttribute(getRequiresCallConvLoweringAttrName(result.name),
2919 builder.getUnitAttr());
2920}
2921
2922//===----------------------------------------------------------------------===//
2923// AnnotationAttr
2924//===----------------------------------------------------------------------===//
2925
2926LogicalResult
2927cir::AnnotationAttr::verify(function_ref<InFlightDiagnostic()> emitError,
2928 mlir::StringAttr name, mlir::ArrayAttr args) {
2929 if (!args)
2930 return success();
2931 for (mlir::Attribute arg : args) {
2932 if (!isa<mlir::StringAttr, mlir::IntegerAttr>(arg))
2933 return emitError() << "annotation args must be StringAttr or IntegerAttr,"
2934 << " got " << arg;
2935 }
2936 return success();
2937}
2938
2939ParseResult cir::FuncOp::parse(OpAsmParser &parser, OperationState &state) {
2940 llvm::SMLoc loc = parser.getCurrentLocation();
2941 mlir::Builder &builder = parser.getBuilder();
2942
2943 mlir::StringAttr builtinNameAttr = getBuiltinAttrName(state.name);
2944 mlir::StringAttr coroutineKindNameAttr = getCoroutineKindAttrName(state.name);
2945 mlir::StringAttr inlineKindNameAttr = getInlineKindAttrName(state.name);
2946 mlir::StringAttr lambdaNameAttr = getLambdaAttrName(state.name);
2947 mlir::StringAttr noProtoNameAttr = getNoProtoAttrName(state.name);
2948 mlir::StringAttr requiresCallConvLoweringNameAttr =
2949 getRequiresCallConvLoweringAttrName(state.name);
2950 mlir::StringAttr comdatNameAttr = getComdatAttrName(state.name);
2951 mlir::StringAttr alignmentNameAttr = getAlignmentAttrName(state.name);
2952 mlir::StringAttr preferredAlignmentNameAttr =
2953 getPreferredAlignmentAttrName(state.name);
2954 mlir::StringAttr visNameAttr = getSymVisibilityAttrName(state.name);
2955 mlir::StringAttr dsoLocalNameAttr = getDsoLocalAttrName(state.name);
2956 mlir::StringAttr unnamedAddrNameAttr = getUnnamedAddrAttrName(state.name);
2957 mlir::StringAttr funcInfoNameAttr = getFuncInfoAttrName(state.name);
2958
2959 if (::mlir::succeeded(parser.parseOptionalKeyword(builtinNameAttr.strref())))
2960 state.addAttribute(builtinNameAttr, parser.getBuilder().getUnitAttr());
2961
2962 // Parse optional coroutine kind attribute
2963 {
2964 static constexpr llvm::StringRef keywords[] = {"coroutine",
2965 "flattened_coroutine"};
2966 llvm::StringRef keyword;
2967 if (parser.parseOptionalKeyword(&keyword, keywords).succeeded())
2968 state.addAttribute(
2969 coroutineKindNameAttr,
2970 cir::CoroutineKindAttr::get(builder.getContext(),
2971 *cir::symbolizeCoroutineKind(keyword)));
2972 }
2973
2974 // Parse optional inline kind attribute
2975 cir::InlineKindAttr inlineKindAttr;
2976 if (failed(parseInlineKindAttr(parser, inlineKindAttr)))
2977 return failure();
2978 if (inlineKindAttr)
2979 state.addAttribute(inlineKindNameAttr, inlineKindAttr);
2980
2981 if (::mlir::succeeded(parser.parseOptionalKeyword(lambdaNameAttr.strref())))
2982 state.addAttribute(lambdaNameAttr, parser.getBuilder().getUnitAttr());
2983 if (parser.parseOptionalKeyword(noProtoNameAttr).succeeded())
2984 state.addAttribute(noProtoNameAttr, parser.getBuilder().getUnitAttr());
2985
2986 {
2987 StringAttr comdatAttr;
2988 if (parseComdatName(parser, comdatAttr).failed())
2989 return failure();
2990 if (comdatAttr)
2991 state.addAttribute(comdatNameAttr, comdatAttr);
2992 }
2993
2994 auto parseAlignmentBody = [&](int64_t &value) {
2995 if (parser.parseLParen().failed() || parser.parseInteger(value).failed() ||
2996 parser.parseRParen().failed())
2997 return failure();
2998
2999 if (value <= 0)
3000 return static_cast<LogicalResult>(parser.emitError(
3001 loc, "function alignment must be a positive integer"));
3002
3003 return success();
3004 };
3005
3006 if (parser.parseOptionalKeyword(alignmentNameAttr).succeeded()) {
3007 int64_t value;
3008 if (parseAlignmentBody(value).failed())
3009 return failure();
3010 state.addAttribute(alignmentNameAttr, builder.getI64IntegerAttr(value));
3011 }
3012
3013 if (parser.parseOptionalKeyword(preferredAlignmentNameAttr).succeeded()) {
3014 int64_t value;
3015 if (parseAlignmentBody(value).failed())
3016 return failure();
3017 state.addAttribute(preferredAlignmentNameAttr,
3018 builder.getI64IntegerAttr(value));
3019 }
3020
3021 // Default to external linkage if no keyword is provided.
3022 state.addAttribute(getLinkageAttrNameString(),
3023 GlobalLinkageKindAttr::get(
3024 parser.getContext(),
3026 parser, GlobalLinkageKind::ExternalLinkage)));
3027
3028 ::llvm::StringRef visAttrStr;
3029 if (parser.parseOptionalKeyword(&visAttrStr, {"private", "public", "nested"})
3030 .succeeded()) {
3031 state.addAttribute(visNameAttr,
3032 parser.getBuilder().getStringAttr(visAttrStr));
3033 }
3034
3035 state.getOrAddProperties<cir::FuncOp::Properties>().global_visibility =
3036 parseOptionalCIRKeyword(parser, cir::VisibilityKind::Default);
3037
3038 if (parser.parseOptionalKeyword(dsoLocalNameAttr).succeeded())
3039 state.addAttribute(dsoLocalNameAttr, parser.getBuilder().getUnitAttr());
3040
3041 if (parser.parseOptionalKeyword(unnamedAddrNameAttr).succeeded())
3042 state.addAttribute(unnamedAddrNameAttr, parser.getBuilder().getUnitAttr());
3043
3044 StringAttr nameAttr;
3045 if (parser.parseSymbolName(nameAttr, getSymNameAttrName(state.name),
3046 state.attributes))
3047 return failure();
3051 bool isVariadic = false;
3052 if (function_interface_impl::parseFunctionSignatureWithArguments(
3053 parser, /*allowVariadic=*/true, arguments, isVariadic, resultTypes,
3054 resultAttrs))
3055 return failure();
3058 bool argAttrsEmpty = true;
3059 for (OpAsmParser::Argument &arg : arguments) {
3060 argTypes.push_back(arg.type);
3061 // Add the 'empty' attribute anyway to make sure the arity matches, but we
3062 // only want to 'set' the attribute at the top level if there is SOME data
3063 // along the way.
3064 argAttrs.push_back(arg.attrs);
3065 if (arg.attrs)
3066 argAttrsEmpty = false;
3067 }
3068
3069 // These should be in sync anyway, but test both of them anyway.
3070 if (resultTypes.size() > 1 || resultAttrs.size() > 1)
3071 return parser.emitError(
3072 loc, "functions with multiple return types are not supported");
3073
3074 mlir::Type returnType =
3075 (resultTypes.empty() ? cir::VoidType::get(builder.getContext())
3076 : resultTypes.front());
3077
3078 cir::FuncType fnType =
3079 cir::FuncType::getChecked([&]() { return parser.emitError(loc); },
3080 argTypes, returnType, isVariadic);
3081 if (!fnType)
3082 return failure();
3083
3084 state.addAttribute(getFunctionTypeAttrName(state.name),
3085 TypeAttr::get(fnType));
3086
3087 if (!resultAttrs.empty() && resultAttrs[0])
3088 state.addAttribute(
3089 getResAttrsAttrName(state.name),
3090 mlir::ArrayAttr::get(parser.getContext(), {resultAttrs[0]}));
3091
3092 if (!argAttrsEmpty)
3093 state.addAttribute(getArgAttrsAttrName(state.name),
3094 mlir::ArrayAttr::get(parser.getContext(), argAttrs));
3095
3096 bool hasAlias = false;
3097 mlir::StringAttr aliaseeNameAttr = getAliaseeAttrName(state.name);
3098 if (parser.parseOptionalKeyword("alias").succeeded()) {
3099 if (parser.parseLParen().failed())
3100 return failure();
3101 mlir::StringAttr aliaseeAttr;
3102 if (parser.parseOptionalSymbolName(aliaseeAttr).failed())
3103 return failure();
3104 state.addAttribute(aliaseeNameAttr, FlatSymbolRefAttr::get(aliaseeAttr));
3105 if (parser.parseRParen().failed())
3106 return failure();
3107 hasAlias = true;
3108 }
3109
3110 mlir::StringAttr personalityNameAttr = getPersonalityAttrName(state.name);
3111 if (parser.parseOptionalKeyword("personality").succeeded()) {
3112 if (parser.parseLParen().failed())
3113 return failure();
3114 mlir::StringAttr personalityAttr;
3115 if (parser.parseOptionalSymbolName(personalityAttr).failed())
3116 return failure();
3117 state.addAttribute(personalityNameAttr,
3118 FlatSymbolRefAttr::get(personalityAttr));
3119 if (parser.parseRParen().failed())
3120 return failure();
3121 }
3122
3123 // Default to C calling convention if no keyword is provided.
3124 mlir::StringAttr callConvNameAttr = getCallingConvAttrName(state.name);
3125 cir::CallingConv callConv = cir::CallingConv::C;
3126 if (parser.parseOptionalKeyword("cc").succeeded()) {
3127 if (parser.parseLParen().failed())
3128 return failure();
3129 if (parseCIRKeyword<cir::CallingConv>(parser, callConv).failed())
3130 return parser.emitError(loc) << "unknown calling convention";
3131 if (parser.parseRParen().failed())
3132 return failure();
3133 }
3134 state.addAttribute(callConvNameAttr,
3135 cir::CallingConvAttr::get(parser.getContext(), callConv));
3136
3137 auto parseGlobalDtorCtor =
3138 [&](StringRef keyword,
3139 llvm::function_ref<void(std::optional<int> prio)> createAttr)
3140 -> mlir::LogicalResult {
3141 if (mlir::succeeded(parser.parseOptionalKeyword(keyword))) {
3142 std::optional<int> priority;
3143 if (mlir::succeeded(parser.parseOptionalLParen())) {
3144 auto parsedPriority = mlir::FieldParser<int>::parse(parser);
3145 if (mlir::failed(parsedPriority))
3146 return parser.emitError(parser.getCurrentLocation(),
3147 "failed to parse 'priority', of type 'int'");
3148 priority = parsedPriority.value_or(int());
3149 // Parse literal ')'
3150 if (parser.parseRParen())
3151 return failure();
3152 }
3153 createAttr(priority);
3154 }
3155 return success();
3156 };
3157
3158 // Parse the func_info attribute
3159 if (parser.parseOptionalKeyword("func_info").succeeded()) {
3160 if (parser.parseLess().failed())
3161 return failure();
3162
3163 llvm::SMLoc attrLoc = parser.getCurrentLocation();
3164 mlir::Attribute attr;
3165 if (parser.parseAttribute(attr).failed())
3166 return failure();
3167 if (!mlir::isa<cir::CXXCtorAttr, cir::CXXDtorAttr, cir::CXXAssignAttr,
3168 cir::FuncIdentityAttr>(attr))
3169 return parser.emitError(attrLoc,
3170 "expected a function info attribute, got ")
3171 << attr;
3172 state.addAttribute(funcInfoNameAttr, attr);
3173
3174 if (parser.parseGreater().failed())
3175 return failure();
3176 }
3177
3178 if (parseGlobalDtorCtor("global_ctor", [&](std::optional<int> priority) {
3179 mlir::IntegerAttr globalCtorPriorityAttr =
3180 builder.getI32IntegerAttr(priority.value_or(65535));
3181 state.addAttribute(getGlobalCtorPriorityAttrName(state.name),
3182 globalCtorPriorityAttr);
3183 }).failed())
3184 return failure();
3185
3186 if (parseGlobalDtorCtor("global_dtor", [&](std::optional<int> priority) {
3187 mlir::IntegerAttr globalDtorPriorityAttr =
3188 builder.getI32IntegerAttr(priority.value_or(65535));
3189 state.addAttribute(getGlobalDtorPriorityAttrName(state.name),
3190 globalDtorPriorityAttr);
3191 }).failed())
3192 return failure();
3193
3194 // Parse optional annotations attribute (an ArrayAttr of AnnotationAttr).
3195 mlir::StringAttr annotationsNameAttr = getAnnotationsAttrName(state.name);
3196 mlir::ArrayAttr annotationsAttr;
3197 if (parser.parseOptionalAttribute(annotationsAttr).has_value() &&
3198 annotationsAttr)
3199 state.addAttribute(annotationsNameAttr, annotationsAttr);
3200
3201 if (parser.parseOptionalKeyword(requiresCallConvLoweringNameAttr).succeeded())
3202 state.addAttribute(requiresCallConvLoweringNameAttr,
3203 parser.getBuilder().getUnitAttr());
3204
3205 // Parse the rest of the attributes.
3206 NamedAttrList parsedAttrs;
3207 llvm::SMLoc attrsLoc = parser.getCurrentLocation();
3208 if (parser.parseOptionalAttrDictWithKeyword(parsedAttrs))
3209 return failure();
3210
3211 // Every other declared attribute has dedicated syntax above.
3212 for (StringRef disallowed : cir::FuncOp::getAttributeNames()) {
3213 if (isFuncAttrInDict(disallowed))
3214 continue;
3215 if (parsedAttrs.get(disallowed))
3216 return parser.emitError(loc, "attribute '")
3217 << disallowed
3218 << "' should not be specified in the explicit attribute list";
3219 }
3220
3221 if (checkEffectAttrKinds(parser, attrsLoc, parsedAttrs).failed())
3222 return failure();
3223
3224 state.attributes.append(parsedAttrs);
3225
3226 // Parse the optional function body.
3227 auto *body = state.addRegion();
3228 OptionalParseResult parseResult = parser.parseOptionalRegion(
3229 *body, arguments, /*enableNameShadowing=*/false);
3230 if (parseResult.has_value()) {
3231 if (hasAlias)
3232 return parser.emitError(loc, "function alias shall not have a body");
3233 if (failed(*parseResult))
3234 return failure();
3235 // Function body was parsed, make sure its not empty.
3236 if (body->empty())
3237 return parser.emitError(loc, "expected non-empty function body");
3238 }
3239
3240 return success();
3241}
3242
3243// This function corresponds to `llvm::GlobalValue::isDeclaration` and should
3244// have a similar implementation. We don't currently ifuncs or materializable
3245// functions, but those should be handled here as they are implemented.
3246bool cir::FuncOp::isDeclaration() {
3248
3249 std::optional<StringRef> aliasee = getAliasee();
3250 if (!aliasee)
3251 return getFunctionBody().empty();
3252
3253 // Aliases are always definitions.
3254 return false;
3255}
3256
3257bool cir::FuncOp::isCXXSpecialMemberFunction() {
3258 // The func_info union can grow forms that are not special members, so the
3259 // check names the concrete forms rather than testing for presence.
3260 mlir::Attribute attr = getFuncInfoAttr();
3261 return attr && mlir::isa<CXXCtorAttr, CXXDtorAttr, CXXAssignAttr>(attr);
3262}
3263
3264bool cir::FuncOp::isCxxConstructor() {
3265 auto attr = getFuncInfoAttr();
3266 return attr && dyn_cast<CXXCtorAttr>(attr);
3267}
3268
3269bool cir::FuncOp::isCxxDestructor() {
3270 auto attr = getFuncInfoAttr();
3271 return attr && dyn_cast<CXXDtorAttr>(attr);
3272}
3273
3274bool cir::FuncOp::isCxxSpecialAssignment() {
3275 auto attr = getFuncInfoAttr();
3276 return attr && dyn_cast<CXXAssignAttr>(attr);
3277}
3278
3279std::optional<CtorKind> cir::FuncOp::getCxxConstructorKind() {
3280 mlir::Attribute attr = getFuncInfoAttr();
3281 if (attr) {
3282 if (auto ctor = dyn_cast<CXXCtorAttr>(attr))
3283 return ctor.getCtorKind();
3284 }
3285 return std::nullopt;
3286}
3287
3288std::optional<AssignKind> cir::FuncOp::getCxxSpecialAssignKind() {
3289 mlir::Attribute attr = getFuncInfoAttr();
3290 if (attr) {
3291 if (auto assign = dyn_cast<CXXAssignAttr>(attr))
3292 return assign.getAssignKind();
3293 }
3294 return std::nullopt;
3295}
3296
3297bool cir::FuncOp::isCxxTrivialMemberFunction() {
3298 mlir::Attribute attr = getFuncInfoAttr();
3299 if (attr) {
3300 if (auto ctor = dyn_cast<CXXCtorAttr>(attr))
3301 return ctor.getIsTrivial();
3302 if (auto dtor = dyn_cast<CXXDtorAttr>(attr))
3303 return dtor.getIsTrivial();
3304 if (auto assign = dyn_cast<CXXAssignAttr>(attr))
3305 return assign.getIsTrivial();
3306 }
3307 return false;
3308}
3309
3310mlir::Region *cir::FuncOp::getCallableRegion() {
3311 // Declarations and aliases have no body to analyze or inline. Returning the
3312 // empty region would make interprocedural analyses (e.g. SCCP) treat calls
3313 // to them as having no returns, leaving their results uninitialized.
3314 if (getBody().empty())
3315 return nullptr;
3316 return &getBody();
3317}
3318
3319void cir::FuncOp::print(OpAsmPrinter &p) {
3320 if (getBuiltin())
3321 p << " builtin";
3322
3323 if (std::optional<cir::CoroutineKind> coroKind = getCoroutineKind())
3324 p << ' ' << cir::stringifyCoroutineKind(*coroKind);
3325
3326 printInlineKindAttr(p, getInlineKindAttr());
3327
3328 if (getLambda())
3329 p << " lambda";
3330
3331 if (getNoProto())
3332 p << " no_proto";
3333
3334 if (getComdatAttr()) {
3335 p << ' ';
3336 ::printComdatName(p, getComdatAttr());
3337 }
3338
3339 if (getAlignment())
3340 p << " alignment(" << *getAlignment() << ')';
3341
3342 if (getPreferredAlignment())
3343 p << " preferred_alignment(" << *getPreferredAlignment() << ')';
3344
3345 if (getLinkage() != GlobalLinkageKind::ExternalLinkage)
3346 p << ' ' << stringifyGlobalLinkageKind(getLinkage());
3347
3348 mlir::SymbolTable::Visibility vis = getVisibility();
3349 if (vis != mlir::SymbolTable::Visibility::Public)
3350 p << ' ' << vis;
3351
3352 if (getGlobalVisibility() != cir::VisibilityKind::Default)
3353 p << ' ' << stringifyVisibilityKind(getGlobalVisibility());
3354
3355 if (getDsoLocal())
3356 p << " dso_local";
3357
3358 if (getUnnamedAddr())
3359 p << " unnamed_addr";
3360
3361 p << ' ';
3362 p.printSymbolName(getSymName());
3363 cir::FuncType fnType = getFunctionType();
3364 function_interface_impl::printFunctionSignature(
3365 p, *this, fnType.getInputs(), fnType.isVarArg(), fnType.getReturnTypes());
3366
3367 if (std::optional<StringRef> aliaseeName = getAliasee()) {
3368 p << " alias(";
3369 p.printSymbolName(*aliaseeName);
3370 p << ")";
3371 }
3372
3373 if (getCallingConv() != cir::CallingConv::C) {
3374 p << " cc(";
3375 p << stringifyCallingConv(getCallingConv());
3376 p << ")";
3377 }
3378
3379 if (std::optional<StringRef> personalityName = getPersonality()) {
3380 p << " personality(";
3381 p.printSymbolName(*personalityName);
3382 p << ")";
3383 }
3384
3385 if (mlir::Attribute funcInfo = getFuncInfoAttr()) {
3386 p << " func_info<";
3387 p.printAttribute(funcInfo);
3388 p << '>';
3389 }
3390
3391 if (auto globalCtorPriority = getGlobalCtorPriority()) {
3392 p << " global_ctor";
3393 if (globalCtorPriority.value() != 65535)
3394 p << "(" << globalCtorPriority.value() << ")";
3395 }
3396
3397 if (auto globalDtorPriority = getGlobalDtorPriority()) {
3398 p << " global_dtor";
3399 if (globalDtorPriority.value() != 65535)
3400 p << "(" << globalDtorPriority.value() << ")";
3401 }
3402
3403 if (mlir::ArrayAttr annotations = getAnnotationsAttr()) {
3404 p << ' ';
3405 p.printAttribute(annotations);
3406 }
3407
3408 if (getRequiresCallConvLowering())
3409 p << ' ' << getRequiresCallConvLoweringAttrName().getValue();
3410
3411 // Every other declared attribute is printed by the syntax above.
3413 for (llvm::StringRef name : cir::FuncOp::getAttributeNames())
3414 if (!isFuncAttrInDict(name))
3415 elidedAttrs.push_back(name);
3416 function_interface_impl::printFunctionAttributes(p, *this, elidedAttrs);
3417
3418 // Print the body if this is not an external function.
3419 Region &body = getOperation()->getRegion(0);
3420 if (!body.empty()) {
3421 p << ' ';
3422 p.printRegion(body, /*printEntryBlockArgs=*/false,
3423 /*printBlockTerminators=*/true);
3424 }
3425}
3426
3427mlir::LogicalResult cir::FuncOp::verify() {
3428
3429 if (!isDeclaration() && getCoroutineKind() == cir::CoroutineKind::Coroutine) {
3430 int coroutineOpCount = 0;
3431 this->walk([&](Operation *op) {
3432 if (isa<CoroutineOp>(op)) {
3433 coroutineOpCount++;
3434 if (coroutineOpCount > 1) {
3435 return mlir::WalkResult::interrupt();
3436 }
3437 }
3438 return mlir::WalkResult::advance();
3439 });
3440 if (coroutineOpCount != 1)
3441 return emitOpError()
3442 << "coroutine function must have exactly one cir.coroutine op";
3443 }
3444
3445 llvm::SmallSet<llvm::StringRef, 16> labels;
3446 llvm::SmallSet<llvm::StringRef, 16> gotos;
3447 llvm::SmallSet<llvm::StringRef, 16> blockAddresses;
3448 bool invalidBlockAddress = false;
3449 getOperation()->walk([&](mlir::Operation *op) {
3450 if (auto lab = dyn_cast<cir::LabelOp>(op)) {
3451 labels.insert(lab.getLabel());
3452 } else if (auto goTo = dyn_cast<cir::GotoOp>(op)) {
3453 gotos.insert(goTo.getLabel());
3454 } else if (auto blkAdd = dyn_cast<cir::BlockAddressOp>(op)) {
3455 if (blkAdd.getBlockAddrInfoAttr().getFunc().getAttr() != getSymName()) {
3456 // Stop the walk early, no need to continue
3457 invalidBlockAddress = true;
3458 return mlir::WalkResult::interrupt();
3459 }
3460 blockAddresses.insert(blkAdd.getBlockAddrInfoAttr().getLabel());
3461 }
3462 return mlir::WalkResult::advance();
3463 });
3464
3465 if (invalidBlockAddress)
3466 return emitOpError() << "blockaddress references a different function";
3467
3468 llvm::SmallSet<llvm::StringRef, 16> mismatched;
3469 if (!labels.empty() || !gotos.empty()) {
3470 mismatched = llvm::set_difference(gotos, labels);
3471
3472 if (!mismatched.empty())
3473 return emitOpError() << "goto/label mismatch";
3474 }
3475
3476 mismatched.clear();
3477
3478 if (!labels.empty() || !blockAddresses.empty()) {
3479 mismatched = llvm::set_difference(blockAddresses, labels);
3480
3481 if (!mismatched.empty())
3482 return emitOpError()
3483 << "expects an existing label target in the referenced function";
3484 }
3485
3486 return success();
3487}
3488
3489//===----------------------------------------------------------------------===//
3490// TernaryOp
3491//===----------------------------------------------------------------------===//
3492
3493void cir::TernaryOp::build(
3494 OpBuilder &builder, OperationState &result, Value cond,
3495 function_ref<void(OpBuilder &, Location)> trueBuilder,
3496 function_ref<void(OpBuilder &, Location)> falseBuilder) {
3497 result.addOperands(cond);
3498 OpBuilder::InsertionGuard guard(builder);
3499 Region *trueRegion = result.addRegion();
3500 builder.createBlock(trueRegion);
3501 trueBuilder(builder, result.location);
3502 Region *falseRegion = result.addRegion();
3503 builder.createBlock(falseRegion);
3504 falseBuilder(builder, result.location);
3505
3506 // Get result type from whichever branch has a yield (the other may have
3507 // unreachable from a throw expression)
3508 cir::YieldOp yield;
3509 if (trueRegion->back().mightHaveTerminator())
3510 yield = dyn_cast_or_null<cir::YieldOp>(trueRegion->back().getTerminator());
3511 if (!yield && falseRegion->back().mightHaveTerminator())
3512 yield = dyn_cast_or_null<cir::YieldOp>(falseRegion->back().getTerminator());
3513
3514 assert((!yield || yield.getNumOperands() <= 1) &&
3515 "expected zero or one result type");
3516 if (yield && yield.getNumOperands() == 1)
3517 result.addTypes(TypeRange{yield.getOperandTypes().front()});
3518}
3519
3520//===----------------------------------------------------------------------===//
3521// SelectOp
3522//===----------------------------------------------------------------------===//
3523
3524OpFoldResult cir::SelectOp::fold(FoldAdaptor adaptor) {
3525 if (auto condition =
3526 mlir::dyn_cast_if_present<cir::BoolAttr>(adaptor.getCondition()))
3527 return condition.getValue() ? getTrueValue() : getFalseValue();
3528
3529 // cir.select if %0 then x else x -> x
3530 mlir::Attribute trueValue = adaptor.getTrueValue();
3531 mlir::Attribute falseValue = adaptor.getFalseValue();
3532 if (trueValue == falseValue)
3533 return trueValue;
3534 if (getTrueValue() == getFalseValue())
3535 return getTrueValue();
3536
3537 return {};
3538}
3539
3540LogicalResult cir::SelectOp::verify() {
3541 // AllTypesMatch already guarantees trueVal and falseVal have matching types.
3542 auto condTy = dyn_cast<cir::VectorType>(getCondition().getType());
3543
3544 // If condition is not a vector, no further checks are needed.
3545 if (!condTy)
3546 return success();
3547
3548 // When condition is a vector, both other operands must also be vectors.
3549 if (!isa<cir::VectorType>(getTrueValue().getType()) ||
3550 !isa<cir::VectorType>(getFalseValue().getType())) {
3551 return emitOpError()
3552 << "expected both true and false operands to be vector types "
3553 "when the condition is a vector boolean type";
3554 }
3555
3556 return success();
3557}
3558
3559//===----------------------------------------------------------------------===//
3560// ShiftOp
3561//===----------------------------------------------------------------------===//
3562LogicalResult cir::ShiftOp::verify() {
3563 mlir::Operation *op = getOperation();
3564 auto op0VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(0).getType());
3565 auto op1VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(1).getType());
3566 if (!op0VecTy ^ !op1VecTy)
3567 return emitOpError() << "input types cannot be one vector and one scalar";
3568
3569 if (op0VecTy) {
3570 if (op0VecTy.getSize() != op1VecTy.getSize())
3571 return emitOpError() << "input vector types must have the same size";
3572
3573 auto opResultTy = mlir::dyn_cast<cir::VectorType>(getType());
3574 if (!opResultTy)
3575 return emitOpError() << "the type of the result must be a vector "
3576 << "if it is vector shift";
3577
3578 auto op0VecEleTy = mlir::cast<cir::IntType>(op0VecTy.getElementType());
3579 auto op1VecEleTy = mlir::cast<cir::IntType>(op1VecTy.getElementType());
3580 if (op0VecEleTy.getWidth() != op1VecEleTy.getWidth())
3581 return emitOpError()
3582 << "vector operands do not have the same elements sizes";
3583
3584 auto resVecEleTy = mlir::cast<cir::IntType>(opResultTy.getElementType());
3585 if (op0VecEleTy.getWidth() != resVecEleTy.getWidth())
3586 return emitOpError() << "vector operands and result type do not have the "
3587 "same elements sizes";
3588 }
3589
3590 return mlir::success();
3591}
3592
3593//===----------------------------------------------------------------------===//
3594// LabelOp Definitions
3595//===----------------------------------------------------------------------===//
3596
3597LogicalResult cir::LabelOp::verify() {
3598 mlir::Operation *op = getOperation();
3599 mlir::Block *blk = op->getBlock();
3600 if (&blk->front() != op)
3601 return emitError() << "must be the first operation in a block";
3602
3603 return mlir::success();
3604}
3605
3606//===----------------------------------------------------------------------===//
3607// IncOp
3608//===----------------------------------------------------------------------===//
3609
3610OpFoldResult cir::IncOp::fold(FoldAdaptor adaptor) {
3611 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3612 return adaptor.getInput();
3613 return {};
3614}
3615
3616//===----------------------------------------------------------------------===//
3617// DecOp
3618//===----------------------------------------------------------------------===//
3619
3620OpFoldResult cir::DecOp::fold(FoldAdaptor adaptor) {
3621 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3622 return adaptor.getInput();
3623 return {};
3624}
3625
3626//===----------------------------------------------------------------------===//
3627// MinusOp
3628//===----------------------------------------------------------------------===//
3629
3630OpFoldResult cir::MinusOp::fold(FoldAdaptor adaptor) {
3631 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3632 return adaptor.getInput();
3633
3634 // Fold with constant inputs. Floating-point negation is handled by
3635 // cir::FNegOp.
3636 if (auto intAttr =
3637 mlir::dyn_cast_if_present<cir::IntAttr>(adaptor.getInput())) {
3638 APInt val = intAttr.getValue();
3639 val.negate();
3640 return cir::IntAttr::get(getType(), val);
3641 }
3642
3643 return {};
3644}
3645
3646//===----------------------------------------------------------------------===//
3647// FNegOp
3648//===----------------------------------------------------------------------===//
3649
3650OpFoldResult cir::FNegOp::fold(FoldAdaptor adaptor) {
3651 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3652 return adaptor.getInput();
3653
3654 // Fold with constant inputs.
3655 if (auto fpAttr =
3656 mlir::dyn_cast_if_present<cir::FPAttr>(adaptor.getInput())) {
3657 APFloat val = fpAttr.getValue();
3658 val.changeSign();
3659 return cir::FPAttr::get(getType(), val);
3660 }
3661
3662 return {};
3663}
3664
3665//===----------------------------------------------------------------------===//
3666// NotOp
3667//===----------------------------------------------------------------------===//
3668
3669OpFoldResult cir::NotOp::fold(FoldAdaptor adaptor) {
3670 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3671 return adaptor.getInput();
3672
3673 // not(not(x)) -> x is handled by the Involution trait.
3674
3675 // Fold with constant inputs.
3676 if (mlir::Attribute attr = adaptor.getInput()) {
3677 if (auto intAttr = mlir::dyn_cast<cir::IntAttr>(attr)) {
3678 APInt val = intAttr.getValue();
3679 val.flipAllBits();
3680 return cir::IntAttr::get(getType(), val);
3681 }
3682 if (auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr))
3683 return cir::BoolAttr::get(getContext(), !boolAttr.getValue());
3684 }
3685
3686 return {};
3687}
3688
3689//===----------------------------------------------------------------------===//
3690// BaseClassAddrOp & DerivedClassAddrOp
3691//===----------------------------------------------------------------------===//
3692
3693LogicalResult cir::BaseClassAddrOp::verify() {
3694 if (getSrcAddr().getType().getAddrSpace() != getType().getAddrSpace())
3695 return emitOpError() << "address space mismatch";
3696 return mlir::success();
3697}
3698
3699LogicalResult cir::DerivedClassAddrOp::verify() {
3700 if (getSrcAddr().getType().getAddrSpace() != getType().getAddrSpace())
3701 return emitOpError() << "address space mismatch";
3702 return mlir::success();
3703}
3704
3705//===----------------------------------------------------------------------===//
3706// BaseDataMemberOp & DerivedDataMemberOp
3707//===----------------------------------------------------------------------===//
3708
3709static LogicalResult verifyMemberPtrCast(Operation *op, mlir::Value src,
3710 mlir::Type resultTy) {
3711 // Let the operand type be T1 C1::*, let the result type be T2 C2::*.
3712 // Verify that T1 and T2 are the same type.
3713 mlir::Type inputMemberTy;
3714 mlir::Type resultMemberTy;
3715 if (mlir::isa<cir::DataMemberType>(src.getType())) {
3716 inputMemberTy =
3717 mlir::cast<cir::DataMemberType>(src.getType()).getMemberTy();
3718 resultMemberTy = mlir::cast<cir::DataMemberType>(resultTy).getMemberTy();
3719 }
3721 if (inputMemberTy != resultMemberTy)
3722 return op->emitOpError()
3723 << "member types of the operand and the result do not match";
3724
3725 return mlir::success();
3726}
3727
3728LogicalResult cir::BaseDataMemberOp::verify() {
3729 return verifyMemberPtrCast(getOperation(), getSrc(), getType());
3730}
3731
3732LogicalResult cir::DerivedDataMemberOp::verify() {
3733 return verifyMemberPtrCast(getOperation(), getSrc(), getType());
3734}
3735
3736//===----------------------------------------------------------------------===//
3737// BaseMethodOp & DerivedMethodOp
3738//===----------------------------------------------------------------------===//
3739
3740LogicalResult cir::BaseMethodOp::verify() {
3741 return verifyMemberPtrCast(getOperation(), getSrc(), getType());
3742}
3743
3744LogicalResult cir::DerivedMethodOp::verify() {
3745 return verifyMemberPtrCast(getOperation(), getSrc(), getType());
3746}
3747
3748//===----------------------------------------------------------------------===//
3749// AwaitOp
3750//===----------------------------------------------------------------------===//
3751
3752void cir::AwaitOp::build(OpBuilder &builder, OperationState &result,
3753 cir::AwaitKind kind, BuilderCallbackRef readyBuilder,
3754 BuilderCallbackRef suspendBuilder,
3755 BuilderCallbackRef resumeBuilder) {
3756 result.addAttribute(getKindAttrName(result.name),
3757 cir::AwaitKindAttr::get(builder.getContext(), kind));
3758 {
3759 OpBuilder::InsertionGuard guard(builder);
3760 Region *readyRegion = result.addRegion();
3761 builder.createBlock(readyRegion);
3762 readyBuilder(builder, result.location);
3763 }
3764
3765 {
3766 OpBuilder::InsertionGuard guard(builder);
3767 Region *suspendRegion = result.addRegion();
3768 builder.createBlock(suspendRegion);
3769 suspendBuilder(builder, result.location);
3770 }
3771
3772 {
3773 OpBuilder::InsertionGuard guard(builder);
3774 Region *resumeRegion = result.addRegion();
3775 builder.createBlock(resumeRegion);
3776 resumeBuilder(builder, result.location);
3777 }
3778}
3779
3780void cir::AwaitOp::getSuccessorRegions(
3781 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &regions) {
3782 assert(point.isParent() || point.getTerminatorPredecessorOrNull());
3783
3784 // Execution always starts in the ready region.
3785 if (point.isParent()) {
3786 regions.emplace_back(&getReady());
3787 return;
3788 }
3789
3790 mlir::Region *parentRegion =
3791 point.getTerminatorPredecessorOrNull()->getParentRegion();
3792
3793 // Branching from ready: the cir.condition terminating it selects between
3794 // suspending and resuming. Keep in sync with
3795 // ConditionOp::getSuccessorRegions.
3796 //
3797 // TODO: retrieve information from the promise and only push the
3798 // necessary ones. Example: `std::suspend_never` on initial or final
3799 // await's might allow suspend region to be skipped.
3800 if (&getReady() == parentRegion) {
3801 regions.emplace_back(&getResume());
3802 regions.emplace_back(&getSuspend());
3803 return;
3804 }
3805
3806 // Branching from suspend: continue in resume once the coroutine is resumed
3807 // (or immediately if suspension is vetoed), or exit to the parent operation
3808 // if it stays suspended or is destroyed.
3809 if (&getSuspend() == parentRegion) {
3810 regions.emplace_back(&getResume());
3811 regions.emplace_back(getOperation());
3812 return;
3813 }
3814
3815 // Branching from resume: exit to the parent operation.
3816 regions.emplace_back(getOperation());
3817}
3818
3819LogicalResult cir::AwaitOp::verify() {
3820 if (!isa<ConditionOp>(this->getReady().back().getTerminator()))
3821 return emitOpError("ready region must end with cir.condition");
3822 if (this->getSuspend().empty())
3823 return emitOpError("suspend region must not be empty");
3824 if (!isa<CoroSuspendPoint>(this->getSuspend().back().getTerminator()))
3825 return emitOpError("suspend region must end with cir.coro.suspend_point");
3826 return success();
3827}
3828
3829//===----------------------------------------------------------------------===//
3830// CoReturnOp
3831//===----------------------------------------------------------------------===//
3832
3833LogicalResult cir::CoReturnOp::verify() {
3834 mlir::Operation *coRet = getOperation();
3835 auto coroutine = coRet->getParentOfType<CoroutineOp>();
3836 if (!coroutine.getBody().isAncestor(getOperation()->getParentRegion()))
3837 return emitOpError("must be inside the cir.coroutine body region");
3838 return success();
3839}
3840
3841//===----------------------------------------------------------------------===//
3842// CoroutineOp
3843//===----------------------------------------------------------------------===//
3844
3845void cir::CoroutineOp::build(OpBuilder &builder, OperationState &result,
3846 BuilderCallbackRef initialSuspendBuilder,
3847 BuilderCallbackRef bodyBuilder,
3848 BuilderCallbackRef finalSuspendBuilder,
3849 BuilderCallbackRef destroyBuilder,
3850 BuilderCallbackRef exitBuilder) {
3851 {
3852 OpBuilder::InsertionGuard guard(builder);
3853 Region *initialRegion = result.addRegion();
3854 builder.createBlock(initialRegion);
3855 initialSuspendBuilder(builder, result.location);
3856 }
3857
3858 {
3859 OpBuilder::InsertionGuard guard(builder);
3860 Region *bodyRegion = result.addRegion();
3861 builder.createBlock(bodyRegion);
3862 bodyBuilder(builder, result.location);
3863 }
3864
3865 {
3866 OpBuilder::InsertionGuard guard(builder);
3867 Region *finalRegion = result.addRegion();
3868 builder.createBlock(finalRegion);
3869 finalSuspendBuilder(builder, result.location);
3870 }
3871
3872 {
3873 OpBuilder::InsertionGuard guard(builder);
3874 Region *destroyRegion = result.addRegion();
3875 builder.createBlock(destroyRegion);
3876 destroyBuilder(builder, result.location);
3877 }
3878
3879 {
3880 OpBuilder::InsertionGuard guard(builder);
3881 Region *exitRegion = result.addRegion();
3882 builder.createBlock(exitRegion);
3883 exitBuilder(builder, result.location);
3884 }
3885}
3886
3887void cir::CoroutineOp::getSuccessorRegions(
3888 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &regions) {
3889 // The parent op always enters through initial_suspend get_return_object()
3890 // (if present) and the init await always run first.
3891 if (point.isParent()) {
3892 regions.emplace_back(&getInitialSuspend());
3893 return;
3894 }
3895
3896 mlir::Region *parent =
3897 point.getTerminatorPredecessorOrNull()->getParentRegion();
3898
3899 // initial_suspend either falls into body (resumed, or never actually
3900 // suspended because await_ready() was true), exits directly, or reaches
3901 // destroy when the coroutine is destroyed while suspended at its initial
3902 // suspend point.
3903 if (parent == &getInitialSuspend()) {
3904 regions.emplace_back(&getBody());
3905 regions.emplace_back(&getExit());
3906 regions.emplace_back(&getDestroy());
3907 return;
3908 }
3909
3910 // body can fall through into final_suspend (co_return), exit directly
3911 // from any suspend_point inside it that just suspends, or reach destroy,
3912 // either from a suspend_point being destroyed, or from an exception
3913 // escaping body's own catch-all.
3914 if (parent == &getBody()) {
3915 regions.emplace_back(&getFinalSuspend());
3916 regions.emplace_back(&getExit()); // any suspend_point inside body
3917 regions.emplace_back(&getDestroy()); // destroy() on any suspend inside body
3918 return;
3919 }
3920
3921 // final_suspend's only live edge in valid programs is destroy. Resuming
3922 // past the final suspend is UB. The ready-immediately edge to exit is
3923 // kept for structural symmetry with the other two suspend regions even
3924 // though it's effectively dead.
3925 if (parent == &getFinalSuspend()) {
3926 regions.emplace_back(
3927 &getDestroy()); // the only real exit from final_suspend
3928 regions.emplace_back(&getExit()); // ready==true edge, rarely taken
3929 return;
3930 }
3931
3932 // destroy has two possible outcomes depending on why it was entered:
3933 // ordinary destroy dispatch falls through to exit (normal return); an
3934 // exception that reached destroy needs to keep propagating instead, i.e.
3935 // leave the whole op rather than go through exit's cir.return.
3936 if (parent == &getDestroy()) {
3937 regions.emplace_back(&getExit());
3938 regions.push_back(RegionSuccessor(getOperation())); // unwind out of the op
3939 return;
3940 }
3941 // exit always terminates the op there's no region it loops back into.
3942 if (parent == &getExit()) {
3943 regions.emplace_back(getOperation());
3944 return;
3945 }
3946}
3947
3948mlir::ValueRange
3949cir::CoroutineOp::getSuccessorInputs(RegionSuccessor successor) {
3950 return ValueRange();
3951}
3952
3953LogicalResult cir::CoroutineOp::verify() {
3954 mlir::Region &initialSuspend = getInitialSuspend();
3955 mlir::Region &body = getBody();
3956 mlir::Region &finalSuspend = getFinalSuspend();
3957 mlir::Region &destroy = getDestroy();
3958 mlir::Region &exit = getExit();
3959
3960 // initial_suspend must contain exactly one 'init'-kind cir.await an
3961 // optional prelude of ordinary statements (get_return_object() and
3962 // similar) is allowed before it, but no *other* await may appear.
3963 int initAwaitCount = 0;
3964 bool hasInvalidAwait = false;
3965
3966 initialSuspend.walk([&](Operation *op) {
3967 auto awaitOp = mlir::dyn_cast<AwaitOp>(op);
3968 if (!awaitOp)
3969 return mlir::WalkResult::advance();
3970
3971 if (awaitOp.getKind() == cir::AwaitKind::Init)
3972 ++initAwaitCount;
3973 else
3974 hasInvalidAwait = true;
3975
3976 if (initAwaitCount > 1 || hasInvalidAwait)
3977 return mlir::WalkResult::interrupt();
3978
3979 return mlir::WalkResult::advance();
3980 });
3981
3982 if (hasInvalidAwait)
3983 return emitOpError("'initial_suspend' must not contain any cir.await other "
3984 "than the 'init' one");
3985 if (initAwaitCount != 1)
3986 return emitOpError(
3987 "must have exactly one 'init' cir.await in 'initial_suspend'");
3988
3989 // final_suspend must contain only one or zero 'final'-kind cir.await
3990 int finalAwaitCount = 0;
3991 hasInvalidAwait = false;
3992
3993 finalSuspend.walk([&](Operation *op) {
3994 auto awaitOp = mlir::dyn_cast<AwaitOp>(op);
3995 if (!awaitOp)
3996 return mlir::WalkResult::advance();
3997
3998 if (awaitOp.getKind() == cir::AwaitKind::Final)
3999 ++finalAwaitCount;
4000 else
4001 hasInvalidAwait = true;
4002
4003 if (finalAwaitCount > 1 || hasInvalidAwait)
4004 return mlir::WalkResult::interrupt();
4005
4006 return mlir::WalkResult::advance();
4007 });
4008
4009 if (hasInvalidAwait)
4010 return emitOpError("'final_suspend' must not contain any cir.await other "
4011 "than the 'final' one");
4012 if (finalAwaitCount > 1)
4013 return emitOpError(
4014 "must have one or zero 'final' cir.await in 'final_suspend'");
4015
4016 // Each region must end with the terminator its role requires:
4017 // initial_suspend/final_suspend/destroy yield back into cir.coroutine's
4018 // own control flow, body ends in a cir.co_return (or a plain yield if
4019 // some path never reaches one), and exit actually returns from the
4020 // function.
4021 if (initialSuspend.empty() || initialSuspend.back().empty())
4022 return emitOpError("initial_suspend region must not be empty");
4023 if (!isa<YieldOp>(initialSuspend.back().back()))
4024 return emitOpError("'initial_suspend' must end with cir.yield");
4025
4026 if (body.empty() || body.back().empty())
4027 return emitOpError("'body' region must not be empty");
4028 if (!isa<YieldOp, CoReturnOp>(body.back().back()))
4029 return emitOpError("'body' must end with cir.yield or cir.co_return");
4030
4031 if (finalSuspend.empty() || finalSuspend.back().empty())
4032 return emitOpError("'final_suspend' region must not be empty");
4033 if (!isa<YieldOp>(finalSuspend.back().back()))
4034 return emitOpError("'final_suspend' must end with cir.yield");
4035
4036 if (destroy.empty() || destroy.back().empty())
4037 return emitOpError("'destroy' region must not be empty");
4038 if (!isa<YieldOp>(destroy.back().back()))
4039 return emitOpError("'destroy' must end with cir.yield");
4040
4041 if (exit.empty() || exit.back().empty())
4042 return emitOpError("'exit' region must not be empty");
4043 if (!isa<ReturnOp>(exit.back().back()))
4044 return emitOpError("'exit' must end with cir.return");
4045
4046 return mlir::success();
4047}
4048
4049//===----------------------------------------------------------------------===//
4050// CopyOp Definitions
4051//===----------------------------------------------------------------------===//
4052
4053// Prints the pointer type(s) for a `cir.copy`. `src` and `dst` share the same
4054// pointee type but may differ in address space; a single type is printed when
4055// they match, otherwise both are printed (`src` first).
4056void cir::printCopyTypes(mlir::OpAsmPrinter &printer, mlir::Operation *,
4057 mlir::Type srcType, mlir::Type dstType) {
4058 printer.printType(srcType);
4059 if (srcType != dstType) {
4060 printer << ", ";
4061 printer.printType(dstType);
4062 }
4063}
4064
4065mlir::ParseResult cir::parseCopyTypes(mlir::OpAsmParser &parser,
4066 mlir::Type &srcType,
4067 mlir::Type &dstType) {
4068 if (parser.parseType(srcType))
4069 return mlir::failure();
4070 if (parser.parseOptionalComma().succeeded()) {
4071 if (parser.parseType(dstType))
4072 return mlir::failure();
4073 } else {
4074 dstType = srcType;
4075 }
4076 return mlir::success();
4077}
4078
4079LogicalResult cir::CopyOp::verify() {
4080 // The pointee types of `src` and `dst` are guaranteed to match by the
4081 // SameOperandsPointeeType trait; they may still differ in address space.
4082
4083 // A data layout is required for us to know the number of bytes to be copied.
4084 if (!getType().getPointee().hasTrait<DataLayoutTypeInterface::Trait>())
4085 return emitError() << "missing data layout for pointee type";
4086
4087 if (getSkipTailPadding() &&
4088 !mlir::isa<cir::RecordType>(getType().getPointee()))
4089 return emitError()
4090 << "skip_tail_padding is only valid for record pointee types";
4091
4092 return mlir::success();
4093}
4094
4095//===----------------------------------------------------------------------===//
4096// PtrMaskOp Definitions
4097//===----------------------------------------------------------------------===//
4098
4099LogicalResult cir::PtrMaskOp::verify() {
4100 mlir::DataLayout layout = mlir::DataLayout::closest(*this);
4101 std::optional<uint64_t> indexWidth =
4102 layout.getTypeIndexBitwidth(getPtr().getType());
4103 if (!indexWidth)
4104 return emitOpError() << "pointer has no index width";
4105
4106 uint64_t maskWidth = getMask().getType().getWidth();
4107 if (maskWidth != *indexWidth)
4108 return emitOpError() << "mask width " << maskWidth
4109 << " must equal the pointer index width "
4110 << *indexWidth;
4111
4112 return mlir::success();
4113}
4114
4115//===----------------------------------------------------------------------===//
4116// GetRuntimeMemberOp Definitions
4117//===----------------------------------------------------------------------===//
4118
4119LogicalResult cir::GetRuntimeMemberOp::verify() {
4120 cir::DataMemberType memberPtrTy = getMember().getType();
4121
4122 if (getAddr().getType().getPointee() != memberPtrTy.getClassTy())
4123 return emitError() << "record type does not match the member pointer type";
4124 if (getType().getPointee() != memberPtrTy.getMemberTy())
4125 return emitError() << "result type does not match the member pointer type";
4126 if (getType().getAddrSpace() != getAddr().getType().getAddrSpace())
4127 return emitError()
4128 << "result address space does not match the object address space";
4129 return mlir::success();
4130}
4131
4132//===----------------------------------------------------------------------===//
4133// GetMethodOp Definitions
4134//===----------------------------------------------------------------------===//
4135
4136LogicalResult cir::GetMethodOp::verify() {
4137 cir::MethodType methodTy = getMethod().getType();
4138
4139 // Assume objectTy is !cir.ptr<!T>
4140 cir::PointerType objectPtrTy = getObject().getType();
4141 mlir::Type objectTy = objectPtrTy.getPointee();
4142
4143 if (methodTy.getClassTy() != objectTy)
4144 return emitError() << "method class type and object type do not match";
4145
4146 // Assume methodFuncTy is !cir.func<!Ret (!Args)>
4147 auto calleeTy = mlir::cast<cir::FuncType>(getCallee().getType().getPointee());
4148 cir::FuncType methodFuncTy = methodTy.getMemberFuncTy();
4149
4150 // We verify at here that calleeTy is !cir.func<!Ret (!cir.ptr<!void>, !Args)>
4151 // Note that the first parameter type of the callee is !cir.ptr<!void> instead
4152 // of !cir.ptr<!T> because the "this" pointer may be adjusted before calling
4153 // the callee.
4154
4155 if (methodFuncTy.getReturnType() != calleeTy.getReturnType())
4156 return emitError()
4157 << "method return type and callee return type do not match";
4158
4159 llvm::ArrayRef<mlir::Type> calleeArgsTy = calleeTy.getInputs();
4160 llvm::ArrayRef<mlir::Type> methodFuncArgsTy = methodFuncTy.getInputs();
4161
4162 if (calleeArgsTy.empty())
4163 return emitError() << "callee parameter list lacks receiver object ptr";
4164
4165 auto calleeThisArgPtrTy = mlir::dyn_cast<cir::PointerType>(calleeArgsTy[0]);
4166 if (!calleeThisArgPtrTy ||
4167 !mlir::isa<cir::VoidType>(calleeThisArgPtrTy.getPointee())) {
4168 return emitError()
4169 << "the first parameter of callee must be a void pointer";
4170 }
4171
4172 if (calleeArgsTy.size() != methodFuncArgsTy.size())
4173 return emitError() << "callee and method parameter counts do not match";
4174
4175 if (calleeArgsTy.size() > 1 &&
4176 calleeArgsTy.slice(1) != methodFuncArgsTy.slice(1))
4177 return emitError()
4178 << "callee parameters and method parameters do not match";
4179
4180 return mlir::success();
4181}
4182
4183//===----------------------------------------------------------------------===//
4184// GetMemberOp Definitions
4185//===----------------------------------------------------------------------===//
4186
4187static mlir::Type memberPointeeType(cir::RecordType recordTy, unsigned idx) {
4188 return cir::memberStorageType(recordTy.getMembers()[idx]);
4189}
4190
4191LogicalResult cir::GetMemberOp::verify() {
4192 const auto recordTy = dyn_cast<RecordType>(getAddrTy().getPointee());
4193 if (!recordTy)
4194 return emitError() << "expected pointer to a record type";
4195
4196 if (recordTy.getMembers().size() <= getIndex())
4197 return emitError() << "member index out of bounds";
4198
4199 mlir::Type pointeeTy = memberPointeeType(recordTy, getIndex());
4200 if (!pointeeTy)
4201 return emitError() << "member owns no storage to point at";
4202
4203 if (pointeeTy != getType().getPointee())
4204 return emitError() << "member type mismatch";
4205
4206 if (getAddrTy().getAddrSpace() != getType().getAddrSpace())
4207 return emitError() << "address space mismatch";
4208
4209 return mlir::success();
4210}
4211
4212//===----------------------------------------------------------------------===//
4213// ExtractMemberOp Definitions
4214//===----------------------------------------------------------------------===//
4215
4216LogicalResult cir::ExtractMemberOp::verify() {
4217 if (mlir::isa<cir::UnionType>(getRecord().getType()))
4218 return emitError()
4219 << "cir.extract_member currently does not support unions";
4220 auto structTy = mlir::cast<cir::StructType>(getRecord().getType());
4221 if (structTy.getMembers().size() <= getIndex())
4222 return emitError() << "member index out of bounds";
4223 mlir::Type memberTy = structTy.getMembers()[getIndex()];
4224 if (mlir::isa<cir::BitFieldType>(memberTy))
4225 return emitError() << "cir.extract_member does not support bit-fields";
4226 if (memberTy != getType())
4227 return emitError() << "member type mismatch";
4228 return mlir::success();
4229}
4230
4231//===----------------------------------------------------------------------===//
4232// InsertMemberOp Definitions
4233//===----------------------------------------------------------------------===//
4234
4235LogicalResult cir::InsertMemberOp::verify() {
4236 if (mlir::isa<cir::UnionType>(getRecord().getType()))
4237 return emitError() << "cir.insert_member currently does not support unions";
4238 auto structTy = mlir::cast<cir::StructType>(getRecord().getType());
4239 if (structTy.getMembers().size() <= getIndex())
4240 return emitError() << "member index out of bounds";
4241 mlir::Type memberTy = structTy.getMembers()[getIndex()];
4242 if (mlir::isa<cir::BitFieldType>(memberTy))
4243 return emitError() << "cir.insert_member does not support bit-fields";
4244 if (memberTy != getValue().getType())
4245 return emitError() << "member type mismatch";
4246 // The op trait already checks that the types of $result and $record match.
4247 return mlir::success();
4248}
4249
4250//===----------------------------------------------------------------------===//
4251// VecCreateOp
4252//===----------------------------------------------------------------------===//
4253
4254OpFoldResult cir::VecCreateOp::fold(FoldAdaptor adaptor) {
4255 if (llvm::any_of(getElements(), [](mlir::Value value) {
4256 return !value.getDefiningOp<cir::ConstantOp>();
4257 }))
4258 return {};
4259
4260 return cir::ConstVectorAttr::get(
4261 getType(), mlir::ArrayAttr::get(getContext(), adaptor.getElements()));
4262}
4263
4264LogicalResult cir::VecCreateOp::verify() {
4265 // Verify that the number of arguments matches the number of elements in the
4266 // vector, and that the type of all the arguments matches the type of the
4267 // elements in the vector.
4268 const cir::VectorType vecTy = getType();
4269 if (vecTy.isScalable())
4270 return emitOpError() << "scalable vectors are not supported";
4271
4272 if (getElements().size() != vecTy.getFixedSize()) {
4273 return emitOpError() << "operand count of " << getElements().size()
4274 << " doesn't match vector type " << vecTy
4275 << " element count of " << vecTy.getFixedSize();
4276 }
4277
4278 const mlir::Type elementType = vecTy.getElementType();
4279 for (const mlir::Value element : getElements()) {
4280 if (element.getType() != elementType) {
4281 return emitOpError() << "operand type " << element.getType()
4282 << " doesn't match vector element type "
4283 << elementType;
4284 }
4285 }
4286
4287 return success();
4288}
4289
4290//===----------------------------------------------------------------------===//
4291// VecExtractOp
4292//===----------------------------------------------------------------------===//
4293
4294OpFoldResult cir::VecExtractOp::fold(FoldAdaptor adaptor) {
4295 const auto vectorAttr =
4296 llvm::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec());
4297 if (!vectorAttr)
4298 return {};
4299
4300 const auto indexAttr =
4301 llvm::dyn_cast_if_present<cir::IntAttr>(adaptor.getIndex());
4302 if (!indexAttr)
4303 return {};
4304
4305 const mlir::ArrayAttr elements = vectorAttr.getElts();
4306 const uint64_t index = indexAttr.getUInt();
4307 if (index >= elements.size())
4308 return {};
4309
4310 return elements[index];
4311}
4312
4313//===----------------------------------------------------------------------===//
4314// CmpOp
4315//===----------------------------------------------------------------------===//
4316
4317LogicalResult cir::CmpOp::verify() {
4318 if (getFenvAttr() && !cir::isAnyFloatingPointType(getLhs().getType()))
4319 return emitOpError()
4320 << "'fenv' is only valid for floating-point comparisons";
4321 return success();
4322}
4323
4324//===----------------------------------------------------------------------===//
4325// VecCmpOp
4326//===----------------------------------------------------------------------===//
4327
4328LogicalResult cir::VecCmpOp::verify() {
4329 if (getFenvAttr() && !cir::isFPOrVectorOfFPType(getLhs().getType()))
4330 return emitOpError()
4331 << "'fenv' is only valid for floating-point comparisons";
4332 return success();
4333}
4334
4335OpFoldResult cir::VecCmpOp::fold(FoldAdaptor adaptor) {
4336 // Do not fold when fenv is present.
4337 // TODO(cir): This is overly conservative. We could fold comparisons as long
4338 // as we can prove that the operation wouldn't raise exceptions or
4339 // when the fenv attribute does not require strict exception
4340 // semantics.
4341 if (getFenvAttr())
4342 return {};
4343
4344 auto lhsVecAttr =
4345 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getLhs());
4346 auto rhsVecAttr =
4347 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getRhs());
4348 if (!lhsVecAttr || !rhsVecAttr)
4349 return {};
4350
4351 mlir::Type inputElemTy =
4352 mlir::cast<cir::VectorType>(lhsVecAttr.getType()).getElementType();
4353 if (!isAnyIntegerOrFloatingPointType(inputElemTy))
4354 return {};
4355
4356 cir::CmpOpKind opKind = adaptor.getKind();
4357 mlir::ArrayAttr lhsVecElhs = lhsVecAttr.getElts();
4358 mlir::ArrayAttr rhsVecElhs = rhsVecAttr.getElts();
4359 uint64_t vecSize = lhsVecElhs.size();
4360
4361 SmallVector<mlir::Attribute, 16> elements(vecSize);
4362 bool isIntAttr = vecSize && mlir::isa<cir::IntAttr>(lhsVecElhs[0]);
4363 bool isUnsignedInt =
4364 isIntAttr && mlir::cast<cir::IntType>(inputElemTy).isUnsigned();
4365 for (uint64_t i = 0; i < vecSize; i++) {
4366 mlir::Attribute lhsAttr = lhsVecElhs[i];
4367 mlir::Attribute rhsAttr = rhsVecElhs[i];
4368 bool cmpResult = false;
4369 switch (opKind) {
4370 case cir::CmpOpKind::lt: {
4371 if (isIntAttr) {
4372 if (isUnsignedInt)
4373 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() <
4374 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
4375 else
4376 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <
4377 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
4378 } else {
4379 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <
4380 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
4381 }
4382 break;
4383 }
4384 case cir::CmpOpKind::le: {
4385 if (isIntAttr) {
4386 if (isUnsignedInt)
4387 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() <=
4388 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
4389 else
4390 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <=
4391 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
4392 } else {
4393 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <=
4394 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
4395 }
4396 break;
4397 }
4398 case cir::CmpOpKind::gt: {
4399 if (isIntAttr) {
4400 if (isUnsignedInt)
4401 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() >
4402 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
4403 else
4404 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >
4405 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
4406 } else {
4407 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >
4408 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
4409 }
4410 break;
4411 }
4412 case cir::CmpOpKind::ge: {
4413 if (isIntAttr) {
4414 if (isUnsignedInt)
4415 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() >=
4416 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
4417 else
4418 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >=
4419 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
4420 } else {
4421 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >=
4422 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
4423 }
4424 break;
4425 }
4426 case cir::CmpOpKind::eq: {
4427 if (isIntAttr) {
4428 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() ==
4429 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
4430 } else {
4431 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() ==
4432 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
4433 }
4434 break;
4435 }
4436 case cir::CmpOpKind::ne: {
4437 if (isIntAttr) {
4438 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() !=
4439 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
4440 } else {
4441 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() !=
4442 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
4443 }
4444 break;
4445 }
4446 case cir::CmpOpKind::one: {
4447 llvm::APFloat::cmpResult cr =
4448 mlir::cast<cir::FPAttr>(lhsAttr).getValue().compare(
4449 mlir::cast<cir::FPAttr>(rhsAttr).getValue());
4450 cmpResult =
4451 cr != llvm::APFloat::cmpUnordered && cr != llvm::APFloat::cmpEqual;
4452 break;
4453 }
4454 case cir::CmpOpKind::uno: {
4455 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue().compare(
4456 mlir::cast<cir::FPAttr>(rhsAttr).getValue()) ==
4457 llvm::APFloat::cmpUnordered;
4458 break;
4459 }
4460 }
4461
4462 // A true result is all bits set (-1 in two's complement), and a false
4463 // result is all bits clear. For a 1-bit element type these are the same
4464 // bit pattern as 1 and 0, respectively.
4465 elements[i] =
4466 cir::IntAttr::get(getType().getElementType(), cmpResult ? -1LL : 0LL);
4467 }
4468
4469 return cir::ConstVectorAttr::get(
4470 getType(), mlir::ArrayAttr::get(getContext(), elements));
4471}
4472
4473//===----------------------------------------------------------------------===//
4474// VecShuffleOp
4475//===----------------------------------------------------------------------===//
4476
4477OpFoldResult cir::VecShuffleOp::fold(FoldAdaptor adaptor) {
4478 auto vec1Attr =
4479 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec1());
4480 auto vec2Attr =
4481 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec2());
4482 if (!vec1Attr || !vec2Attr)
4483 return {};
4484
4485 mlir::Type vec1ElemTy =
4486 mlir::cast<cir::VectorType>(vec1Attr.getType()).getElementType();
4487
4488 mlir::ArrayAttr vec1Elts = vec1Attr.getElts();
4489 mlir::ArrayAttr vec2Elts = vec2Attr.getElts();
4490 mlir::ArrayAttr indicesElts = adaptor.getIndices();
4491
4493 elements.reserve(indicesElts.size());
4494
4495 uint64_t vec1Size = vec1Elts.size();
4496 for (const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
4497 if (idxAttr.getSInt() == -1) {
4498 elements.push_back(cir::UndefAttr::get(vec1ElemTy));
4499 continue;
4500 }
4501
4502 uint64_t idxValue = idxAttr.getUInt();
4503 elements.push_back(idxValue < vec1Size ? vec1Elts[idxValue]
4504 : vec2Elts[idxValue - vec1Size]);
4505 }
4506
4507 return cir::ConstVectorAttr::get(
4508 getType(), mlir::ArrayAttr::get(getContext(), elements));
4509}
4510
4511LogicalResult cir::VecShuffleOp::verify() {
4512 if (getVec1().getType().isScalable() || getVec2().getType().isScalable() ||
4513 getResult().getType().isScalable())
4514 return emitOpError() << "scalable vectors are not supported";
4515
4516 // The number of elements in the indices array must match the number of
4517 // elements in the result type.
4518 if (getIndices().size() != getResult().getType().getFixedSize()) {
4519 return emitOpError() << ": the number of elements in " << getIndices()
4520 << " and " << getResult().getType() << " don't match";
4521 }
4522
4523 // The element types of the two input vectors and of the result type must
4524 // match.
4525 if (getVec1().getType().getElementType() !=
4526 getResult().getType().getElementType()) {
4527 return emitOpError() << ": element types of " << getVec1().getType()
4528 << " and " << getResult().getType() << " don't match";
4529 }
4530
4531 const uint64_t maxValidIndex = getVec1().getType().getFixedSize() +
4532 getVec2().getType().getFixedSize() - 1;
4533 if (llvm::any_of(
4534 getIndices().getAsRange<cir::IntAttr>(), [&](cir::IntAttr idxAttr) {
4535 return idxAttr.getSInt() != -1 && idxAttr.getUInt() > maxValidIndex;
4536 })) {
4537 return emitOpError() << ": index for __builtin_shufflevector must be "
4538 "less than the total number of vector elements";
4539 }
4540 return success();
4541}
4542
4543//===----------------------------------------------------------------------===//
4544// VecShuffleDynamicOp
4545//===----------------------------------------------------------------------===//
4546
4547OpFoldResult cir::VecShuffleDynamicOp::fold(FoldAdaptor adaptor) {
4548 mlir::Attribute vec = adaptor.getVec();
4549 mlir::Attribute indices = adaptor.getIndices();
4550 if (mlir::isa_and_nonnull<cir::ConstVectorAttr>(vec) &&
4551 mlir::isa_and_nonnull<cir::ConstVectorAttr>(indices)) {
4552 auto vecAttr = mlir::cast<cir::ConstVectorAttr>(vec);
4553 auto indicesAttr = mlir::cast<cir::ConstVectorAttr>(indices);
4554
4555 mlir::ArrayAttr vecElts = vecAttr.getElts();
4556 mlir::ArrayAttr indicesElts = indicesAttr.getElts();
4557
4558 const uint64_t numElements = vecElts.size();
4559
4561 elements.reserve(numElements);
4562
4563 const uint64_t maskBits = llvm::NextPowerOf2(numElements - 1) - 1;
4564 for (const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
4565 uint64_t idxValue = idxAttr.getUInt();
4566 uint64_t newIdx = idxValue & maskBits;
4567 elements.push_back(vecElts[newIdx]);
4568 }
4569
4570 return cir::ConstVectorAttr::get(
4571 getType(), mlir::ArrayAttr::get(getContext(), elements));
4572 }
4573
4574 return {};
4575}
4576
4577LogicalResult cir::VecShuffleDynamicOp::verify() {
4578 // The number of elements in the two input vectors must match.
4579 if (getVec().getType().getSize() !=
4580 mlir::cast<cir::VectorType>(getIndices().getType()).getSize()) {
4581 return emitOpError() << ": the number of elements in " << getVec().getType()
4582 << " and " << getIndices().getType() << " don't match";
4583 }
4584 return success();
4585}
4586
4587//===----------------------------------------------------------------------===//
4588// VecTernaryOp
4589//===----------------------------------------------------------------------===//
4590
4591LogicalResult cir::VecTernaryOp::verify() {
4592 // Verify that the condition operand has the same number of elements as the
4593 // other operands. (The automatic verification already checked that all
4594 // operands are vector types and that the second and third operands are the
4595 // same type.)
4596 if (getCond().getType().getSize() != getLhs().getType().getSize()) {
4597 return emitOpError() << ": the number of elements in "
4598 << getCond().getType() << " and " << getLhs().getType()
4599 << " don't match";
4600 }
4601 return success();
4602}
4603
4604OpFoldResult cir::VecTernaryOp::fold(FoldAdaptor adaptor) {
4605 mlir::Attribute cond = adaptor.getCond();
4606 mlir::Attribute lhs = adaptor.getLhs();
4607 mlir::Attribute rhs = adaptor.getRhs();
4608
4609 if (!mlir::isa_and_nonnull<cir::ConstVectorAttr>(cond) ||
4610 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(lhs) ||
4611 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(rhs))
4612 return {};
4613 auto condVec = mlir::cast<cir::ConstVectorAttr>(cond);
4614 auto lhsVec = mlir::cast<cir::ConstVectorAttr>(lhs);
4615 auto rhsVec = mlir::cast<cir::ConstVectorAttr>(rhs);
4616
4617 mlir::ArrayAttr condElts = condVec.getElts();
4618
4620 elements.reserve(condElts.size());
4621
4622 for (const auto &[idx, condAttr] :
4623 llvm::enumerate(condElts.getAsRange<cir::IntAttr>())) {
4624 if (condAttr.getSInt()) {
4625 elements.push_back(lhsVec.getElts()[idx]);
4626 } else {
4627 elements.push_back(rhsVec.getElts()[idx]);
4628 }
4629 }
4630
4631 cir::VectorType vecTy = getLhs().getType();
4632 return cir::ConstVectorAttr::get(
4633 vecTy, mlir::ArrayAttr::get(getContext(), elements));
4634}
4635
4636//===----------------------------------------------------------------------===//
4637// MatrixTransposeOp
4638//===----------------------------------------------------------------------===//
4639
4640LogicalResult cir::MatrixTransposeOp::verify() {
4641 cir::MatrixType valueTy = getValue().getType();
4642 cir::MatrixType resultTy = getResult().getType();
4643
4644 if ((valueTy.getElementType() != resultTy.getElementType()) ||
4645 (valueTy.getNumRows() != resultTy.getNumColumns()) ||
4646 (valueTy.getNumColumns() != resultTy.getNumRows())) {
4647 auto expectedTy =
4648 cir::MatrixType::get(valueTy.getElementType(), valueTy.getNumColumns(),
4649 valueTy.getNumRows());
4650 emitOpError() << "operand type " << valueTy << " expects result type of "
4651 << expectedTy << " but got " << resultTy;
4652 return failure();
4653 }
4654
4655 return success();
4656}
4657
4658//===----------------------------------------------------------------------===//
4659// ComplexCreateOp
4660//===----------------------------------------------------------------------===//
4661
4662LogicalResult cir::ComplexCreateOp::verify() {
4663 if (getType().getElementType() != getReal().getType()) {
4664 emitOpError()
4665 << "operand type of cir.complex.create does not match its result type";
4666 return failure();
4667 }
4668
4669 return success();
4670}
4671
4672OpFoldResult cir::ComplexCreateOp::fold(FoldAdaptor adaptor) {
4673 mlir::Attribute real = adaptor.getReal();
4674 mlir::Attribute imag = adaptor.getImag();
4675 if (!real || !imag)
4676 return {};
4677
4678 // When both of real and imag are constants, we can fold the operation into an
4679 // `#cir.const_complex` operation.
4680 auto realAttr = mlir::cast<mlir::TypedAttr>(real);
4681 auto imagAttr = mlir::cast<mlir::TypedAttr>(imag);
4682 return cir::ConstComplexAttr::get(realAttr, imagAttr);
4683}
4684
4685//===----------------------------------------------------------------------===//
4686// ComplexRealOp
4687//===----------------------------------------------------------------------===//
4688
4689LogicalResult cir::ComplexRealOp::verify() {
4690 mlir::Type operandTy = getOperand().getType();
4691 if (auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
4692 operandTy = complexOperandTy.getElementType();
4693
4694 if (getType() != operandTy) {
4695 emitOpError() << ": result type does not match operand type";
4696 return failure();
4697 }
4698
4699 return success();
4700}
4701
4702OpFoldResult cir::ComplexRealOp::fold(FoldAdaptor adaptor) {
4703 if (!mlir::isa<cir::ComplexType>(getOperand().getType()))
4704 return nullptr;
4705
4706 if (auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
4707 return complexCreateOp.getOperand(0);
4708
4709 auto complex =
4710 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
4711 return complex ? complex.getReal() : nullptr;
4712}
4713
4714//===----------------------------------------------------------------------===//
4715// ComplexImagOp
4716//===----------------------------------------------------------------------===//
4717
4718LogicalResult cir::ComplexImagOp::verify() {
4719 mlir::Type operandTy = getOperand().getType();
4720 if (auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
4721 operandTy = complexOperandTy.getElementType();
4722
4723 if (getType() != operandTy) {
4724 emitOpError() << ": result type does not match operand type";
4725 return failure();
4726 }
4727
4728 return success();
4729}
4730
4731OpFoldResult cir::ComplexImagOp::fold(FoldAdaptor adaptor) {
4732 if (!mlir::isa<cir::ComplexType>(getOperand().getType()))
4733 return nullptr;
4734
4735 if (auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
4736 return complexCreateOp.getOperand(1);
4737
4738 auto complex =
4739 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
4740 return complex ? complex.getImag() : nullptr;
4741}
4742
4743//===----------------------------------------------------------------------===//
4744// ComplexRealPtrOp
4745//===----------------------------------------------------------------------===//
4746
4747LogicalResult cir::ComplexRealPtrOp::verify() {
4748 mlir::Type resultPointeeTy = getType().getPointee();
4749 cir::PointerType operandPtrTy = getOperand().getType();
4750 auto operandPointeeTy =
4751 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
4752
4753 if (resultPointeeTy != operandPointeeTy.getElementType()) {
4754 return emitOpError() << ": result type does not match operand type";
4755 }
4756
4757 return success();
4758}
4759
4760//===----------------------------------------------------------------------===//
4761// ComplexImagPtrOp
4762//===----------------------------------------------------------------------===//
4763
4764LogicalResult cir::ComplexImagPtrOp::verify() {
4765 mlir::Type resultPointeeTy = getType().getPointee();
4766 cir::PointerType operandPtrTy = getOperand().getType();
4767 auto operandPointeeTy =
4768 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
4769
4770 if (resultPointeeTy != operandPointeeTy.getElementType()) {
4771 return emitOpError()
4772 << "cir.complex.imag_ptr result type does not match operand type";
4773 }
4774 return success();
4775}
4776
4777//===----------------------------------------------------------------------===//
4778// Bit manipulation operations
4779//===----------------------------------------------------------------------===//
4780
4781static OpFoldResult
4782foldUnaryBitOp(mlir::Attribute inputAttr,
4783 llvm::function_ref<llvm::APInt(const llvm::APInt &)> func,
4784 bool poisonZero = false) {
4785 if (mlir::isa_and_present<cir::PoisonAttr>(inputAttr)) {
4786 // Propagate poison value
4787 return inputAttr;
4788 }
4789
4790 auto input = mlir::dyn_cast_if_present<IntAttr>(inputAttr);
4791 if (!input)
4792 return nullptr;
4793
4794 llvm::APInt inputValue = input.getValue();
4795 if (poisonZero && inputValue.isZero())
4796 return cir::PoisonAttr::get(input.getType());
4797
4798 llvm::APInt resultValue = func(inputValue);
4799 return IntAttr::get(input.getType(), resultValue);
4800}
4801
4802OpFoldResult BitClrsbOp::fold(FoldAdaptor adaptor) {
4803 return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
4804 unsigned resultValue =
4805 inputValue.getBitWidth() - inputValue.getSignificantBits();
4806 return llvm::APInt(inputValue.getBitWidth(), resultValue);
4807 });
4808}
4809
4810OpFoldResult BitClzOp::fold(FoldAdaptor adaptor) {
4811 return foldUnaryBitOp(
4812 adaptor.getInput(),
4813 [](const llvm::APInt &inputValue) {
4814 unsigned resultValue = inputValue.countLeadingZeros();
4815 return llvm::APInt(inputValue.getBitWidth(), resultValue);
4816 },
4817 getPoisonZero());
4818}
4819
4820OpFoldResult BitCtzOp::fold(FoldAdaptor adaptor) {
4821 return foldUnaryBitOp(
4822 adaptor.getInput(),
4823 [](const llvm::APInt &inputValue) {
4824 return llvm::APInt(inputValue.getBitWidth(),
4825 inputValue.countTrailingZeros());
4826 },
4827 getPoisonZero());
4828}
4829
4830OpFoldResult BitFfsOp::fold(FoldAdaptor adaptor) {
4831 return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
4832 unsigned trailingZeros = inputValue.countTrailingZeros();
4833 unsigned result =
4834 trailingZeros == inputValue.getBitWidth() ? 0 : trailingZeros + 1;
4835 return llvm::APInt(inputValue.getBitWidth(), result);
4836 });
4837}
4838
4839OpFoldResult BitParityOp::fold(FoldAdaptor adaptor) {
4840 return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
4841 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount() % 2);
4842 });
4843}
4844
4845OpFoldResult BitPopcountOp::fold(FoldAdaptor adaptor) {
4846 return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
4847 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount());
4848 });
4849}
4850
4851OpFoldResult BitReverseOp::fold(FoldAdaptor adaptor) {
4852 return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
4853 return inputValue.reverseBits();
4854 });
4855}
4856
4857OpFoldResult ByteSwapOp::fold(FoldAdaptor adaptor) {
4858 return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
4859 return inputValue.byteSwap();
4860 });
4861}
4862
4863OpFoldResult RotateOp::fold(FoldAdaptor adaptor) {
4864 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()) ||
4865 mlir::isa_and_present<cir::PoisonAttr>(adaptor.getAmount())) {
4866 // Propagate poison values
4867 return cir::PoisonAttr::get(getType());
4868 }
4869
4870 auto input = mlir::dyn_cast_if_present<IntAttr>(adaptor.getInput());
4871 auto amount = mlir::dyn_cast_if_present<IntAttr>(adaptor.getAmount());
4872 if (!input && !amount)
4873 return nullptr;
4874
4875 // We could fold cir.rotate even if one of its two operands is not a constant:
4876 // - `cir.rotate left/right %0, 0` could be folded into just %0 even if %0
4877 // is not a constant.
4878 // - `cir.rotate left/right 0/0b111...111, %0` could be folded into 0 or
4879 // 0b111...111 even if %0 is not a constant.
4880
4881 llvm::APInt inputValue;
4882 if (input) {
4883 inputValue = input.getValue();
4884 if (inputValue.isZero() || inputValue.isAllOnes()) {
4885 // An input value of all 0s or all 1s will not change after rotation
4886 return input;
4887 }
4888 }
4889
4890 uint64_t amountValue;
4891 if (amount) {
4892 amountValue = amount.getValue().urem(getInput().getType().getWidth());
4893 if (amountValue == 0) {
4894 // A shift amount of 0 will not change the input value
4895 return getInput();
4896 }
4897 }
4898
4899 if (!input || !amount)
4900 return nullptr;
4901
4902 assert(inputValue.getBitWidth() == getInput().getType().getWidth() &&
4903 "input value must have the same bit width as the input type");
4904
4905 llvm::APInt resultValue;
4906 if (isRotateLeft())
4907 resultValue = inputValue.rotl(amountValue);
4908 else
4909 resultValue = inputValue.rotr(amountValue);
4910
4911 return IntAttr::get(input.getContext(), input.getType(), resultValue);
4912}
4913
4914//===----------------------------------------------------------------------===//
4915// InlineAsmOp
4916//===----------------------------------------------------------------------===//
4917
4918void cir::InlineAsmOp::print(OpAsmPrinter &p) {
4919 p << '(' << getAsmFlavor() << ", ";
4920 p.increaseIndent();
4921 p.printNewline();
4922
4923 llvm::SmallVector<std::string, 3> names{"out", "in", "in_out"};
4924 auto *nameIt = names.begin();
4925 auto *attrIt = getOperandAttrs().begin();
4926
4927 for (mlir::OperandRange ops : getAsmOperands()) {
4928 p << *nameIt << " = ";
4929
4930 p << '[';
4931 llvm::interleaveComma(llvm::make_range(ops.begin(), ops.end()), p,
4932 [&](Value value) {
4933 p.printOperand(value);
4934 p << " : " << value.getType();
4935 if (mlir::isa<mlir::UnitAttr>(*attrIt))
4936 p << " (maybe_memory)";
4937 attrIt++;
4938 });
4939 p << "],";
4940 p.printNewline();
4941 ++nameIt;
4942 }
4943
4944 p << "{";
4945 p.printString(getAsmString());
4946 p << " ";
4947 p.printString(getConstraints());
4948 p << "}";
4949 p.decreaseIndent();
4950 p << ')';
4951 if (getSideEffects())
4952 p << " side_effects";
4953
4954 p.printOptionalAttrDict(
4955 getOperation()->getDiscardableAttrDictionary().getValue());
4956
4957 if (auto v = getRes())
4958 p << " -> " << v.getType();
4959}
4960
4961void cir::InlineAsmOp::build(OpBuilder &odsBuilder, OperationState &odsState,
4962 ArrayRef<ValueRange> asmOperands,
4963 StringRef asmString, StringRef constraints,
4964 bool sideEffects, cir::AsmFlavor asmFlavor,
4965 ArrayRef<Attribute> operandAttrs) {
4966 // Set up the operands_segments for VariadicOfVariadic
4967 SmallVector<int32_t> segments;
4968 for (auto operandRange : asmOperands) {
4969 segments.push_back(operandRange.size());
4970 odsState.addOperands(operandRange);
4971 }
4972
4973 odsState.addAttribute(
4974 "operands_segments",
4975 DenseI32ArrayAttr::get(odsBuilder.getContext(), segments));
4976 odsState.addAttribute("asm_string", odsBuilder.getStringAttr(asmString));
4977 odsState.addAttribute("constraints", odsBuilder.getStringAttr(constraints));
4978 odsState.addAttribute("asm_flavor",
4979 AsmFlavorAttr::get(odsBuilder.getContext(), asmFlavor));
4980
4981 if (sideEffects)
4982 odsState.addAttribute("side_effects", odsBuilder.getUnitAttr());
4983
4984 odsState.addAttribute("operand_attrs", odsBuilder.getArrayAttr(operandAttrs));
4985}
4986
4987ParseResult cir::InlineAsmOp::parse(OpAsmParser &parser,
4988 OperationState &result) {
4990 llvm::SmallVector<int32_t> operandsGroupSizes;
4991 std::string asmString, constraints;
4992 Type resType;
4993 MLIRContext *ctxt = parser.getBuilder().getContext();
4994
4995 auto error = [&](const Twine &msg) -> LogicalResult {
4996 return parser.emitError(parser.getCurrentLocation(), msg);
4997 };
4998
4999 auto expected = [&](const std::string &c) {
5000 return error("expected '" + c + "'");
5001 };
5002
5003 if (parser.parseLParen().failed())
5004 return expected("(");
5005
5006 auto flavor = FieldParser<AsmFlavor, AsmFlavor>::parse(parser);
5007 if (failed(flavor))
5008 return error("Unknown AsmFlavor");
5009
5010 if (parser.parseComma().failed())
5011 return expected(",");
5012
5013 auto parseValue = [&](Value &v) {
5014 OpAsmParser::UnresolvedOperand op;
5015
5016 if (parser.parseOperand(op) || parser.parseColon())
5017 return error("can't parse operand");
5018
5019 Type typ;
5020 if (parser.parseType(typ).failed())
5021 return error("can't parse operand type");
5023 if (parser.resolveOperand(op, typ, tmp))
5024 return error("can't resolve operand");
5025 v = tmp[0];
5026 return mlir::success();
5027 };
5028
5029 auto parseOperands = [&](llvm::StringRef name) {
5030 if (parser.parseKeyword(name).failed())
5031 return error("expected " + name + " operands here");
5032 if (parser.parseEqual().failed())
5033 return expected("=");
5034 if (parser.parseLSquare().failed())
5035 return expected("[");
5036
5037 int size = 0;
5038 if (parser.parseOptionalRSquare().succeeded()) {
5039 operandsGroupSizes.push_back(size);
5040 if (parser.parseComma())
5041 return expected(",");
5042 return mlir::success();
5043 }
5044
5045 auto parseOperand = [&]() {
5046 Value val;
5047 if (parseValue(val).succeeded()) {
5048 result.operands.push_back(val);
5049 size++;
5050
5051 if (parser.parseOptionalLParen().failed()) {
5052 operandAttrs.push_back(mlir::DictionaryAttr::get(ctxt));
5053 return mlir::success();
5054 }
5055
5056 if (parser.parseKeyword("maybe_memory").succeeded()) {
5057 operandAttrs.push_back(mlir::UnitAttr::get(ctxt));
5058 if (parser.parseRParen())
5059 return expected(")");
5060 return mlir::success();
5061 } else {
5062 return expected("maybe_memory");
5063 }
5064 }
5065 return mlir::failure();
5066 };
5067
5068 if (parser.parseCommaSeparatedList(parseOperand).failed())
5069 return mlir::failure();
5070
5071 if (parser.parseRSquare().failed() || parser.parseComma().failed())
5072 return expected("]");
5073 operandsGroupSizes.push_back(size);
5074 return mlir::success();
5075 };
5076
5077 if (parseOperands("out").failed() || parseOperands("in").failed() ||
5078 parseOperands("in_out").failed())
5079 return error("failed to parse operands");
5080
5081 if (parser.parseLBrace())
5082 return expected("{");
5083 if (parser.parseString(&asmString))
5084 return error("asm string parsing failed");
5085 if (parser.parseString(&constraints))
5086 return error("constraints string parsing failed");
5087 if (parser.parseRBrace())
5088 return expected("}");
5089 if (parser.parseRParen())
5090 return expected(")");
5091
5092 if (parser.parseOptionalKeyword("side_effects").succeeded())
5093 result.attributes.set("side_effects", UnitAttr::get(ctxt));
5094
5095 if (parser.parseOptionalAttrDict(result.attributes).failed())
5096 return mlir::failure();
5097
5098 if (parser.parseOptionalArrow().succeeded() &&
5099 parser.parseType(resType).failed())
5100 return mlir::failure();
5101
5102 result.attributes.set("asm_flavor", AsmFlavorAttr::get(ctxt, *flavor));
5103 result.attributes.set("asm_string", StringAttr::get(ctxt, asmString));
5104 result.attributes.set("constraints", StringAttr::get(ctxt, constraints));
5105 result.attributes.set("operand_attrs", ArrayAttr::get(ctxt, operandAttrs));
5106 result.getOrAddProperties<InlineAsmOp::Properties>().operands_segments =
5107 parser.getBuilder().getDenseI32ArrayAttr(operandsGroupSizes);
5108 if (resType)
5109 result.addTypes(TypeRange{resType});
5110
5111 return mlir::success();
5112}
5113
5114void InlineAsmOp::getEffects(
5116 // If we have any side effects (that is, we're volatile asm), add a read and
5117 // write memory effect. We do this the same as the llvm dialect InlineAsmOp.
5118 if (getSideEffects()) {
5119 effects.emplace_back(mlir::MemoryEffects::Read::get());
5120 effects.emplace_back(mlir::MemoryEffects::Write::get());
5121 }
5122}
5123
5124//===----------------------------------------------------------------------===//
5125// ThrowOp / TryThrowOp
5126//===----------------------------------------------------------------------===//
5127
5128template <typename ThrowOpTy>
5129static mlir::LogicalResult verifyThrowOpImpl(ThrowOpTy op) {
5130 if (op.rethrows())
5131 return mlir::success();
5132
5133 if (op.getNumOperands() != 0) {
5134 if (op.getTypeInfo())
5135 return mlir::success();
5136 return op.emitOpError() << "'type_info' symbol attribute missing";
5137 }
5138
5139 return mlir::failure();
5140}
5141
5142mlir::LogicalResult cir::ThrowOp::verify() { return verifyThrowOpImpl(*this); }
5143
5144mlir::LogicalResult cir::TryThrowOp::verify() {
5145 return verifyThrowOpImpl(*this);
5146}
5147
5148//===----------------------------------------------------------------------===//
5149// AtomicFetchOp
5150//===----------------------------------------------------------------------===//
5151
5152LogicalResult cir::AtomicFetchOp::verify() {
5153 if (getBinop() != cir::AtomicFetchKind::Add &&
5154 getBinop() != cir::AtomicFetchKind::Sub &&
5155 getBinop() != cir::AtomicFetchKind::Max &&
5156 getBinop() != cir::AtomicFetchKind::Min &&
5157 getBinop() != cir::AtomicFetchKind::Maximum &&
5158 getBinop() != cir::AtomicFetchKind::Minimum &&
5159 getBinop() != cir::AtomicFetchKind::MaximumNum &&
5160 getBinop() != cir::AtomicFetchKind::MinimumNum &&
5161 !mlir::isa<cir::IntType>(getVal().getType()))
5162 return emitError("only atomic add, sub, max, min, maximum, minimum, "
5163 "maximum_num, and minimum_num operation could operate on "
5164 "floating-point values");
5165
5166 if ((getBinop() == cir::AtomicFetchKind::Maximum ||
5167 getBinop() == cir::AtomicFetchKind::Minimum ||
5168 getBinop() == cir::AtomicFetchKind::MaximumNum ||
5169 getBinop() == cir::AtomicFetchKind::MinimumNum) &&
5170 !cir::isFPOrVectorOfFPType(getVal().getType()))
5171 return emitError("atomic maximum, minimum, maximum_num, and minimum_num "
5172 "operation could only operate on floating-point values");
5173
5174 return success();
5175}
5176
5177//===----------------------------------------------------------------------===//
5178// TypeInfoAttr
5179//===----------------------------------------------------------------------===//
5180
5181LogicalResult cir::TypeInfoAttr::verify(
5182 ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError,
5183 ::mlir::Type type, ::mlir::ArrayAttr typeInfoData) {
5184
5185 if (cir::ConstRecordAttr::verify(emitError, type, typeInfoData).failed())
5186 return failure();
5187
5188 return success();
5189}
5190
5191//===----------------------------------------------------------------------===//
5192// TryOp
5193//===----------------------------------------------------------------------===//
5194
5195void cir::TryOp::getSuccessorRegions(
5196 mlir::RegionBranchPoint point,
5198 if (point.isParent()) {
5199 regions.emplace_back(&getTryRegion());
5200 } else {
5201 // A handler exit leaves the operation.
5202 mlir::Operation *term = point.getTerminatorPredecessorOrNull();
5203 if (term->getParentRegion() != &getTryRegion()) {
5204 regions.emplace_back(getOperation());
5205 return;
5206 }
5207 // A cir.resume ending the try region unwinds into a handler, so it leaves
5208 // the operation only when there is none. Every other exit can leave it.
5209 if (!isa<cir::ResumeOp>(term) || getHandlerRegions().empty())
5210 regions.emplace_back(getOperation());
5211 }
5212
5213 // Most handlers are entered by an unwind out of a call in the try region,
5214 // which is not a branch point, so the handlers are successors of the parent
5215 // and of every exit from the try region to stand in for it.
5216 //
5217 // TODO(CIR): If we know a target function never throws a specific type, we
5218 // can remove the catch handler.
5219 regions.reserve(regions.size() + getHandlerRegions().size());
5220 for (mlir::Region &handlerRegion : getHandlerRegions())
5221 regions.emplace_back(&handlerRegion);
5222}
5223
5224/// Verify that each cir.init_catch_param in \p handlerRegion, outside any
5225/// nested cir.try, agrees with the handler's leading cir.construct_catch_param
5226/// \p constructOp, which may be null. A cir.init_catch_param of kind
5227/// reference_to_pointer or non_trivial_copy needs \p constructOp on its
5228/// parameter, and a cir.init_catch_param on the parameter of \p constructOp
5229/// must have the kind of \p constructOp.
5230static LogicalResult
5231verifyCatchParamPairing(mlir::Region &handlerRegion,
5232 cir::ConstructCatchParamOp constructOp) {
5233 mlir::WalkResult result =
5234 handlerRegion.walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
5235 if (mlir::isa<cir::TryOp>(op))
5236 return mlir::WalkResult::skip();
5237 auto initOp = mlir::dyn_cast<cir::InitCatchParamOp>(op);
5238 if (!initOp)
5239 return mlir::WalkResult::advance();
5240
5241 cir::InitCatchKind kind = initOp.getKind();
5242 bool sameParam =
5243 constructOp && constructOp.getParamAddr() == initOp.getParamAddr();
5244 if (sameParam && constructOp.getKind() != kind) {
5245 initOp.emitOpError("kind '")
5246 << cir::stringifyInitCatchKind(kind)
5247 << "' does not match the kind '"
5248 << cir::stringifyInitCatchKind(constructOp.getKind())
5249 << "' of the preceding 'cir.construct_catch_param'";
5250 return mlir::WalkResult::interrupt();
5251 }
5252 if ((kind == cir::InitCatchKind::ReferenceToPointer ||
5253 kind == cir::InitCatchKind::NonTrivialCopy) &&
5254 !sameParam) {
5255 initOp.emitOpError("'")
5256 << cir::stringifyInitCatchKind(kind)
5257 << "' requires a preceding 'cir.construct_catch_param' of the "
5258 "same kind on the same parameter";
5259 return mlir::WalkResult::interrupt();
5260 }
5261 return mlir::WalkResult::advance();
5262 });
5263 return failure(result.wasInterrupted());
5264}
5265
5266LogicalResult cir::TryOp::verifyRegions() {
5267 mlir::ArrayAttr handlerTypes = getHandlerTypes();
5268 if (!handlerTypes) {
5269 if (!getHandlerRegions().empty())
5270 return emitOpError(
5271 "handler regions must be empty when no handler types are present");
5272 return success();
5273 }
5274
5275 mlir::MutableArrayRef<mlir::Region> handlerRegions = getHandlerRegions();
5276
5277 // The parser and builder won't allow this to happen, but the loop below
5278 // relies on the sizes being the same, so we check it here.
5279 if (handlerRegions.size() != handlerTypes.size())
5280 return emitOpError(
5281 "number of handler regions and handler types must match");
5282
5283 // A filter handler and an unexpected handler together implement a dynamic
5284 // exception specification. The filter try operation wraps the whole function
5285 // body and exists only to check the specification, so the two must appear
5286 // together and must stand alone. A catch-all in the same list would make the
5287 // filter unreachable, and the filter handler already provides the
5288 // continue-unwinding path that an unwind handler would supply.
5289 if (llvm::any_of(handlerTypes, [](mlir::Attribute typeAttr) {
5290 return mlir::isa<cir::EhFilterAttr, cir::EhUnexpectedAttr>(typeAttr);
5291 })) {
5292 if (handlerTypes.size() != 2 ||
5293 !mlir::isa<cir::EhFilterAttr>(handlerTypes[0]) ||
5294 !mlir::isa<cir::EhUnexpectedAttr>(handlerTypes[1]))
5295 return emitOpError("a filter handler must be followed by an unexpected "
5296 "handler, and the two must be the only handlers");
5297 }
5298
5299 for (const auto &[typeAttr, handlerRegion] :
5300 llvm::zip(handlerTypes, handlerRegions)) {
5301 // Verify that handler regions have a !cir.eh_token block argument.
5302 mlir::Block &entryBlock = handlerRegion.front();
5303 if (entryBlock.getNumArguments() != 1 ||
5304 !mlir::isa<cir::EhTokenType>(entryBlock.getArgument(0).getType()))
5305 return emitOpError(
5306 "handler region must have a single '!cir.eh_token' argument");
5307
5308 // The unwind, filter and unexpected regions do not require a
5309 // cir.begin_catch. None of them catches the exception.
5310 if (mlir::isa<cir::UnwindAttr, cir::EhFilterAttr, cir::EhUnexpectedAttr>(
5311 typeAttr))
5312 continue;
5313
5314 if (entryBlock.empty())
5315 return emitOpError("catch handler region must not be empty");
5316
5317 // A terminate scope, which wraps the body of a function that cannot throw,
5318 // is a catch-all handler that only terminates the program. The exception is
5319 // caught by the runtime helper that cir.eh.terminate lowers to, so the
5320 // handler region has no cir.begin_catch of its own.
5321 if (mlir::isa<cir::EhTerminateOp>(entryBlock.front())) {
5322 if (!mlir::isa<cir::CatchAllAttr>(typeAttr))
5323 return emitOpError("'cir.eh.terminate' is only allowed in a catch-all "
5324 "handler region");
5325 continue;
5326 }
5327
5328 // Nothing may run in a catch handler before cir.begin_catch, so it has to
5329 // be the handler region's first operation, with two exceptions.
5330 //
5331 // When lifetime markers are enabled, the catch parameter's storage can be
5332 // marked by a cir.lifetime.start. That parameter is the only variable
5333 // whose lifetime begins before the catch is entered, so there is at most
5334 // one such marker. Its lifetime-end cleanup has to run after the catch
5335 // handler is finished (or exited by an exception unwind), so if there is a
5336 // lifetime begin marker, it is followed by a cir.cleanup.scope that
5337 // encloses the the rest of the handler with a cir.lifetime.end in its
5338 // cleanup region.
5339 //
5340 // A cir.construct_catch_param may also precede cir.begin_catch, to
5341 // perform any pre-begin_catch initialization of the catch parameter.
5342 mlir::Operation *firstOp = &entryBlock.front();
5343 if (mlir::isa<cir::LifetimeStartOp>(firstOp)) {
5344 mlir::Operation *next = firstOp->getNextNode();
5345 auto lifetimeScope = mlir::dyn_cast_if_present<cir::CleanupScopeOp>(next);
5346 if (!lifetimeScope)
5347 return emitOpError("'cir.lifetime.start' in a catch handler region "
5348 "must be followed by the 'cir.cleanup.scope' of "
5349 "its lifetime-end cleanup");
5350 if (lifetimeScope.getBodyRegion().empty())
5351 return emitOpError(
5352 "'cir.lifetime.start' in a catch handler region must be "
5353 "followed by the 'cir.cleanup.scope' of its lifetime-end "
5354 "cleanup");
5355 mlir::Block &scopeBody = lifetimeScope.getBodyRegion().front();
5356 firstOp = scopeBody.empty() ? nullptr : &scopeBody.front();
5357 }
5358
5359 auto constructOp =
5360 mlir::dyn_cast_if_present<cir::ConstructCatchParamOp>(firstOp);
5361 if (constructOp)
5362 firstOp = firstOp->getNextNode();
5363 if (!mlir::isa_and_present<cir::BeginCatchOp>(firstOp))
5364 return emitOpError(
5365 "catch handler region must start with 'cir.begin_catch'");
5366
5367 if (failed(verifyCatchParamPairing(handlerRegion, constructOp)))
5368 return failure();
5369 }
5370
5371 return success();
5372}
5373
5375 mlir::OpAsmPrinter &printer, cir::TryOp op,
5376 mlir::MutableArrayRef<mlir::Region> handlerRegions,
5377 mlir::ArrayAttr handlerTypes) {
5378 if (!handlerTypes)
5379 return;
5380
5381 for (const auto [typeIdx, typeAttr] : llvm::enumerate(handlerTypes)) {
5382 if (typeIdx)
5383 printer << " ";
5384
5385 if (mlir::isa<cir::CatchAllAttr>(typeAttr)) {
5386 printer << "catch all ";
5387 } else if (mlir::isa<cir::UnwindAttr>(typeAttr)) {
5388 printer << "unwind ";
5389 } else if (auto filterAttr = mlir::dyn_cast<cir::EhFilterAttr>(typeAttr)) {
5390 printer << "filter [";
5391 llvm::interleaveComma(
5392 filterAttr.getPermittedTypes(), printer,
5393 [&](mlir::Attribute sym) { printer.printAttribute(sym); });
5394 printer << "] ";
5395 } else if (mlir::isa<cir::EhUnexpectedAttr>(typeAttr)) {
5396 printer << "unexpected ";
5397 } else {
5398 printer << "catch [type ";
5399 printer.printAttribute(typeAttr);
5400 printer << "] ";
5401 }
5402
5403 // Print the handler region's !cir.eh_token block argument.
5404 mlir::Region &region = handlerRegions[typeIdx];
5405 if (!region.empty() && region.front().getNumArguments() > 0) {
5406 printer << "(";
5407 printer.printRegionArgument(region.front().getArgument(0));
5408 printer << ") ";
5409 }
5410
5411 printer.printRegion(region,
5412 /*printEntryBLockArgs=*/false,
5413 /*printBlockTerminators=*/true);
5414 }
5415}
5416
5418 mlir::OpAsmParser &parser,
5419 llvm::SmallVectorImpl<std::unique_ptr<mlir::Region>> &handlerRegions,
5420 mlir::ArrayAttr &handlerTypes) {
5421
5422 auto parseCheckedCatcherRegion = [&]() -> mlir::ParseResult {
5423 handlerRegions.emplace_back(new mlir::Region);
5424
5425 mlir::Region &currRegion = *handlerRegions.back();
5426
5427 // Parse the required region argument: (%eh_token : !cir.eh_token)
5429 if (parser.parseLParen())
5430 return failure();
5431 mlir::OpAsmParser::Argument arg;
5432 if (parser.parseArgument(arg, /*allowType=*/true))
5433 return failure();
5434 regionArgs.push_back(arg);
5435 if (parser.parseRParen())
5436 return failure();
5437
5438 mlir::SMLoc regionLoc = parser.getCurrentLocation();
5439 if (parser.parseRegion(currRegion, regionArgs)) {
5440 handlerRegions.clear();
5441 return failure();
5442 }
5443
5444 if (currRegion.empty())
5445 return parser.emitError(regionLoc, "handler region shall not be empty");
5446
5447 if (!(currRegion.back().mightHaveTerminator() &&
5448 currRegion.back().getTerminator()))
5449 return parser.emitError(
5450 regionLoc, "blocks are expected to be explicitly terminated");
5451
5452 return success();
5453 };
5454
5455 bool hasCatchAll = false;
5457 while (parser.parseOptionalKeyword("catch").succeeded()) {
5458 bool hasLSquare = parser.parseOptionalLSquare().succeeded();
5459
5460 llvm::StringRef attrStr;
5461 if (parser.parseOptionalKeyword(&attrStr, {"all", "type"}).failed())
5462 return parser.emitError(parser.getCurrentLocation(),
5463 "expected 'all' or 'type' keyword");
5464
5465 bool isCatchAll = attrStr == "all";
5466 if (isCatchAll) {
5467 if (hasCatchAll)
5468 return parser.emitError(parser.getCurrentLocation(),
5469 "can't have more than one catch all");
5470 hasCatchAll = true;
5471 }
5472
5473 mlir::Attribute exceptionRTTIAttr;
5474 if (!isCatchAll && parser.parseAttribute(exceptionRTTIAttr).failed())
5475 return parser.emitError(parser.getCurrentLocation(),
5476 "expected valid RTTI info attribute");
5477
5478 catcherAttrs.push_back(isCatchAll
5479 ? cir::CatchAllAttr::get(parser.getContext())
5480 : exceptionRTTIAttr);
5481
5482 if (hasLSquare && isCatchAll)
5483 return parser.emitError(parser.getCurrentLocation(),
5484 "catch all dosen't need RTTI info attribute");
5485
5486 if (hasLSquare && parser.parseRSquare().failed())
5487 return parser.emitError(parser.getCurrentLocation(),
5488 "expected `]` after RTTI info attribute");
5489
5490 if (parseCheckedCatcherRegion().failed())
5491 return mlir::failure();
5492 }
5493
5494 // A filter handler carries the type info symbols permitted by the enclosing
5495 // function's dynamic exception specification. TryOp::verifyRegions enforces
5496 // that it is paired with an unexpected handler and that the two stand alone.
5497 if (parser.parseOptionalKeyword("filter").succeeded()) {
5498 mlir::SMLoc filterLoc = parser.getCurrentLocation();
5500 auto parsePermittedType = [&]() -> mlir::ParseResult {
5501 mlir::SMLoc typeLoc = parser.getCurrentLocation();
5502 mlir::Attribute rtti;
5503 if (parser.parseAttribute(rtti).failed())
5504 return mlir::failure();
5505 if (!mlir::isa<cir::GlobalViewAttr>(rtti))
5506 return parser.emitError(typeLoc, "expected a type info symbol naming a "
5507 "permitted exception type");
5508 permittedTypes.push_back(rtti);
5509 return mlir::success();
5510 };
5511 if (parser
5512 .parseCommaSeparatedList(mlir::OpAsmParser::Delimiter::Square,
5513 parsePermittedType)
5514 .failed())
5515 return mlir::failure();
5516
5517 auto filterAttr = cir::EhFilterAttr::getChecked(
5518 [&]() { return parser.emitError(filterLoc); }, parser.getContext(),
5519 parser.getBuilder().getArrayAttr(permittedTypes));
5520 if (!filterAttr)
5521 return mlir::failure();
5522 catcherAttrs.push_back(filterAttr);
5523 if (parseCheckedCatcherRegion().failed())
5524 return mlir::failure();
5525 }
5526
5527 if (parser.parseOptionalKeyword("unexpected").succeeded()) {
5528 catcherAttrs.push_back(cir::EhUnexpectedAttr::get(parser.getContext()));
5529 if (parseCheckedCatcherRegion().failed())
5530 return mlir::failure();
5531 }
5532
5533 if (parser.parseOptionalKeyword("unwind").succeeded()) {
5534 if (hasCatchAll)
5535 return parser.emitError(parser.getCurrentLocation(),
5536 "unwind can't be used with catch all");
5537
5538 catcherAttrs.push_back(cir::UnwindAttr::get(parser.getContext()));
5539 if (parseCheckedCatcherRegion().failed())
5540 return mlir::failure();
5541 }
5542
5543 handlerTypes = parser.getBuilder().getArrayAttr(catcherAttrs);
5544 return mlir::success();
5545}
5546
5547//===----------------------------------------------------------------------===//
5548// EhTypeIdOp
5549//===----------------------------------------------------------------------===//
5550
5551LogicalResult
5552cir::EhTypeIdOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
5553 Operation *op = symbolTable.lookupNearestSymbolFrom(*this, getTypeSymAttr());
5554 if (!isa_and_nonnull<GlobalOp>(op))
5555 return emitOpError("'")
5556 << getTypeSym() << "' does not reference a valid cir.global";
5557 return success();
5558}
5559
5560//===----------------------------------------------------------------------===//
5561// LifetimeStartOp & LifetimeEndOp
5562//===----------------------------------------------------------------------===//
5563
5564LogicalResult cir::LifetimeStartOp::verify() {
5565 return verifyProducedBy<cir::AllocaOp>(*this, getPtr(), "ptr");
5566}
5567
5568LogicalResult cir::LifetimeEndOp::verify() {
5569 return verifyProducedBy<cir::AllocaOp>(*this, getPtr(), "ptr");
5570}
5571
5572//===----------------------------------------------------------------------===//
5573// MemChrOp
5574//===----------------------------------------------------------------------===//
5575
5576/// Reads a fundamental integer width from a signless i32 attribute.
5577static std::optional<unsigned> getRecordedIntegerWidth(mlir::Attribute attr) {
5578 auto intAttr = mlir::dyn_cast<mlir::IntegerAttr>(attr);
5579 if (!intAttr || !intAttr.getType().isSignlessInteger(32))
5580 return std::nullopt;
5581 int64_t width = intAttr.getInt();
5582 if (width < 0 ||
5583 !cir::isValidFundamentalIntWidth(static_cast<unsigned>(width)))
5584 return std::nullopt;
5585 return static_cast<unsigned>(width);
5586}
5587
5588LogicalResult cir::MemChrOp::verify() {
5589 auto moduleOp = (*this)->getParentOfType<mlir::ModuleOp>();
5590 if (!moduleOp)
5591 return emitOpError("expects an enclosing module");
5592
5593 // libc memchr uses pointers in the target's default address space.
5594 if (mlir::cast<cir::PointerType>(getSrc().getType()).getAddrSpace())
5595 return emitOpError("src must be in the default address space");
5596
5597 auto checkWidth = [&](cir::IntType type, llvm::StringRef operandName,
5598 llvm::StringRef attrName) -> LogicalResult {
5599 mlir::Attribute attr = moduleOp->getAttr(attrName);
5600 if (!attr)
5601 return emitOpError("expects the module to record ") << attrName;
5602 std::optional<unsigned> width = getRecordedIntegerWidth(attr);
5603 if (!width)
5604 return emitOpError("requires ")
5605 << attrName
5606 << " to be a signless i32 holding a fundamental integer width";
5607 if (type.getWidth() != *width)
5608 return emitOpError() << operandName << " must have the width recorded in "
5609 << attrName;
5610 return success();
5611 };
5612
5613 if (failed(checkWidth(getPattern().getType(), "pattern",
5614 cir::CIRDialect::getIntTypeWidthAttrName())))
5615 return failure();
5616 return checkWidth(getLen().getType(), "len",
5617 cir::CIRDialect::getSizeTypeWidthAttrName());
5618}
5619
5620//===----------------------------------------------------------------------===//
5621// InitCatchParamOp
5622//===----------------------------------------------------------------------===//
5623
5624/// For the reference_to_pointer and reference_to_record_pointer kinds, emit an
5625/// error on \p op unless \p paramAddrType is the type of the address of a
5626/// reference to a pointer. Any other \p kind is accepted.
5627static LogicalResult verifyCatchParamAddr(mlir::Operation *op,
5628 cir::InitCatchKind kind,
5629 cir::PointerType paramAddrType) {
5630 if (kind != cir::InitCatchKind::ReferenceToPointer &&
5631 kind != cir::InitCatchKind::ReferenceToRecordPointer)
5632 return success();
5633
5634 auto refType = mlir::dyn_cast<cir::PointerType>(paramAddrType.getPointee());
5635 if (!refType || !mlir::isa<cir::PointerType>(refType.getPointee()))
5636 return op->emitOpError("'")
5637 << cir::stringifyInitCatchKind(kind)
5638 << "' requires 'param_addr' to be the address of a reference to a "
5639 "pointer";
5640 return success();
5641}
5642
5643LogicalResult cir::InitCatchParamOp::verify() {
5644 return verifyCatchParamAddr(*this, getKind(), getParamAddr().getType());
5645}
5646
5647//===----------------------------------------------------------------------===//
5648// ConstructCatchParamOp
5649//===----------------------------------------------------------------------===//
5650
5651LogicalResult cir::ConstructCatchParamOp::verify() {
5652 return verifyCatchParamAddr(*this, getKind(), getParamAddr().getType());
5653}
5654
5655LogicalResult cir::ConstructCatchParamOp::verifySymbolUses(
5656 SymbolTableCollection &symbolTable) {
5657 auto copyFnAttr = getCopyFnAttr();
5658 if (!copyFnAttr)
5659 return success();
5660 auto fn =
5661 symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(*this, getCopyFnAttr());
5662 if (!fn)
5663 return emitOpError("'")
5664 << *getCopyFn() << "' does not reference a valid cir.func";
5665
5666 if (!fn->hasAttr(cir::CIRDialect::getCatchCopyThunkAttrName()))
5667 return emitOpError("catch-init copy_fn must be tagged with the ")
5668 << cir::CIRDialect::getCatchCopyThunkAttrName() << " attribute";
5669
5670 cir::FuncType fnType = fn.getFunctionType();
5671 if (fnType.getNumInputs() != 2 || !fnType.hasVoidReturn())
5672 return emitOpError("catch-init copy_fn must take two pointer arguments and "
5673 "return void");
5674
5675 if (fnType.getInput(0) != getParamAddr().getType())
5676 return emitOpError("first argument of catch-init copy_fn must match the "
5677 "type of 'param_addr'");
5678
5679 if (fnType.getInput(1) != getParamAddr().getType())
5680 return emitOpError(
5681 "second argument of catch-init copy_fn must be a pointer "
5682 "to the catch type");
5683
5684 return success();
5685}
5686
5687//===----------------------------------------------------------------------===//
5688// EhDispatchOp
5689//===----------------------------------------------------------------------===//
5690
5691LogicalResult cir::EhDispatchOp::verify() {
5692 mlir::ArrayAttr handlerTypes = getCatchTypesAttr();
5693 if (!handlerTypes)
5694 return success();
5695
5696 bool hasFilter = false;
5697 for (mlir::Attribute typeAttr : handlerTypes) {
5698 if (!mlir::isa<cir::EhFilterAttr>(typeAttr))
5699 continue;
5700 if (hasFilter)
5701 return emitOpError("can't have more than one 'filter' handler");
5702 hasFilter = true;
5703 }
5704
5705 // Unlike the other handlers, a filter does not take the place of the default
5706 // destination. Its destination is taken when the exception is not permitted
5707 // by the specification, and the default 'unwind' destination is taken when
5708 // it is. A catch-all default would leave the filter unreachable.
5709 if (hasFilter && getDefaultIsCatchAll())
5710 return emitOpError(
5711 "'filter' handler requires an 'unwind' default destination");
5712
5713 return success();
5714}
5715
5717 OpAsmParser &parser, mlir::ArrayAttr &catchTypes,
5718 SmallVectorImpl<Block *> &catchDestinations, Block *&defaultDestination,
5719 mlir::UnitAttr &defaultIsCatchAll) {
5720 // Parse: [ ... ]
5721 if (parser.parseLSquare())
5722 return failure();
5723
5724 SmallVector<Attribute> handlerTypes;
5725 bool hasCatchAll = false;
5726 bool hasUnwind = false;
5727
5728 // Parse handler list.
5729 auto parseHandler = [&]() -> ParseResult {
5730 // Check for 'catch_all' or 'unwind' keywords.
5731 if (succeeded(parser.parseOptionalKeyword("catch_all"))) {
5732 if (hasCatchAll)
5733 return parser.emitError(parser.getCurrentLocation(),
5734 "duplicate 'catch_all' handler");
5735 if (hasUnwind)
5736 return parser.emitError(parser.getCurrentLocation(),
5737 "cannot have both 'catch_all' and 'unwind'");
5738 hasCatchAll = true;
5739
5740 if (parser.parseColon().failed())
5741 return failure();
5742
5743 if (parser.parseSuccessor(defaultDestination).failed())
5744 return failure();
5745
5746 return success();
5747 }
5748
5749 if (succeeded(parser.parseOptionalKeyword("unwind"))) {
5750 if (hasUnwind)
5751 return parser.emitError(parser.getCurrentLocation(),
5752 "duplicate 'unwind' handler");
5753 if (hasCatchAll)
5754 return parser.emitError(parser.getCurrentLocation(),
5755 "cannot have both 'catch_all' and 'unwind'");
5756 hasUnwind = true;
5757
5758 if (parser.parseColon().failed())
5759 return failure();
5760
5761 if (parser.parseSuccessor(defaultDestination).failed())
5762 return failure();
5763 return success();
5764 }
5765
5766 // A filter handler carries the type info symbols permitted by the
5767 // enclosing function's dynamic exception specification. Its destination is
5768 // taken when the exception is *not* one of those types.
5769 if (succeeded(parser.parseOptionalKeyword("filter"))) {
5770 SMLoc filterLoc = parser.getCurrentLocation();
5771 SmallVector<Attribute, 4> permittedTypes;
5772 auto parsePermittedType = [&]() -> ParseResult {
5773 mlir::SMLoc typeLoc = parser.getCurrentLocation();
5774 mlir::Attribute rtti;
5775 if (parser.parseAttribute(rtti).failed())
5776 return failure();
5777 if (!mlir::isa<cir::GlobalViewAttr>(rtti))
5778 return parser.emitError(typeLoc,
5779 "expected a type info symbol naming a "
5780 "permitted exception type");
5781 permittedTypes.push_back(rtti);
5782 return success();
5783 };
5784 if (parser
5785 .parseCommaSeparatedList(OpAsmParser::Delimiter::Paren,
5786 parsePermittedType)
5787 .failed())
5788 return failure();
5789
5790 auto filterAttr = cir::EhFilterAttr::getChecked(
5791 [&]() { return parser.emitError(filterLoc); }, parser.getContext(),
5792 parser.getBuilder().getArrayAttr(permittedTypes));
5793 if (!filterAttr)
5794 return failure();
5795 handlerTypes.push_back(filterAttr);
5796
5797 if (parser.parseColon().failed())
5798 return failure();
5799
5800 Block *dest;
5801 if (parser.parseSuccessor(dest).failed())
5802 return failure();
5803 catchDestinations.push_back(dest);
5804 return success();
5805 }
5806
5807 // Otherwise, expect 'catch(<attr> : <type>) : ^block'.
5808 // The 'catch(...)' wrapper allows the attribute to include its type
5809 // without conflicting with the ':' used for the block destination.
5810 if (parser.parseKeyword("catch").failed())
5811 return failure();
5812
5813 if (parser.parseLParen().failed())
5814 return failure();
5815
5816 mlir::Attribute catchTypeAttr;
5817 if (parser.parseAttribute(catchTypeAttr).failed())
5818 return failure();
5819 handlerTypes.push_back(catchTypeAttr);
5820
5821 if (parser.parseRParen().failed())
5822 return failure();
5823
5824 if (parser.parseColon().failed())
5825 return failure();
5826
5827 Block *dest;
5828 if (parser.parseSuccessor(dest).failed())
5829 return failure();
5830 catchDestinations.push_back(dest);
5831 return success();
5832 };
5833
5834 if (parser.parseCommaSeparatedList(parseHandler).failed())
5835 return failure();
5836
5837 if (parser.parseRSquare().failed())
5838 return failure();
5839
5840 // Verify we have catch_all or unwind.
5841 if (!hasCatchAll && !hasUnwind)
5842 return parser.emitError(parser.getCurrentLocation(),
5843 "must have either 'catch_all' or 'unwind' handler");
5844
5845 // Add attributes and successors.
5846 if (!handlerTypes.empty())
5847 catchTypes = parser.getBuilder().getArrayAttr(handlerTypes);
5848
5849 if (hasCatchAll)
5850 defaultIsCatchAll = parser.getBuilder().getUnitAttr();
5851
5852 return success();
5853}
5854
5855void cir::printEhDispatchDestinations(OpAsmPrinter &p, cir::EhDispatchOp op,
5856 mlir::ArrayAttr catchTypes,
5857 SuccessorRange catchDestinations,
5858 Block *defaultDestination,
5859 mlir::UnitAttr defaultIsCatchAll) {
5860 p << " [";
5861 p.printNewline();
5862
5863 // If we have at least one catch type, print them.
5864 if (catchTypes) {
5865 // Print type handlers using 'catch(<attr>) : ^block' syntax.
5866 llvm::interleave(
5867 llvm::zip(catchTypes, catchDestinations),
5868 [&](auto i) {
5869 mlir::Attribute typeAttr = std::get<0>(i);
5870 if (auto filterAttr = mlir::dyn_cast<cir::EhFilterAttr>(typeAttr)) {
5871 p << " filter(";
5872 llvm::interleaveComma(
5873 filterAttr.getPermittedTypes(), p,
5874 [&](mlir::Attribute sym) { p.printAttribute(sym); });
5875 } else {
5876 p << " catch(";
5877 p.printAttribute(typeAttr);
5878 }
5879 p << ") : ";
5880 p.printSuccessor(std::get<1>(i));
5881 },
5882 [&] {
5883 p << ',';
5884 p.printNewline();
5885 });
5886
5887 p << ", ";
5888 p.printNewline();
5889 }
5890
5891 // Print catch_all or unwind handler.
5892 if (defaultIsCatchAll)
5893 p << " catch_all : ";
5894 else
5895 p << " unwind : ";
5896 p.printSuccessor(defaultDestination);
5897 p.printNewline();
5898
5899 p << "]";
5900}
5901
5902//===----------------------------------------------------------------------===//
5903// Standard library op signature matching
5904//===----------------------------------------------------------------------===//
5905
5906bool cir::StdFindOp::signatureMatches(mlir::TypeRange operands,
5907 mlir::TypeRange results) {
5908 if (operands.size() != getNumArgs() || results.size() != 1)
5909 return false;
5910 mlir::Type iterTy = operands[0];
5911 return iterTy == operands[1] && iterTy == operands[2] && iterTy == results[0];
5912}
static StringRef bytes(const std::vector< T, Allocator > &v)
static LogicalResult verifyLoopCleanup(LoopOpTy op)
static LogicalResult verifyOpenCLCXXVersion(ModuleOp module, cir::OpenCLVersionAttr cxxVersion)
static LogicalResult verifyCatchParamPairing(mlir::Region &handlerRegion, cir::ConstructCatchParamOp constructOp)
Verify that each cir.init_catch_param in handlerRegion, outside any nested cir.try,...
static mlir::LogicalResult checkReturnAndFunction(cir::ReturnOp op, cir::FuncOp function)
static LogicalResult verifyOffloadContainer(mlir::Operation *op)
static std::optional< unsigned > getRecordedIntegerWidth(mlir::Attribute attr)
Reads a fundamental integer width from a signless i32 attribute.
static bool isCirFunctionPointerType(mlir::Type ty)
static LogicalResult verifyMemberPtrCast(Operation *op, mlir::Value src, mlir::Type resultTy)
static bool isFloatingPointCastKind(cir::CastKind kind)
static LogicalResult verifyOffloadKind(mlir::ModuleOp module, cir::OffloadKind expected)
static mlir::ParseResult parseCallCommon(mlir::OpAsmParser &parser, mlir::OperationState &result, bool hasDestinationBlocks=false)
static mlir::Type memberPointeeType(cir::RecordType recordTy, unsigned idx)
static bool isIntOrBoolCast(cir::CastOp op)
static LogicalResult verifyCatchParamAddr(mlir::Operation *op, cir::InitCatchKind kind, cir::PointerType paramAddrType)
For the reference_to_pointer and reference_to_record_pointer kinds, emit an error on op unless paramA...
static void printConstant(OpAsmPrinter &p, Attribute value)
static ParseResult checkEffectAttrKinds(mlir::OpAsmParser &parser, llvm::SMLoc loc, const mlir::NamedAttrList &attrs)
Reject an attribute in an explicit attribute dictionary whose value is not the attribute class expect...
static void printCallCommon(mlir::Operation *op, mlir::FlatSymbolRefAttr calleeSym, mlir::Value indirectCallee, mlir::OpAsmPrinter &printer, bool isNothrow, ArrayAttr argAttrs, ArrayAttr resAttrs, mlir::Block *normalDest=nullptr, mlir::Block *unwindDest=nullptr)
static bool areOpenCLVersionsCompatible(cir::OpenCLVersionAttr openCLVersion, cir::OpenCLVersionAttr cxxVersion)
static LogicalResult verifyOpenCLVersionAttrPlacement(Operation *op, NamedAttribute attr)
static bool isInVarCtorRegion(mlir::Operation *op)
Returns true if op is nested in the ctor region of a cir.global or cir.local_init without crossing a ...
ParseResult parseInlineKindAttr(OpAsmParser &parser, cir::InlineKindAttr &inlineKindAttr)
void printInlineKindAttr(OpAsmPrinter &p, cir::InlineKindAttr inlineKindAttr)
static LogicalResult verifyOpenCLVersionAttr(Operation *op, NamedAttribute attr)
static LogicalResult verifyCallCommInSymbolUses(mlir::Operation *op, SymbolTableCollection &symbolTable)
static bool isOpenCLVersionAttrName(StringRef attrName)
static LogicalResult ensureRegionTerm(OpAsmParser &parser, Region &region, SMLoc errLoc)
static OpFoldResult foldUnaryBitOp(mlir::Attribute inputAttr, llvm::function_ref< llvm::APInt(const llvm::APInt &)> func, bool poisonZero=false)
static llvm::StringRef getLinkageAttrNameString()
Returns the name used for the linkage attribute.
static RetTy parseOptionalCIRKeyword(AsmParser &parser, EnumTy defaultValue)
Parse an enum from the keyword, or default to the provided default value.
static LogicalResult verifyProducedBy(Operation *op, Value operand, StringRef operandName)
static mlir::ParseResult parseTryCallDestinations(mlir::OpAsmParser &parser, mlir::OperationState &result)
static void printComdatName(OpAsmPrinter &p, StringAttr comdat)
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 bool omitRegionTerm(mlir::Region &r)
static ParseResult parseConstantValue(OpAsmParser &parser, mlir::Attribute &valueAttr)
static LogicalResult verifyArrayCtorDtor(Op op)
static bool isFuncAttrInDict(llvm::StringRef name)
Declared cir.func attributes with no dedicated syntax, which print in and parse from the attribute di...
static bool isRedundantBeforeReturn(mlir::Region &cleanupRegion)
static mlir::LogicalResult verifyThrowOpImpl(ThrowOpTy op)
static LogicalResult checkConstantTypes(mlir::Operation *op, mlir::Type opType, mlir::Attribute attrType)
#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:34
llvm::function_ref< void( mlir::OpBuilder &, mlir::Location, mlir::OperationState &)> BuilderOpStateCallbackRef
Definition CIRDialect.h:36
static std::optional< NonLoc > getIndex(ProgramStateRef State, const ElementRegion *ER, CharKind CK)
static Decl::Kind getKind(const Decl *D)
TokenType getType() const
Returns the token's type, e.g.
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a an optional score condition
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
unsigned getProgramAddressSpace() const
C++ view class that accepts both !cir.struct and !cir.union types.
Definition CIRTypes.h:150
llvm::ArrayRef< mlir::Type > getMembers() const
Definition CIRTypes.cpp:648
static bool isSupportedCXXABI(const llvm::Triple &T, Kind Kind)
static bool isABI(StringRef Name)
Kind getKind() const
Kind
The basic C++ ABI kind.
void addBytecodeInterface(CIRDialect *dialect)
Add the interfaces necessary for encoding the CIR dialect components in bytecode.
mlir::ParseResult parseEhDispatchDestinations(mlir::OpAsmParser &parser, mlir::ArrayAttr &catchTypes, llvm::SmallVectorImpl< mlir::Block * > &catchDestinations, mlir::Block *&defaultDestination, mlir::UnitAttr &defaultIsCatchAll)
mlir::ParseResult parseOmittedTerminatorRegion(mlir::OpAsmParser &parser, mlir::Region &region)
void printCopyTypes(mlir::OpAsmPrinter &printer, mlir::Operation *, mlir::Type srcType, mlir::Type dstType)
mlir::ParseResult parseCopyTypes(mlir::OpAsmParser &parser, mlir::Type &srcType, mlir::Type &dstType)
mlir::Type memberStorageType(mlir::Type memberTy)
The storage a member is stored as: the access unit for a bit-field member, and the member type itself...
Definition CIRTypes.h:135
void printComdatName(mlir::OpAsmPrinter &p, cir::GlobalOp op, mlir::StringAttr comdat)
mlir::ParseResult parseGlobalOpTypeAndInitialValue(mlir::OpAsmParser &parser, mlir::TypeAttr &typeAttr, mlir::Attribute &initialValueAttr, mlir::Region &ctorRegion, mlir::Region &dtorRegion)
mlir::ParseResult parseSwitchFlatOpCases(mlir::OpAsmParser &parser, mlir::Type flagType, mlir::ArrayAttr &caseValues, llvm::SmallVectorImpl< mlir::Block * > &caseDestinations, llvm::SmallVectorImpl< llvm::SmallVector< mlir::OpAsmParser::UnresolvedOperand > > &caseOperands, llvm::SmallVectorImpl< llvm::SmallVector< mlir::Type > > &caseOperandTypes)
bool isValidFundamentalIntWidth(unsigned width)
void buildTerminatedBody(mlir::OpBuilder &builder, mlir::Location loc)
mlir::ParseResult parseAssumeBundle(mlir::OpAsmParser &p, cir::AssumeBundleKindAttr &bundleKindAttr, llvm::SmallVector< mlir::OpAsmParser::UnresolvedOperand, 4 > &bundleArgs, llvm::SmallVector< mlir::Type, 1 > &bundleArgTypes)
mlir::ParseResult parseComdatName(mlir::OpAsmParser &parser, mlir::StringAttr &comdatAttr)
AllocaOp getUnderlyingAlloca(mlir::Value addr)
The alloca that defines addr, looking through casts that preserve the underlying storage.
void printOmittedTerminatorRegion(mlir::OpAsmPrinter &printer, cir::ScopeOp &op, mlir::Region &region)
void printTryHandlerRegions(mlir::OpAsmPrinter &printer, cir::TryOp op, mlir::MutableArrayRef< mlir::Region > handlerRegions, mlir::ArrayAttr handlerTypes)
mlir::ptr::MemorySpaceAttrInterface normalizeDefaultAddressSpace(mlir::ptr::MemorySpaceAttrInterface addrSpace)
Normalize LangAddressSpace::Default to null (empty attribute).
void printIndirectBrOpSucessors(mlir::OpAsmPrinter &p, cir::IndirectBrOp op, mlir::Type flagType, mlir::SuccessorRange succs, mlir::OperandRangeRange succOperands, const mlir::TypeRangeRange &succOperandsTypes)
mlir::ParseResult parseTryHandlerRegions(mlir::OpAsmParser &parser, llvm::SmallVectorImpl< std::unique_ptr< mlir::Region > > &handlerRegions, mlir::ArrayAttr &handlerTypes)
mlir::ParseResult parseIndirectBrOpSucessors(mlir::OpAsmParser &parser, mlir::Type &flagType, llvm::SmallVectorImpl< mlir::Block * > &succOperandBlocks, llvm::SmallVectorImpl< llvm::SmallVector< mlir::OpAsmParser::UnresolvedOperand > > &succOperands, llvm::SmallVectorImpl< llvm::SmallVector< mlir::Type > > &succOperandsTypes)
void printGlobalOpTypeAndInitialValue(mlir::OpAsmPrinter &p, cir::GlobalOp op, mlir::TypeAttr type, mlir::Attribute initAttr, mlir::Region &ctorRegion, mlir::Region &dtorRegion)
std::optional< llvm::Triple > getTripleFromModule(mlir::ModuleOp mod)
Attempts to construct an llvm::Triple from a module's cir.triple attribute.
void printEhDispatchDestinations(mlir::OpAsmPrinter &p, cir::EhDispatchOp op, mlir::ArrayAttr catchTypes, mlir::SuccessorRange catchDestinations, mlir::Block *defaultDestination, mlir::UnitAttr defaultIsCatchAll)
void printAssumeBundle(mlir::OpAsmPrinter &p, cir::AssumeOp op, cir::AssumeBundleKindAttr kindAttr, mlir::OperandRange bundleArgs, mlir::TypeRange bundleArgTypes)
void printSwitchFlatOpCases(mlir::OpAsmPrinter &p, cir::SwitchFlatOp op, mlir::Type flagType, mlir::ArrayAttr caseValues, mlir::SuccessorRange caseDestinations, mlir::OperandRangeRange caseOperands, const mlir::TypeRangeRange &caseOperandTypes)
const AstTypeMatcher< BuiltinType > builtinType
const internal::VariadicAllOfMatcher< Attr > attr
const internal::VariadicAllOfMatcher< TypeLoc > typeLoc
Matches TypeLocs in the clang AST.
const AstTypeMatcher< RecordType > recordType
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Clean up any erroneous/redundant code in the given Ranges in Code.
Definition Format.cpp:4563
StringRef getName(const HeaderType T)
Definition HeaderFile.h:38
void info(bool Verbose, unsigned Level, const char *Fmt, Ts &&...Args)
Prints an indented note to stderr when Verbose is set.
Definition Utils.h:57
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)
__builtin_bitreverse32 uint32_t __builtin_riscv_aaddu_u32 __builtin_riscv_asubu_u32 __builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t uint32_t uint32_t __builtin_riscv_mhacc_i32 __builtin_riscv_mhaccu_u32 __builtin_riscv_mhaccsu_i32 __builtin_riscv_mulq_i32 int64_t
static bool memberFuncPtrCast()
static bool opCallCallConv()
static bool opScopeCleanupRegion()
static bool supportIFuncAttr()