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