clang 22.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
17
18#include "mlir/IR/DialectImplementation.h"
19#include "mlir/Interfaces/ControlFlowInterfaces.h"
20#include "mlir/Interfaces/FunctionImplementation.h"
21#include "mlir/Support/LLVM.h"
22
23#include "clang/CIR/Dialect/IR/CIROpsDialect.cpp.inc"
24#include "clang/CIR/Dialect/IR/CIROpsEnums.cpp.inc"
26#include "llvm/ADT/SetOperations.h"
27#include "llvm/ADT/SmallSet.h"
28#include "llvm/Support/LogicalResult.h"
29
30using namespace mlir;
31using namespace cir;
32
33//===----------------------------------------------------------------------===//
34// CIR Dialect
35//===----------------------------------------------------------------------===//
36namespace {
37struct CIROpAsmDialectInterface : public OpAsmDialectInterface {
38 using OpAsmDialectInterface::OpAsmDialectInterface;
39
40 AliasResult getAlias(Type type, raw_ostream &os) const final {
41 if (auto recordType = dyn_cast<cir::RecordType>(type)) {
42 StringAttr nameAttr = recordType.getName();
43 if (!nameAttr)
44 os << "rec_anon_" << recordType.getKindAsStr();
45 else
46 os << "rec_" << nameAttr.getValue();
47 return AliasResult::OverridableAlias;
48 }
49 if (auto intType = dyn_cast<cir::IntType>(type)) {
50 // We only provide alias for standard integer types (i.e. integer types
51 // whose width is a power of 2 and at least 8).
52 unsigned width = intType.getWidth();
53 if (width < 8 || !llvm::isPowerOf2_32(width))
54 return AliasResult::NoAlias;
55 os << intType.getAlias();
56 return AliasResult::OverridableAlias;
57 }
58 if (auto voidType = dyn_cast<cir::VoidType>(type)) {
59 os << voidType.getAlias();
60 return AliasResult::OverridableAlias;
61 }
62
63 return AliasResult::NoAlias;
64 }
65
66 AliasResult getAlias(Attribute attr, raw_ostream &os) const final {
67 if (auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr)) {
68 os << (boolAttr.getValue() ? "true" : "false");
69 return AliasResult::FinalAlias;
70 }
71 if (auto bitfield = mlir::dyn_cast<cir::BitfieldInfoAttr>(attr)) {
72 os << "bfi_" << bitfield.getName().str();
73 return AliasResult::FinalAlias;
74 }
75 if (auto dynCastInfoAttr = mlir::dyn_cast<cir::DynamicCastInfoAttr>(attr)) {
76 os << dynCastInfoAttr.getAlias();
77 return AliasResult::FinalAlias;
78 }
79 return AliasResult::NoAlias;
80 }
81};
82} // namespace
83
84void cir::CIRDialect::initialize() {
85 registerTypes();
86 registerAttributes();
87 addOperations<
88#define GET_OP_LIST
89#include "clang/CIR/Dialect/IR/CIROps.cpp.inc"
90 >();
91 addInterfaces<CIROpAsmDialectInterface>();
92}
93
94Operation *cir::CIRDialect::materializeConstant(mlir::OpBuilder &builder,
95 mlir::Attribute value,
96 mlir::Type type,
97 mlir::Location loc) {
98 return builder.create<cir::ConstantOp>(loc, type,
99 mlir::cast<mlir::TypedAttr>(value));
100}
101
102//===----------------------------------------------------------------------===//
103// Helpers
104//===----------------------------------------------------------------------===//
105
106// Parses one of the keywords provided in the list `keywords` and returns the
107// position of the parsed keyword in the list. If none of the keywords from the
108// list is parsed, returns -1.
109static int parseOptionalKeywordAlternative(AsmParser &parser,
110 ArrayRef<llvm::StringRef> keywords) {
111 for (auto en : llvm::enumerate(keywords)) {
112 if (succeeded(parser.parseOptionalKeyword(en.value())))
113 return en.index();
114 }
115 return -1;
116}
117
118namespace {
119template <typename Ty> struct EnumTraits {};
120
121#define REGISTER_ENUM_TYPE(Ty) \
122 template <> struct EnumTraits<cir::Ty> { \
123 static llvm::StringRef stringify(cir::Ty value) { \
124 return stringify##Ty(value); \
125 } \
126 static unsigned getMaxEnumVal() { return cir::getMaxEnumValFor##Ty(); } \
127 }
128
129REGISTER_ENUM_TYPE(GlobalLinkageKind);
130REGISTER_ENUM_TYPE(VisibilityKind);
131REGISTER_ENUM_TYPE(SideEffect);
132} // namespace
133
134/// Parse an enum from the keyword, or default to the provided default value.
135/// The return type is the enum type by default, unless overriden with the
136/// second template argument.
137template <typename EnumTy, typename RetTy = EnumTy>
138static RetTy parseOptionalCIRKeyword(AsmParser &parser, EnumTy defaultValue) {
140 for (unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
141 names.push_back(EnumTraits<EnumTy>::stringify(static_cast<EnumTy>(i)));
142
143 int index = parseOptionalKeywordAlternative(parser, names);
144 if (index == -1)
145 return static_cast<RetTy>(defaultValue);
146 return static_cast<RetTy>(index);
147}
148
149/// Parse an enum from the keyword, return failure if the keyword is not found.
150template <typename EnumTy, typename RetTy = EnumTy>
151static ParseResult parseCIRKeyword(AsmParser &parser, RetTy &result) {
153 for (unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
154 names.push_back(EnumTraits<EnumTy>::stringify(static_cast<EnumTy>(i)));
155
156 int index = parseOptionalKeywordAlternative(parser, names);
157 if (index == -1)
158 return failure();
159 result = static_cast<RetTy>(index);
160 return success();
161}
162
163// Check if a region's termination omission is valid and, if so, creates and
164// inserts the omitted terminator into the region.
165static LogicalResult ensureRegionTerm(OpAsmParser &parser, Region &region,
166 SMLoc errLoc) {
167 Location eLoc = parser.getEncodedSourceLoc(parser.getCurrentLocation());
168 OpBuilder builder(parser.getBuilder().getContext());
169
170 // Insert empty block in case the region is empty to ensure the terminator
171 // will be inserted
172 if (region.empty())
173 builder.createBlock(&region);
174
175 Block &block = region.back();
176 // Region is properly terminated: nothing to do.
177 if (!block.empty() && block.back().hasTrait<OpTrait::IsTerminator>())
178 return success();
179
180 // Check for invalid terminator omissions.
181 if (!region.hasOneBlock())
182 return parser.emitError(errLoc,
183 "multi-block region must not omit terminator");
184
185 // Terminator was omitted correctly: recreate it.
186 builder.setInsertionPointToEnd(&block);
187 builder.create<cir::YieldOp>(eLoc);
188 return success();
189}
190
191// True if the region's terminator should be omitted.
192static bool omitRegionTerm(mlir::Region &r) {
193 const auto singleNonEmptyBlock = r.hasOneBlock() && !r.back().empty();
194 const auto yieldsNothing = [&r]() {
195 auto y = dyn_cast<cir::YieldOp>(r.back().getTerminator());
196 return y && y.getArgs().empty();
197 };
198 return singleNonEmptyBlock && yieldsNothing();
199}
200
201void printVisibilityAttr(OpAsmPrinter &printer,
202 cir::VisibilityAttr &visibility) {
203 switch (visibility.getValue()) {
204 case cir::VisibilityKind::Hidden:
205 printer << "hidden";
206 break;
207 case cir::VisibilityKind::Protected:
208 printer << "protected";
209 break;
210 case cir::VisibilityKind::Default:
211 break;
212 }
213}
214
215void parseVisibilityAttr(OpAsmParser &parser, cir::VisibilityAttr &visibility) {
216 cir::VisibilityKind visibilityKind =
217 parseOptionalCIRKeyword(parser, cir::VisibilityKind::Default);
218 visibility = cir::VisibilityAttr::get(parser.getContext(), visibilityKind);
219}
220
221//===----------------------------------------------------------------------===//
222// CIR Custom Parsers/Printers
223//===----------------------------------------------------------------------===//
224
225static mlir::ParseResult parseOmittedTerminatorRegion(mlir::OpAsmParser &parser,
226 mlir::Region &region) {
227 auto regionLoc = parser.getCurrentLocation();
228 if (parser.parseRegion(region))
229 return failure();
230 if (ensureRegionTerm(parser, region, regionLoc).failed())
231 return failure();
232 return success();
233}
234
235static void printOmittedTerminatorRegion(mlir::OpAsmPrinter &printer,
236 cir::ScopeOp &op,
237 mlir::Region &region) {
238 printer.printRegion(region,
239 /*printEntryBlockArgs=*/false,
240 /*printBlockTerminators=*/!omitRegionTerm(region));
241}
242
243//===----------------------------------------------------------------------===//
244// AllocaOp
245//===----------------------------------------------------------------------===//
246
247void cir::AllocaOp::build(mlir::OpBuilder &odsBuilder,
248 mlir::OperationState &odsState, mlir::Type addr,
249 mlir::Type allocaType, llvm::StringRef name,
250 mlir::IntegerAttr alignment) {
251 odsState.addAttribute(getAllocaTypeAttrName(odsState.name),
252 mlir::TypeAttr::get(allocaType));
253 odsState.addAttribute(getNameAttrName(odsState.name),
254 odsBuilder.getStringAttr(name));
255 if (alignment) {
256 odsState.addAttribute(getAlignmentAttrName(odsState.name), alignment);
257 }
258 odsState.addTypes(addr);
259}
260
261//===----------------------------------------------------------------------===//
262// BreakOp
263//===----------------------------------------------------------------------===//
264
265LogicalResult cir::BreakOp::verify() {
267 if (!getOperation()->getParentOfType<LoopOpInterface>() &&
268 !getOperation()->getParentOfType<SwitchOp>())
269 return emitOpError("must be within a loop");
270 return success();
271}
272
273//===----------------------------------------------------------------------===//
274// ConditionOp
275//===----------------------------------------------------------------------===//
276
277//===----------------------------------
278// BranchOpTerminatorInterface Methods
279//===----------------------------------
280
281void cir::ConditionOp::getSuccessorRegions(
282 ArrayRef<Attribute> operands, SmallVectorImpl<RegionSuccessor> &regions) {
283 // TODO(cir): The condition value may be folded to a constant, narrowing
284 // down its list of possible successors.
285
286 // Parent is a loop: condition may branch to the body or to the parent op.
287 if (auto loopOp = dyn_cast<LoopOpInterface>(getOperation()->getParentOp())) {
288 regions.emplace_back(&loopOp.getBody(), loopOp.getBody().getArguments());
289 regions.emplace_back(loopOp->getResults());
290 }
291
293}
294
295MutableOperandRange
296cir::ConditionOp::getMutableSuccessorOperands(RegionBranchPoint point) {
297 // No values are yielded to the successor region.
298 return MutableOperandRange(getOperation(), 0, 0);
299}
300
301LogicalResult cir::ConditionOp::verify() {
303 if (!isa<LoopOpInterface>(getOperation()->getParentOp()))
304 return emitOpError("condition must be within a conditional region");
305 return success();
306}
307
308//===----------------------------------------------------------------------===//
309// ConstantOp
310//===----------------------------------------------------------------------===//
311
312static LogicalResult checkConstantTypes(mlir::Operation *op, mlir::Type opType,
313 mlir::Attribute attrType) {
314 if (isa<cir::ConstPtrAttr>(attrType)) {
315 if (!mlir::isa<cir::PointerType>(opType))
316 return op->emitOpError(
317 "pointer constant initializing a non-pointer type");
318 return success();
319 }
320
321 if (isa<cir::ZeroAttr>(attrType)) {
322 if (isa<cir::RecordType, cir::ArrayType, cir::VectorType, cir::ComplexType>(
323 opType))
324 return success();
325 return op->emitOpError(
326 "zero expects struct, array, vector, or complex type");
327 }
328
329 if (mlir::isa<cir::BoolAttr>(attrType)) {
330 if (!mlir::isa<cir::BoolType>(opType))
331 return op->emitOpError("result type (")
332 << opType << ") must be '!cir.bool' for '" << attrType << "'";
333 return success();
334 }
335
336 if (mlir::isa<cir::IntAttr, cir::FPAttr>(attrType)) {
337 auto at = cast<TypedAttr>(attrType);
338 if (at.getType() != opType) {
339 return op->emitOpError("result type (")
340 << opType << ") does not match value type (" << at.getType()
341 << ")";
342 }
343 return success();
344 }
345
346 if (mlir::isa<cir::ConstArrayAttr, cir::ConstVectorAttr,
347 cir::ConstComplexAttr, cir::ConstRecordAttr,
348 cir::GlobalViewAttr, cir::PoisonAttr, cir::TypeInfoAttr,
349 cir::VTableAttr>(attrType))
350 return success();
351
352 assert(isa<TypedAttr>(attrType) && "What else could we be looking at here?");
353 return op->emitOpError("global with type ")
354 << cast<TypedAttr>(attrType).getType() << " not yet supported";
355}
356
357LogicalResult cir::ConstantOp::verify() {
358 // ODS already generates checks to make sure the result type is valid. We just
359 // need to additionally check that the value's attribute type is consistent
360 // with the result type.
361 return checkConstantTypes(getOperation(), getType(), getValue());
362}
363
364OpFoldResult cir::ConstantOp::fold(FoldAdaptor /*adaptor*/) {
365 return getValue();
366}
367
368//===----------------------------------------------------------------------===//
369// ContinueOp
370//===----------------------------------------------------------------------===//
371
372LogicalResult cir::ContinueOp::verify() {
373 if (!getOperation()->getParentOfType<LoopOpInterface>())
374 return emitOpError("must be within a loop");
375 return success();
376}
377
378//===----------------------------------------------------------------------===//
379// CastOp
380//===----------------------------------------------------------------------===//
381
382LogicalResult cir::CastOp::verify() {
383 mlir::Type resType = getType();
384 mlir::Type srcType = getSrc().getType();
385
386 if (mlir::isa<cir::VectorType>(srcType) &&
387 mlir::isa<cir::VectorType>(resType)) {
388 // Use the element type of the vector to verify the cast kind. (Except for
389 // bitcast, see below.)
390 srcType = mlir::dyn_cast<cir::VectorType>(srcType).getElementType();
391 resType = mlir::dyn_cast<cir::VectorType>(resType).getElementType();
392 }
393
394 switch (getKind()) {
395 case cir::CastKind::int_to_bool: {
396 if (!mlir::isa<cir::BoolType>(resType))
397 return emitOpError() << "requires !cir.bool type for result";
398 if (!mlir::isa<cir::IntType>(srcType))
399 return emitOpError() << "requires !cir.int type for source";
400 return success();
401 }
402 case cir::CastKind::ptr_to_bool: {
403 if (!mlir::isa<cir::BoolType>(resType))
404 return emitOpError() << "requires !cir.bool type for result";
405 if (!mlir::isa<cir::PointerType>(srcType))
406 return emitOpError() << "requires !cir.ptr type for source";
407 return success();
408 }
409 case cir::CastKind::integral: {
410 if (!mlir::isa<cir::IntType>(resType))
411 return emitOpError() << "requires !cir.int type for result";
412 if (!mlir::isa<cir::IntType>(srcType))
413 return emitOpError() << "requires !cir.int type for source";
414 return success();
415 }
416 case cir::CastKind::array_to_ptrdecay: {
417 const auto arrayPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
418 const auto flatPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
419 if (!arrayPtrTy || !flatPtrTy)
420 return emitOpError() << "requires !cir.ptr type for source and result";
421
422 // TODO(CIR): Make sure the AddrSpace of both types are equals
423 return success();
424 }
425 case cir::CastKind::bitcast: {
426 // Handle the pointer types first.
427 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
428 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
429
430 if (srcPtrTy && resPtrTy) {
431 return success();
432 }
433
434 return success();
435 }
436 case cir::CastKind::floating: {
437 if (!mlir::isa<cir::FPTypeInterface>(srcType) ||
438 !mlir::isa<cir::FPTypeInterface>(resType))
439 return emitOpError() << "requires !cir.float type for source and result";
440 return success();
441 }
442 case cir::CastKind::float_to_int: {
443 if (!mlir::isa<cir::FPTypeInterface>(srcType))
444 return emitOpError() << "requires !cir.float type for source";
445 if (!mlir::dyn_cast<cir::IntType>(resType))
446 return emitOpError() << "requires !cir.int type for result";
447 return success();
448 }
449 case cir::CastKind::int_to_ptr: {
450 if (!mlir::dyn_cast<cir::IntType>(srcType))
451 return emitOpError() << "requires !cir.int type for source";
452 if (!mlir::dyn_cast<cir::PointerType>(resType))
453 return emitOpError() << "requires !cir.ptr type for result";
454 return success();
455 }
456 case cir::CastKind::ptr_to_int: {
457 if (!mlir::dyn_cast<cir::PointerType>(srcType))
458 return emitOpError() << "requires !cir.ptr type for source";
459 if (!mlir::dyn_cast<cir::IntType>(resType))
460 return emitOpError() << "requires !cir.int type for result";
461 return success();
462 }
463 case cir::CastKind::float_to_bool: {
464 if (!mlir::isa<cir::FPTypeInterface>(srcType))
465 return emitOpError() << "requires !cir.float type for source";
466 if (!mlir::isa<cir::BoolType>(resType))
467 return emitOpError() << "requires !cir.bool type for result";
468 return success();
469 }
470 case cir::CastKind::bool_to_int: {
471 if (!mlir::isa<cir::BoolType>(srcType))
472 return emitOpError() << "requires !cir.bool type for source";
473 if (!mlir::isa<cir::IntType>(resType))
474 return emitOpError() << "requires !cir.int type for result";
475 return success();
476 }
477 case cir::CastKind::int_to_float: {
478 if (!mlir::isa<cir::IntType>(srcType))
479 return emitOpError() << "requires !cir.int type for source";
480 if (!mlir::isa<cir::FPTypeInterface>(resType))
481 return emitOpError() << "requires !cir.float type for result";
482 return success();
483 }
484 case cir::CastKind::bool_to_float: {
485 if (!mlir::isa<cir::BoolType>(srcType))
486 return emitOpError() << "requires !cir.bool type for source";
487 if (!mlir::isa<cir::FPTypeInterface>(resType))
488 return emitOpError() << "requires !cir.float type for result";
489 return success();
490 }
491 case cir::CastKind::address_space: {
492 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
493 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
494 if (!srcPtrTy || !resPtrTy)
495 return emitOpError() << "requires !cir.ptr type for source and result";
496 if (srcPtrTy.getPointee() != resPtrTy.getPointee())
497 return emitOpError() << "requires two types differ in addrspace only";
498 return success();
499 }
500 case cir::CastKind::float_to_complex: {
501 if (!mlir::isa<cir::FPTypeInterface>(srcType))
502 return emitOpError() << "requires !cir.float type for source";
503 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
504 if (!resComplexTy)
505 return emitOpError() << "requires !cir.complex type for result";
506 if (srcType != resComplexTy.getElementType())
507 return emitOpError() << "requires source type match result element type";
508 return success();
509 }
510 case cir::CastKind::int_to_complex: {
511 if (!mlir::isa<cir::IntType>(srcType))
512 return emitOpError() << "requires !cir.int type for source";
513 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
514 if (!resComplexTy)
515 return emitOpError() << "requires !cir.complex type for result";
516 if (srcType != resComplexTy.getElementType())
517 return emitOpError() << "requires source type match result element type";
518 return success();
519 }
520 case cir::CastKind::float_complex_to_real: {
521 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
522 if (!srcComplexTy)
523 return emitOpError() << "requires !cir.complex type for source";
524 if (!mlir::isa<cir::FPTypeInterface>(resType))
525 return emitOpError() << "requires !cir.float type for result";
526 if (srcComplexTy.getElementType() != resType)
527 return emitOpError() << "requires source element type match result type";
528 return success();
529 }
530 case cir::CastKind::int_complex_to_real: {
531 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
532 if (!srcComplexTy)
533 return emitOpError() << "requires !cir.complex type for source";
534 if (!mlir::isa<cir::IntType>(resType))
535 return emitOpError() << "requires !cir.int type for result";
536 if (srcComplexTy.getElementType() != resType)
537 return emitOpError() << "requires source element type match result type";
538 return success();
539 }
540 case cir::CastKind::float_complex_to_bool: {
541 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
542 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
543 return emitOpError()
544 << "requires floating point !cir.complex type for source";
545 if (!mlir::isa<cir::BoolType>(resType))
546 return emitOpError() << "requires !cir.bool type for result";
547 return success();
548 }
549 case cir::CastKind::int_complex_to_bool: {
550 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
551 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
552 return emitOpError()
553 << "requires floating point !cir.complex type for source";
554 if (!mlir::isa<cir::BoolType>(resType))
555 return emitOpError() << "requires !cir.bool type for result";
556 return success();
557 }
558 case cir::CastKind::float_complex: {
559 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
560 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
561 return emitOpError()
562 << "requires floating point !cir.complex type for source";
563 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
564 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
565 return emitOpError()
566 << "requires floating point !cir.complex type for result";
567 return success();
568 }
569 case cir::CastKind::float_complex_to_int_complex: {
570 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
571 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
572 return emitOpError()
573 << "requires floating point !cir.complex type for source";
574 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
575 if (!resComplexTy || !resComplexTy.isIntegerComplex())
576 return emitOpError() << "requires integer !cir.complex type for result";
577 return success();
578 }
579 case cir::CastKind::int_complex: {
580 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
581 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
582 return emitOpError() << "requires integer !cir.complex type for source";
583 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
584 if (!resComplexTy || !resComplexTy.isIntegerComplex())
585 return emitOpError() << "requires integer !cir.complex type for result";
586 return success();
587 }
588 case cir::CastKind::int_complex_to_float_complex: {
589 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
590 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
591 return emitOpError() << "requires integer !cir.complex type for source";
592 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
593 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
594 return emitOpError()
595 << "requires floating point !cir.complex type for result";
596 return success();
597 }
598 default:
599 llvm_unreachable("Unknown CastOp kind?");
600 }
601}
602
603static bool isIntOrBoolCast(cir::CastOp op) {
604 auto kind = op.getKind();
605 return kind == cir::CastKind::bool_to_int ||
606 kind == cir::CastKind::int_to_bool || kind == cir::CastKind::integral;
607}
608
609static Value tryFoldCastChain(cir::CastOp op) {
610 cir::CastOp head = op, tail = op;
611
612 while (op) {
613 if (!isIntOrBoolCast(op))
614 break;
615 head = op;
616 op = head.getSrc().getDefiningOp<cir::CastOp>();
617 }
618
619 if (head == tail)
620 return {};
621
622 // if bool_to_int -> ... -> int_to_bool: take the bool
623 // as we had it was before all casts
624 if (head.getKind() == cir::CastKind::bool_to_int &&
625 tail.getKind() == cir::CastKind::int_to_bool)
626 return head.getSrc();
627
628 // if int_to_bool -> ... -> int_to_bool: take the result
629 // of the first one, as no other casts (and ext casts as well)
630 // don't change the first result
631 if (head.getKind() == cir::CastKind::int_to_bool &&
632 tail.getKind() == cir::CastKind::int_to_bool)
633 return head.getResult();
634
635 return {};
636}
637
638OpFoldResult cir::CastOp::fold(FoldAdaptor adaptor) {
639 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getSrc())) {
640 // Propagate poison value
641 return cir::PoisonAttr::get(getContext(), getType());
642 }
643
644 if (getSrc().getType() == getType()) {
645 switch (getKind()) {
646 case cir::CastKind::integral: {
647 // TODO: for sign differences, it's possible in certain conditions to
648 // create a new attribute that's capable of representing the source.
650 auto foldOrder = getSrc().getDefiningOp()->fold(foldResults);
651 if (foldOrder.succeeded() && mlir::isa<mlir::Attribute>(foldResults[0]))
652 return mlir::cast<mlir::Attribute>(foldResults[0]);
653 return {};
654 }
655 case cir::CastKind::bitcast:
656 case cir::CastKind::address_space:
657 case cir::CastKind::float_complex:
658 case cir::CastKind::int_complex: {
659 return getSrc();
660 }
661 default:
662 return {};
663 }
664 }
665 return tryFoldCastChain(*this);
666}
667
668//===----------------------------------------------------------------------===//
669// CallOp
670//===----------------------------------------------------------------------===//
671
672mlir::OperandRange cir::CallOp::getArgOperands() {
673 if (isIndirect())
674 return getArgs().drop_front(1);
675 return getArgs();
676}
677
678mlir::MutableOperandRange cir::CallOp::getArgOperandsMutable() {
679 mlir::MutableOperandRange args = getArgsMutable();
680 if (isIndirect())
681 return args.slice(1, args.size() - 1);
682 return args;
683}
684
685mlir::Value cir::CallOp::getIndirectCall() {
686 assert(isIndirect());
687 return getOperand(0);
688}
689
690/// Return the operand at index 'i'.
691Value cir::CallOp::getArgOperand(unsigned i) {
692 if (isIndirect())
693 ++i;
694 return getOperand(i);
695}
696
697/// Return the number of operands.
698unsigned cir::CallOp::getNumArgOperands() {
699 if (isIndirect())
700 return this->getOperation()->getNumOperands() - 1;
701 return this->getOperation()->getNumOperands();
702}
703
704static mlir::ParseResult parseCallCommon(mlir::OpAsmParser &parser,
705 mlir::OperationState &result) {
707 llvm::SMLoc opsLoc;
708 mlir::FlatSymbolRefAttr calleeAttr;
709 llvm::ArrayRef<mlir::Type> allResultTypes;
710
711 // If we cannot parse a string callee, it means this is an indirect call.
712 if (!parser
713 .parseOptionalAttribute(calleeAttr, CIRDialect::getCalleeAttrName(),
714 result.attributes)
715 .has_value()) {
716 OpAsmParser::UnresolvedOperand indirectVal;
717 // Do not resolve right now, since we need to figure out the type
718 if (parser.parseOperand(indirectVal).failed())
719 return failure();
720 ops.push_back(indirectVal);
721 }
722
723 if (parser.parseLParen())
724 return mlir::failure();
725
726 opsLoc = parser.getCurrentLocation();
727 if (parser.parseOperandList(ops))
728 return mlir::failure();
729 if (parser.parseRParen())
730 return mlir::failure();
731
732 if (parser.parseOptionalKeyword("nothrow").succeeded())
733 result.addAttribute(CIRDialect::getNoThrowAttrName(),
734 mlir::UnitAttr::get(parser.getContext()));
735
736 if (parser.parseOptionalKeyword("side_effect").succeeded()) {
737 if (parser.parseLParen().failed())
738 return failure();
739 cir::SideEffect sideEffect;
740 if (parseCIRKeyword<cir::SideEffect>(parser, sideEffect).failed())
741 return failure();
742 if (parser.parseRParen().failed())
743 return failure();
744 auto attr = cir::SideEffectAttr::get(parser.getContext(), sideEffect);
745 result.addAttribute(CIRDialect::getSideEffectAttrName(), attr);
746 }
747
748 if (parser.parseOptionalAttrDict(result.attributes))
749 return ::mlir::failure();
750
751 if (parser.parseColon())
752 return ::mlir::failure();
753
754 mlir::FunctionType opsFnTy;
755 if (parser.parseType(opsFnTy))
756 return mlir::failure();
757
758 allResultTypes = opsFnTy.getResults();
759 result.addTypes(allResultTypes);
760
761 if (parser.resolveOperands(ops, opsFnTy.getInputs(), opsLoc, result.operands))
762 return mlir::failure();
763
764 return mlir::success();
765}
766
767static void printCallCommon(mlir::Operation *op,
768 mlir::FlatSymbolRefAttr calleeSym,
769 mlir::Value indirectCallee,
770 mlir::OpAsmPrinter &printer, bool isNothrow,
771 cir::SideEffect sideEffect) {
772 printer << ' ';
773
774 auto callLikeOp = mlir::cast<cir::CIRCallOpInterface>(op);
775 auto ops = callLikeOp.getArgOperands();
776
777 if (calleeSym) {
778 // Direct calls
779 printer.printAttributeWithoutType(calleeSym);
780 } else {
781 // Indirect calls
782 assert(indirectCallee);
783 printer << indirectCallee;
784 }
785 printer << "(" << ops << ")";
786
787 if (isNothrow)
788 printer << " nothrow";
789
790 if (sideEffect != cir::SideEffect::All) {
791 printer << " side_effect(";
792 printer << stringifySideEffect(sideEffect);
793 printer << ")";
794 }
795
796 printer.printOptionalAttrDict(op->getAttrs(),
797 {CIRDialect::getCalleeAttrName(),
798 CIRDialect::getNoThrowAttrName(),
799 CIRDialect::getSideEffectAttrName()});
800
801 printer << " : ";
802 printer.printFunctionalType(op->getOperands().getTypes(),
803 op->getResultTypes());
804}
805
806mlir::ParseResult cir::CallOp::parse(mlir::OpAsmParser &parser,
807 mlir::OperationState &result) {
808 return parseCallCommon(parser, result);
809}
810
811void cir::CallOp::print(mlir::OpAsmPrinter &p) {
812 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() : nullptr;
813 cir::SideEffect sideEffect = getSideEffect();
814 printCallCommon(*this, getCalleeAttr(), indirectCallee, p, getNothrow(),
815 sideEffect);
816}
817
818static LogicalResult
819verifyCallCommInSymbolUses(mlir::Operation *op,
820 SymbolTableCollection &symbolTable) {
821 auto fnAttr =
822 op->getAttrOfType<FlatSymbolRefAttr>(CIRDialect::getCalleeAttrName());
823 if (!fnAttr) {
824 // This is an indirect call, thus we don't have to check the symbol uses.
825 return mlir::success();
826 }
827
828 auto fn = symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(op, fnAttr);
829 if (!fn)
830 return op->emitOpError() << "'" << fnAttr.getValue()
831 << "' does not reference a valid function";
832
833 auto callIf = dyn_cast<cir::CIRCallOpInterface>(op);
834 assert(callIf && "expected CIR call interface to be always available");
835
836 // Verify that the operand and result types match the callee. Note that
837 // argument-checking is disabled for functions without a prototype.
838 auto fnType = fn.getFunctionType();
839 if (!fn.getNoProto()) {
840 unsigned numCallOperands = callIf.getNumArgOperands();
841 unsigned numFnOpOperands = fnType.getNumInputs();
842
843 if (!fnType.isVarArg() && numCallOperands != numFnOpOperands)
844 return op->emitOpError("incorrect number of operands for callee");
845 if (fnType.isVarArg() && numCallOperands < numFnOpOperands)
846 return op->emitOpError("too few operands for callee");
847
848 for (unsigned i = 0, e = numFnOpOperands; i != e; ++i)
849 if (callIf.getArgOperand(i).getType() != fnType.getInput(i))
850 return op->emitOpError("operand type mismatch: expected operand type ")
851 << fnType.getInput(i) << ", but provided "
852 << op->getOperand(i).getType() << " for operand number " << i;
853 }
854
856
857 // Void function must not return any results.
858 if (fnType.hasVoidReturn() && op->getNumResults() != 0)
859 return op->emitOpError("callee returns void but call has results");
860
861 // Non-void function calls must return exactly one result.
862 if (!fnType.hasVoidReturn() && op->getNumResults() != 1)
863 return op->emitOpError("incorrect number of results for callee");
864
865 // Parent function and return value types must match.
866 if (!fnType.hasVoidReturn() &&
867 op->getResultTypes().front() != fnType.getReturnType()) {
868 return op->emitOpError("result type mismatch: expected ")
869 << fnType.getReturnType() << ", but provided "
870 << op->getResult(0).getType();
871 }
872
873 return mlir::success();
874}
875
876LogicalResult
877cir::CallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
878 return verifyCallCommInSymbolUses(*this, symbolTable);
879}
880
881//===----------------------------------------------------------------------===//
882// ReturnOp
883//===----------------------------------------------------------------------===//
884
885static mlir::LogicalResult checkReturnAndFunction(cir::ReturnOp op,
886 cir::FuncOp function) {
887 // ReturnOps currently only have a single optional operand.
888 if (op.getNumOperands() > 1)
889 return op.emitOpError() << "expects at most 1 return operand";
890
891 // Ensure returned type matches the function signature.
892 auto expectedTy = function.getFunctionType().getReturnType();
893 auto actualTy =
894 (op.getNumOperands() == 0 ? cir::VoidType::get(op.getContext())
895 : op.getOperand(0).getType());
896 if (actualTy != expectedTy)
897 return op.emitOpError() << "returns " << actualTy
898 << " but enclosing function returns " << expectedTy;
899
900 return mlir::success();
901}
902
903mlir::LogicalResult cir::ReturnOp::verify() {
904 // Returns can be present in multiple different scopes, get the
905 // wrapping function and start from there.
906 auto *fnOp = getOperation()->getParentOp();
907 while (!isa<cir::FuncOp>(fnOp))
908 fnOp = fnOp->getParentOp();
909
910 // Make sure return types match function return type.
911 if (checkReturnAndFunction(*this, cast<cir::FuncOp>(fnOp)).failed())
912 return failure();
913
914 return success();
915}
916
917//===----------------------------------------------------------------------===//
918// IfOp
919//===----------------------------------------------------------------------===//
920
921ParseResult cir::IfOp::parse(OpAsmParser &parser, OperationState &result) {
922 // create the regions for 'then'.
923 result.regions.reserve(2);
924 Region *thenRegion = result.addRegion();
925 Region *elseRegion = result.addRegion();
926
927 mlir::Builder &builder = parser.getBuilder();
928 OpAsmParser::UnresolvedOperand cond;
929 Type boolType = cir::BoolType::get(builder.getContext());
930
931 if (parser.parseOperand(cond) ||
932 parser.resolveOperand(cond, boolType, result.operands))
933 return failure();
934
935 // Parse 'then' region.
936 mlir::SMLoc parseThenLoc = parser.getCurrentLocation();
937 if (parser.parseRegion(*thenRegion, /*arguments=*/{}, /*argTypes=*/{}))
938 return failure();
939
940 if (ensureRegionTerm(parser, *thenRegion, parseThenLoc).failed())
941 return failure();
942
943 // If we find an 'else' keyword, parse the 'else' region.
944 if (!parser.parseOptionalKeyword("else")) {
945 mlir::SMLoc parseElseLoc = parser.getCurrentLocation();
946 if (parser.parseRegion(*elseRegion, /*arguments=*/{}, /*argTypes=*/{}))
947 return failure();
948 if (ensureRegionTerm(parser, *elseRegion, parseElseLoc).failed())
949 return failure();
950 }
951
952 // Parse the optional attribute list.
953 if (parser.parseOptionalAttrDict(result.attributes))
954 return failure();
955 return success();
956}
957
958void cir::IfOp::print(OpAsmPrinter &p) {
959 p << " " << getCondition() << " ";
960 mlir::Region &thenRegion = this->getThenRegion();
961 p.printRegion(thenRegion,
962 /*printEntryBlockArgs=*/false,
963 /*printBlockTerminators=*/!omitRegionTerm(thenRegion));
964
965 // Print the 'else' regions if it exists and has a block.
966 mlir::Region &elseRegion = this->getElseRegion();
967 if (!elseRegion.empty()) {
968 p << " else ";
969 p.printRegion(elseRegion,
970 /*printEntryBlockArgs=*/false,
971 /*printBlockTerminators=*/!omitRegionTerm(elseRegion));
972 }
973
974 p.printOptionalAttrDict(getOperation()->getAttrs());
975}
976
977/// Default callback for IfOp builders.
978void cir::buildTerminatedBody(OpBuilder &builder, Location loc) {
979 // add cir.yield to end of the block
980 builder.create<cir::YieldOp>(loc);
981}
982
983/// Given the region at `index`, or the parent operation if `index` is None,
984/// return the successor regions. These are the regions that may be selected
985/// during the flow of control. `operands` is a set of optional attributes that
986/// correspond to a constant value for each operand, or null if that operand is
987/// not a constant.
988void cir::IfOp::getSuccessorRegions(mlir::RegionBranchPoint point,
989 SmallVectorImpl<RegionSuccessor> &regions) {
990 // The `then` and the `else` region branch back to the parent operation.
991 if (!point.isParent()) {
992 regions.push_back(RegionSuccessor());
993 return;
994 }
995
996 // Don't consider the else region if it is empty.
997 Region *elseRegion = &this->getElseRegion();
998 if (elseRegion->empty())
999 elseRegion = nullptr;
1000
1001 // If the condition isn't constant, both regions may be executed.
1002 regions.push_back(RegionSuccessor(&getThenRegion()));
1003 // If the else region does not exist, it is not a viable successor.
1004 if (elseRegion)
1005 regions.push_back(RegionSuccessor(elseRegion));
1006
1007 return;
1008}
1009
1010void cir::IfOp::build(OpBuilder &builder, OperationState &result, Value cond,
1011 bool withElseRegion, BuilderCallbackRef thenBuilder,
1012 BuilderCallbackRef elseBuilder) {
1013 assert(thenBuilder && "the builder callback for 'then' must be present");
1014 result.addOperands(cond);
1015
1016 OpBuilder::InsertionGuard guard(builder);
1017 Region *thenRegion = result.addRegion();
1018 builder.createBlock(thenRegion);
1019 thenBuilder(builder, result.location);
1020
1021 Region *elseRegion = result.addRegion();
1022 if (!withElseRegion)
1023 return;
1024
1025 builder.createBlock(elseRegion);
1026 elseBuilder(builder, result.location);
1027}
1028
1029//===----------------------------------------------------------------------===//
1030// ScopeOp
1031//===----------------------------------------------------------------------===//
1032
1033/// Given the region at `index`, or the parent operation if `index` is None,
1034/// return the successor regions. These are the regions that may be selected
1035/// during the flow of control. `operands` is a set of optional attributes
1036/// that correspond to a constant value for each operand, or null if that
1037/// operand is not a constant.
1038void cir::ScopeOp::getSuccessorRegions(
1039 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &regions) {
1040 // The only region always branch back to the parent operation.
1041 if (!point.isParent()) {
1042 regions.push_back(RegionSuccessor(getODSResults(0)));
1043 return;
1044 }
1045
1046 // If the condition isn't constant, both regions may be executed.
1047 regions.push_back(RegionSuccessor(&getScopeRegion()));
1048}
1049
1050void cir::ScopeOp::build(
1051 OpBuilder &builder, OperationState &result,
1052 function_ref<void(OpBuilder &, Type &, Location)> scopeBuilder) {
1053 assert(scopeBuilder && "the builder callback for 'then' must be present");
1054
1055 OpBuilder::InsertionGuard guard(builder);
1056 Region *scopeRegion = result.addRegion();
1057 builder.createBlock(scopeRegion);
1059
1060 mlir::Type yieldTy;
1061 scopeBuilder(builder, yieldTy, result.location);
1062
1063 if (yieldTy)
1064 result.addTypes(TypeRange{yieldTy});
1065}
1066
1067void cir::ScopeOp::build(
1068 OpBuilder &builder, OperationState &result,
1069 function_ref<void(OpBuilder &, Location)> scopeBuilder) {
1070 assert(scopeBuilder && "the builder callback for 'then' must be present");
1071 OpBuilder::InsertionGuard guard(builder);
1072 Region *scopeRegion = result.addRegion();
1073 builder.createBlock(scopeRegion);
1075 scopeBuilder(builder, result.location);
1076}
1077
1078LogicalResult cir::ScopeOp::verify() {
1079 if (getRegion().empty()) {
1080 return emitOpError() << "cir.scope must not be empty since it should "
1081 "include at least an implicit cir.yield ";
1082 }
1083
1084 mlir::Block &lastBlock = getRegion().back();
1085 if (lastBlock.empty() || !lastBlock.mightHaveTerminator() ||
1086 !lastBlock.getTerminator()->hasTrait<OpTrait::IsTerminator>())
1087 return emitOpError() << "last block of cir.scope must be terminated";
1088 return success();
1089}
1090
1091//===----------------------------------------------------------------------===//
1092// BrOp
1093//===----------------------------------------------------------------------===//
1094
1095mlir::SuccessorOperands cir::BrOp::getSuccessorOperands(unsigned index) {
1096 assert(index == 0 && "invalid successor index");
1097 return mlir::SuccessorOperands(getDestOperandsMutable());
1098}
1099
1100Block *cir::BrOp::getSuccessorForOperands(ArrayRef<Attribute>) {
1101 return getDest();
1102}
1103
1104//===----------------------------------------------------------------------===//
1105// BrCondOp
1106//===----------------------------------------------------------------------===//
1107
1108mlir::SuccessorOperands cir::BrCondOp::getSuccessorOperands(unsigned index) {
1109 assert(index < getNumSuccessors() && "invalid successor index");
1110 return SuccessorOperands(index == 0 ? getDestOperandsTrueMutable()
1111 : getDestOperandsFalseMutable());
1112}
1113
1114Block *cir::BrCondOp::getSuccessorForOperands(ArrayRef<Attribute> operands) {
1115 if (IntegerAttr condAttr = dyn_cast_if_present<IntegerAttr>(operands.front()))
1116 return condAttr.getValue().isOne() ? getDestTrue() : getDestFalse();
1117 return nullptr;
1118}
1119
1120//===----------------------------------------------------------------------===//
1121// CaseOp
1122//===----------------------------------------------------------------------===//
1123
1124void cir::CaseOp::getSuccessorRegions(
1125 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &regions) {
1126 if (!point.isParent()) {
1127 regions.push_back(RegionSuccessor());
1128 return;
1129 }
1130 regions.push_back(RegionSuccessor(&getCaseRegion()));
1131}
1132
1133void cir::CaseOp::build(OpBuilder &builder, OperationState &result,
1134 ArrayAttr value, CaseOpKind kind,
1135 OpBuilder::InsertPoint &insertPoint) {
1136 OpBuilder::InsertionGuard guardSwitch(builder);
1137 result.addAttribute("value", value);
1138 result.getOrAddProperties<Properties>().kind =
1139 cir::CaseOpKindAttr::get(builder.getContext(), kind);
1140 Region *caseRegion = result.addRegion();
1141 builder.createBlock(caseRegion);
1142
1143 insertPoint = builder.saveInsertionPoint();
1144}
1145
1146//===----------------------------------------------------------------------===//
1147// SwitchOp
1148//===----------------------------------------------------------------------===//
1149
1150static ParseResult parseSwitchOp(OpAsmParser &parser, mlir::Region &regions,
1151 mlir::OpAsmParser::UnresolvedOperand &cond,
1152 mlir::Type &condType) {
1153 cir::IntType intCondType;
1154
1155 if (parser.parseLParen())
1156 return mlir::failure();
1157
1158 if (parser.parseOperand(cond))
1159 return mlir::failure();
1160 if (parser.parseColon())
1161 return mlir::failure();
1162 if (parser.parseCustomTypeWithFallback(intCondType))
1163 return mlir::failure();
1164 condType = intCondType;
1165
1166 if (parser.parseRParen())
1167 return mlir::failure();
1168 if (parser.parseRegion(regions, /*arguments=*/{}, /*argTypes=*/{}))
1169 return failure();
1170
1171 return mlir::success();
1172}
1173
1174static void printSwitchOp(OpAsmPrinter &p, cir::SwitchOp op,
1175 mlir::Region &bodyRegion, mlir::Value condition,
1176 mlir::Type condType) {
1177 p << "(";
1178 p << condition;
1179 p << " : ";
1180 p.printStrippedAttrOrType(condType);
1181 p << ")";
1182
1183 p << ' ';
1184 p.printRegion(bodyRegion, /*printEntryBlockArgs=*/false,
1185 /*printBlockTerminators=*/true);
1186}
1187
1188void cir::SwitchOp::getSuccessorRegions(
1189 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &region) {
1190 if (!point.isParent()) {
1191 region.push_back(RegionSuccessor());
1192 return;
1193 }
1194
1195 region.push_back(RegionSuccessor(&getBody()));
1196}
1197
1198void cir::SwitchOp::build(OpBuilder &builder, OperationState &result,
1199 Value cond, BuilderOpStateCallbackRef switchBuilder) {
1200 assert(switchBuilder && "the builder callback for regions must be present");
1201 OpBuilder::InsertionGuard guardSwitch(builder);
1202 Region *switchRegion = result.addRegion();
1203 builder.createBlock(switchRegion);
1204 result.addOperands({cond});
1205 switchBuilder(builder, result.location, result);
1206}
1207
1208void cir::SwitchOp::collectCases(llvm::SmallVectorImpl<CaseOp> &cases) {
1209 walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
1210 // Don't walk in nested switch op.
1211 if (isa<cir::SwitchOp>(op) && op != *this)
1212 return WalkResult::skip();
1213
1214 if (auto caseOp = dyn_cast<cir::CaseOp>(op))
1215 cases.push_back(caseOp);
1216
1217 return WalkResult::advance();
1218 });
1219}
1220
1221bool cir::SwitchOp::isSimpleForm(llvm::SmallVectorImpl<CaseOp> &cases) {
1222 collectCases(cases);
1223
1224 if (getBody().empty())
1225 return false;
1226
1227 if (!isa<YieldOp>(getBody().front().back()))
1228 return false;
1229
1230 if (!llvm::all_of(getBody().front(),
1231 [](Operation &op) { return isa<CaseOp, YieldOp>(op); }))
1232 return false;
1233
1234 return llvm::all_of(cases, [this](CaseOp op) {
1235 return op->getParentOfType<SwitchOp>() == *this;
1236 });
1237}
1238
1239//===----------------------------------------------------------------------===//
1240// SwitchFlatOp
1241//===----------------------------------------------------------------------===//
1242
1243void cir::SwitchFlatOp::build(OpBuilder &builder, OperationState &result,
1244 Value value, Block *defaultDestination,
1245 ValueRange defaultOperands,
1246 ArrayRef<APInt> caseValues,
1247 BlockRange caseDestinations,
1248 ArrayRef<ValueRange> caseOperands) {
1249
1250 std::vector<mlir::Attribute> caseValuesAttrs;
1251 for (const APInt &val : caseValues)
1252 caseValuesAttrs.push_back(cir::IntAttr::get(value.getType(), val));
1253 mlir::ArrayAttr attrs = ArrayAttr::get(builder.getContext(), caseValuesAttrs);
1254
1255 build(builder, result, value, defaultOperands, caseOperands, attrs,
1256 defaultDestination, caseDestinations);
1257}
1258
1259/// <cases> ::= `[` (case (`,` case )* )? `]`
1260/// <case> ::= integer `:` bb-id (`(` ssa-use-and-type-list `)`)?
1261static ParseResult parseSwitchFlatOpCases(
1262 OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues,
1263 SmallVectorImpl<Block *> &caseDestinations,
1265 &caseOperands,
1266 SmallVectorImpl<llvm::SmallVector<Type>> &caseOperandTypes) {
1267 if (failed(parser.parseLSquare()))
1268 return failure();
1269 if (succeeded(parser.parseOptionalRSquare()))
1270 return success();
1272
1273 auto parseCase = [&]() {
1274 int64_t value = 0;
1275 if (failed(parser.parseInteger(value)))
1276 return failure();
1277
1278 values.push_back(cir::IntAttr::get(flagType, value));
1279
1280 Block *destination;
1282 llvm::SmallVector<Type> operandTypes;
1283 if (parser.parseColon() || parser.parseSuccessor(destination))
1284 return failure();
1285 if (!parser.parseOptionalLParen()) {
1286 if (parser.parseOperandList(operands, OpAsmParser::Delimiter::None,
1287 /*allowResultNumber=*/false) ||
1288 parser.parseColonTypeList(operandTypes) || parser.parseRParen())
1289 return failure();
1290 }
1291 caseDestinations.push_back(destination);
1292 caseOperands.emplace_back(operands);
1293 caseOperandTypes.emplace_back(operandTypes);
1294 return success();
1295 };
1296 if (failed(parser.parseCommaSeparatedList(parseCase)))
1297 return failure();
1298
1299 caseValues = ArrayAttr::get(flagType.getContext(), values);
1300
1301 return parser.parseRSquare();
1302}
1303
1304static void printSwitchFlatOpCases(OpAsmPrinter &p, cir::SwitchFlatOp op,
1305 Type flagType, mlir::ArrayAttr caseValues,
1306 SuccessorRange caseDestinations,
1307 OperandRangeRange caseOperands,
1308 const TypeRangeRange &caseOperandTypes) {
1309 p << '[';
1310 p.printNewline();
1311 if (!caseValues) {
1312 p << ']';
1313 return;
1314 }
1315
1316 size_t index = 0;
1317 llvm::interleave(
1318 llvm::zip(caseValues, caseDestinations),
1319 [&](auto i) {
1320 p << " ";
1321 mlir::Attribute a = std::get<0>(i);
1322 p << mlir::cast<cir::IntAttr>(a).getValue();
1323 p << ": ";
1324 p.printSuccessorAndUseList(std::get<1>(i), caseOperands[index++]);
1325 },
1326 [&] {
1327 p << ',';
1328 p.printNewline();
1329 });
1330 p.printNewline();
1331 p << ']';
1332}
1333
1334//===----------------------------------------------------------------------===//
1335// GlobalOp
1336//===----------------------------------------------------------------------===//
1337
1338static ParseResult parseConstantValue(OpAsmParser &parser,
1339 mlir::Attribute &valueAttr) {
1340 NamedAttrList attr;
1341 return parser.parseAttribute(valueAttr, "value", attr);
1342}
1343
1344static void printConstant(OpAsmPrinter &p, Attribute value) {
1345 p.printAttribute(value);
1346}
1347
1348mlir::LogicalResult cir::GlobalOp::verify() {
1349 // Verify that the initial value, if present, is either a unit attribute or
1350 // an attribute CIR supports.
1351 if (getInitialValue().has_value()) {
1352 if (checkConstantTypes(getOperation(), getSymType(), *getInitialValue())
1353 .failed())
1354 return failure();
1355 }
1356
1357 // TODO(CIR): Many other checks for properties that haven't been upstreamed
1358 // yet.
1359
1360 return success();
1361}
1362
1363void cir::GlobalOp::build(
1364 OpBuilder &odsBuilder, OperationState &odsState, llvm::StringRef sym_name,
1365 mlir::Type sym_type, bool isConstant, cir::GlobalLinkageKind linkage,
1366 function_ref<void(OpBuilder &, Location)> ctorBuilder,
1367 function_ref<void(OpBuilder &, Location)> dtorBuilder) {
1368 odsState.addAttribute(getSymNameAttrName(odsState.name),
1369 odsBuilder.getStringAttr(sym_name));
1370 odsState.addAttribute(getSymTypeAttrName(odsState.name),
1371 mlir::TypeAttr::get(sym_type));
1372 if (isConstant)
1373 odsState.addAttribute(getConstantAttrName(odsState.name),
1374 odsBuilder.getUnitAttr());
1375
1376 cir::GlobalLinkageKindAttr linkageAttr =
1377 cir::GlobalLinkageKindAttr::get(odsBuilder.getContext(), linkage);
1378 odsState.addAttribute(getLinkageAttrName(odsState.name), linkageAttr);
1379
1380 Region *ctorRegion = odsState.addRegion();
1381 if (ctorBuilder) {
1382 odsBuilder.createBlock(ctorRegion);
1383 ctorBuilder(odsBuilder, odsState.location);
1384 }
1385
1386 Region *dtorRegion = odsState.addRegion();
1387 if (dtorBuilder) {
1388 odsBuilder.createBlock(dtorRegion);
1389 dtorBuilder(odsBuilder, odsState.location);
1390 }
1391
1392 odsState.addAttribute(getGlobalVisibilityAttrName(odsState.name),
1393 cir::VisibilityAttr::get(odsBuilder.getContext()));
1394}
1395
1396/// Given the region at `index`, or the parent operation if `index` is None,
1397/// return the successor regions. These are the regions that may be selected
1398/// during the flow of control. `operands` is a set of optional attributes that
1399/// correspond to a constant value for each operand, or null if that operand is
1400/// not a constant.
1401void cir::GlobalOp::getSuccessorRegions(
1402 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &regions) {
1403 // The `ctor` and `dtor` regions always branch back to the parent operation.
1404 if (!point.isParent()) {
1405 regions.push_back(RegionSuccessor());
1406 return;
1407 }
1408
1409 // Don't consider the ctor region if it is empty.
1410 Region *ctorRegion = &this->getCtorRegion();
1411 if (ctorRegion->empty())
1412 ctorRegion = nullptr;
1413
1414 // Don't consider the dtor region if it is empty.
1415 Region *dtorRegion = &this->getCtorRegion();
1416 if (dtorRegion->empty())
1417 dtorRegion = nullptr;
1418
1419 // If the condition isn't constant, both regions may be executed.
1420 if (ctorRegion)
1421 regions.push_back(RegionSuccessor(ctorRegion));
1422 if (dtorRegion)
1423 regions.push_back(RegionSuccessor(dtorRegion));
1424}
1425
1426static void printGlobalOpTypeAndInitialValue(OpAsmPrinter &p, cir::GlobalOp op,
1427 TypeAttr type, Attribute initAttr,
1428 mlir::Region &ctorRegion,
1429 mlir::Region &dtorRegion) {
1430 auto printType = [&]() { p << ": " << type; };
1431 if (!op.isDeclaration()) {
1432 p << "= ";
1433 if (!ctorRegion.empty()) {
1434 p << "ctor ";
1435 printType();
1436 p << " ";
1437 p.printRegion(ctorRegion,
1438 /*printEntryBlockArgs=*/false,
1439 /*printBlockTerminators=*/false);
1440 } else {
1441 // This also prints the type...
1442 if (initAttr)
1443 printConstant(p, initAttr);
1444 }
1445
1446 if (!dtorRegion.empty()) {
1447 p << " dtor ";
1448 p.printRegion(dtorRegion,
1449 /*printEntryBlockArgs=*/false,
1450 /*printBlockTerminators=*/false);
1451 }
1452 } else {
1453 printType();
1454 }
1455}
1456
1457static ParseResult parseGlobalOpTypeAndInitialValue(OpAsmParser &parser,
1458 TypeAttr &typeAttr,
1459 Attribute &initialValueAttr,
1460 mlir::Region &ctorRegion,
1461 mlir::Region &dtorRegion) {
1462 mlir::Type opTy;
1463 if (parser.parseOptionalEqual().failed()) {
1464 // Absence of equal means a declaration, so we need to parse the type.
1465 // cir.global @a : !cir.int<s, 32>
1466 if (parser.parseColonType(opTy))
1467 return failure();
1468 } else {
1469 // Parse contructor, example:
1470 // cir.global @rgb = ctor : type { ... }
1471 if (!parser.parseOptionalKeyword("ctor")) {
1472 if (parser.parseColonType(opTy))
1473 return failure();
1474 auto parseLoc = parser.getCurrentLocation();
1475 if (parser.parseRegion(ctorRegion, /*arguments=*/{}, /*argTypes=*/{}))
1476 return failure();
1477 if (ensureRegionTerm(parser, ctorRegion, parseLoc).failed())
1478 return failure();
1479 } else {
1480 // Parse constant with initializer, examples:
1481 // cir.global @y = 3.400000e+00 : f32
1482 // cir.global @rgb = #cir.const_array<[...] : !cir.array<i8 x 3>>
1483 if (parseConstantValue(parser, initialValueAttr).failed())
1484 return failure();
1485
1486 assert(mlir::isa<mlir::TypedAttr>(initialValueAttr) &&
1487 "Non-typed attrs shouldn't appear here.");
1488 auto typedAttr = mlir::cast<mlir::TypedAttr>(initialValueAttr);
1489 opTy = typedAttr.getType();
1490 }
1491
1492 // Parse destructor, example:
1493 // dtor { ... }
1494 if (!parser.parseOptionalKeyword("dtor")) {
1495 auto parseLoc = parser.getCurrentLocation();
1496 if (parser.parseRegion(dtorRegion, /*arguments=*/{}, /*argTypes=*/{}))
1497 return failure();
1498 if (ensureRegionTerm(parser, dtorRegion, parseLoc).failed())
1499 return failure();
1500 }
1501 }
1502
1503 typeAttr = TypeAttr::get(opTy);
1504 return success();
1505}
1506
1507//===----------------------------------------------------------------------===//
1508// GetGlobalOp
1509//===----------------------------------------------------------------------===//
1510
1511LogicalResult
1512cir::GetGlobalOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1513 // Verify that the result type underlying pointer type matches the type of
1514 // the referenced cir.global or cir.func op.
1515 mlir::Operation *op =
1516 symbolTable.lookupNearestSymbolFrom(*this, getNameAttr());
1517 if (op == nullptr || !(isa<GlobalOp>(op) || isa<FuncOp>(op)))
1518 return emitOpError("'")
1519 << getName()
1520 << "' does not reference a valid cir.global or cir.func";
1521
1522 mlir::Type symTy;
1523 if (auto g = dyn_cast<GlobalOp>(op)) {
1524 symTy = g.getSymType();
1527 } else if (auto f = dyn_cast<FuncOp>(op)) {
1528 symTy = f.getFunctionType();
1529 } else {
1530 llvm_unreachable("Unexpected operation for GetGlobalOp");
1531 }
1532
1533 auto resultType = dyn_cast<PointerType>(getAddr().getType());
1534 if (!resultType || symTy != resultType.getPointee())
1535 return emitOpError("result type pointee type '")
1536 << resultType.getPointee() << "' does not match type " << symTy
1537 << " of the global @" << getName();
1538
1539 return success();
1540}
1541
1542//===----------------------------------------------------------------------===//
1543// VTableAddrPointOp
1544//===----------------------------------------------------------------------===//
1545
1546LogicalResult
1547cir::VTableAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1548 StringRef name = getName();
1549
1550 // Verify that the result type underlying pointer type matches the type of
1551 // the referenced cir.global.
1552 auto op =
1553 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*this, getNameAttr());
1554 if (!op)
1555 return emitOpError("'")
1556 << name << "' does not reference a valid cir.global";
1557 std::optional<mlir::Attribute> init = op.getInitialValue();
1558 if (!init)
1559 return success();
1560 if (!isa<cir::VTableAttr>(*init))
1561 return emitOpError("Expected #cir.vtable in initializer for global '")
1562 << name << "'";
1563 return success();
1564}
1565
1566//===----------------------------------------------------------------------===//
1567// VTTAddrPointOp
1568//===----------------------------------------------------------------------===//
1569
1570LogicalResult
1571cir::VTTAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1572 // VTT ptr is not coming from a symbol.
1573 if (!getName())
1574 return success();
1575 StringRef name = *getName();
1576
1577 // Verify that the result type underlying pointer type matches the type of
1578 // the referenced cir.global op.
1579 auto op =
1580 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*this, getNameAttr());
1581 if (!op)
1582 return emitOpError("'")
1583 << name << "' does not reference a valid cir.global";
1584 std::optional<mlir::Attribute> init = op.getInitialValue();
1585 if (!init)
1586 return success();
1587 if (!isa<cir::ConstArrayAttr>(*init))
1588 return emitOpError(
1589 "Expected constant array in initializer for global VTT '")
1590 << name << "'";
1591 return success();
1592}
1593
1594LogicalResult cir::VTTAddrPointOp::verify() {
1595 // The operation uses either a symbol or a value to operate, but not both
1596 if (getName() && getSymAddr())
1597 return emitOpError("should use either a symbol or value, but not both");
1598
1599 // If not a symbol, stick with the concrete type used for getSymAddr.
1600 if (getSymAddr())
1601 return success();
1602
1603 mlir::Type resultType = getAddr().getType();
1604 mlir::Type resTy = cir::PointerType::get(
1605 cir::PointerType::get(cir::VoidType::get(getContext())));
1606
1607 if (resultType != resTy)
1608 return emitOpError("result type must be ")
1609 << resTy << ", but provided result type is " << resultType;
1610 return success();
1611}
1612
1613//===----------------------------------------------------------------------===//
1614// FuncOp
1615//===----------------------------------------------------------------------===//
1616
1617/// Returns the name used for the linkage attribute. This *must* correspond to
1618/// the name of the attribute in ODS.
1619static llvm::StringRef getLinkageAttrNameString() { return "linkage"; }
1620
1621void cir::FuncOp::build(OpBuilder &builder, OperationState &result,
1622 StringRef name, FuncType type,
1623 GlobalLinkageKind linkage) {
1624 result.addRegion();
1625 result.addAttribute(SymbolTable::getSymbolAttrName(),
1626 builder.getStringAttr(name));
1627 result.addAttribute(getFunctionTypeAttrName(result.name),
1628 TypeAttr::get(type));
1629 result.addAttribute(
1631 GlobalLinkageKindAttr::get(builder.getContext(), linkage));
1632 result.addAttribute(getGlobalVisibilityAttrName(result.name),
1633 cir::VisibilityAttr::get(builder.getContext()));
1634}
1635
1636ParseResult cir::FuncOp::parse(OpAsmParser &parser, OperationState &state) {
1637 llvm::SMLoc loc = parser.getCurrentLocation();
1638 mlir::Builder &builder = parser.getBuilder();
1639
1640 mlir::StringAttr builtinNameAttr = getBuiltinAttrName(state.name);
1641 mlir::StringAttr coroutineNameAttr = getCoroutineAttrName(state.name);
1642 mlir::StringAttr lambdaNameAttr = getLambdaAttrName(state.name);
1643 mlir::StringAttr noProtoNameAttr = getNoProtoAttrName(state.name);
1644 mlir::StringAttr visNameAttr = getSymVisibilityAttrName(state.name);
1645 mlir::StringAttr visibilityNameAttr = getGlobalVisibilityAttrName(state.name);
1646 mlir::StringAttr dsoLocalNameAttr = getDsoLocalAttrName(state.name);
1647
1648 if (::mlir::succeeded(parser.parseOptionalKeyword(builtinNameAttr.strref())))
1649 state.addAttribute(builtinNameAttr, parser.getBuilder().getUnitAttr());
1650 if (::mlir::succeeded(
1651 parser.parseOptionalKeyword(coroutineNameAttr.strref())))
1652 state.addAttribute(coroutineNameAttr, parser.getBuilder().getUnitAttr());
1653 if (::mlir::succeeded(parser.parseOptionalKeyword(lambdaNameAttr.strref())))
1654 state.addAttribute(lambdaNameAttr, parser.getBuilder().getUnitAttr());
1655 if (parser.parseOptionalKeyword(noProtoNameAttr).succeeded())
1656 state.addAttribute(noProtoNameAttr, parser.getBuilder().getUnitAttr());
1657
1658 // Default to external linkage if no keyword is provided.
1659 state.addAttribute(getLinkageAttrNameString(),
1660 GlobalLinkageKindAttr::get(
1661 parser.getContext(),
1663 parser, GlobalLinkageKind::ExternalLinkage)));
1664
1665 ::llvm::StringRef visAttrStr;
1666 if (parser.parseOptionalKeyword(&visAttrStr, {"private", "public", "nested"})
1667 .succeeded()) {
1668 state.addAttribute(visNameAttr,
1669 parser.getBuilder().getStringAttr(visAttrStr));
1670 }
1671
1672 cir::VisibilityAttr cirVisibilityAttr;
1673 parseVisibilityAttr(parser, cirVisibilityAttr);
1674 state.addAttribute(visibilityNameAttr, cirVisibilityAttr);
1675
1676 if (parser.parseOptionalKeyword(dsoLocalNameAttr).succeeded())
1677 state.addAttribute(dsoLocalNameAttr, parser.getBuilder().getUnitAttr());
1678
1679 StringAttr nameAttr;
1680 if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
1681 state.attributes))
1682 return failure();
1686 bool isVariadic = false;
1687 if (function_interface_impl::parseFunctionSignatureWithArguments(
1688 parser, /*allowVariadic=*/true, arguments, isVariadic, resultTypes,
1689 resultAttrs))
1690 return failure();
1692 for (OpAsmParser::Argument &arg : arguments)
1693 argTypes.push_back(arg.type);
1694
1695 if (resultTypes.size() > 1) {
1696 return parser.emitError(
1697 loc, "functions with multiple return types are not supported");
1698 }
1699
1700 mlir::Type returnType =
1701 (resultTypes.empty() ? cir::VoidType::get(builder.getContext())
1702 : resultTypes.front());
1703
1704 cir::FuncType fnType = cir::FuncType::get(argTypes, returnType, isVariadic);
1705 if (!fnType)
1706 return failure();
1707 state.addAttribute(getFunctionTypeAttrName(state.name),
1708 TypeAttr::get(fnType));
1709
1710 bool hasAlias = false;
1711 mlir::StringAttr aliaseeNameAttr = getAliaseeAttrName(state.name);
1712 if (parser.parseOptionalKeyword("alias").succeeded()) {
1713 if (parser.parseLParen().failed())
1714 return failure();
1715 mlir::StringAttr aliaseeAttr;
1716 if (parser.parseOptionalSymbolName(aliaseeAttr).failed())
1717 return failure();
1718 state.addAttribute(aliaseeNameAttr, FlatSymbolRefAttr::get(aliaseeAttr));
1719 if (parser.parseRParen().failed())
1720 return failure();
1721 hasAlias = true;
1722 }
1723
1724 auto parseGlobalDtorCtor =
1725 [&](StringRef keyword,
1726 llvm::function_ref<void(std::optional<int> prio)> createAttr)
1727 -> mlir::LogicalResult {
1728 if (mlir::succeeded(parser.parseOptionalKeyword(keyword))) {
1729 std::optional<int> priority;
1730 if (mlir::succeeded(parser.parseOptionalLParen())) {
1731 auto parsedPriority = mlir::FieldParser<int>::parse(parser);
1732 if (mlir::failed(parsedPriority))
1733 return parser.emitError(parser.getCurrentLocation(),
1734 "failed to parse 'priority', of type 'int'");
1735 priority = parsedPriority.value_or(int());
1736 // Parse literal ')'
1737 if (parser.parseRParen())
1738 return failure();
1739 }
1740 createAttr(priority);
1741 }
1742 return success();
1743 };
1744
1745 if (parseGlobalDtorCtor("global_ctor", [&](std::optional<int> priority) {
1746 mlir::IntegerAttr globalCtorPriorityAttr =
1747 builder.getI32IntegerAttr(priority.value_or(65535));
1748 state.addAttribute(getGlobalCtorPriorityAttrName(state.name),
1749 globalCtorPriorityAttr);
1750 }).failed())
1751 return failure();
1752
1753 if (parseGlobalDtorCtor("global_dtor", [&](std::optional<int> priority) {
1754 mlir::IntegerAttr globalDtorPriorityAttr =
1755 builder.getI32IntegerAttr(priority.value_or(65535));
1756 state.addAttribute(getGlobalDtorPriorityAttrName(state.name),
1757 globalDtorPriorityAttr);
1758 }).failed())
1759 return failure();
1760
1761 // Parse the optional function body.
1762 auto *body = state.addRegion();
1763 OptionalParseResult parseResult = parser.parseOptionalRegion(
1764 *body, arguments, /*enableNameShadowing=*/false);
1765 if (parseResult.has_value()) {
1766 if (hasAlias)
1767 return parser.emitError(loc, "function alias shall not have a body");
1768 if (failed(*parseResult))
1769 return failure();
1770 // Function body was parsed, make sure its not empty.
1771 if (body->empty())
1772 return parser.emitError(loc, "expected non-empty function body");
1773 }
1774
1775 return success();
1776}
1777
1778// This function corresponds to `llvm::GlobalValue::isDeclaration` and should
1779// have a similar implementation. We don't currently ifuncs or materializable
1780// functions, but those should be handled here as they are implemented.
1781bool cir::FuncOp::isDeclaration() {
1783
1784 std::optional<StringRef> aliasee = getAliasee();
1785 if (!aliasee)
1786 return getFunctionBody().empty();
1787
1788 // Aliases are always definitions.
1789 return false;
1790}
1791
1792mlir::Region *cir::FuncOp::getCallableRegion() {
1793 // TODO(CIR): This function will have special handling for aliases and a
1794 // check for an external function, once those features have been upstreamed.
1795 return &getBody();
1796}
1797
1798void cir::FuncOp::print(OpAsmPrinter &p) {
1799 if (getBuiltin())
1800 p << " builtin";
1801
1802 if (getCoroutine())
1803 p << " coroutine";
1804
1805 if (getLambda())
1806 p << " lambda";
1807
1808 if (getNoProto())
1809 p << " no_proto";
1810
1811 if (getComdat())
1812 p << " comdat";
1813
1814 if (getLinkage() != GlobalLinkageKind::ExternalLinkage)
1815 p << ' ' << stringifyGlobalLinkageKind(getLinkage());
1816
1817 mlir::SymbolTable::Visibility vis = getVisibility();
1818 if (vis != mlir::SymbolTable::Visibility::Public)
1819 p << ' ' << vis;
1820
1821 cir::VisibilityAttr cirVisibilityAttr = getGlobalVisibilityAttr();
1822 if (!cirVisibilityAttr.isDefault()) {
1823 p << ' ';
1824 printVisibilityAttr(p, cirVisibilityAttr);
1825 }
1826
1827 if (getDsoLocal())
1828 p << " dso_local";
1829
1830 p << ' ';
1831 p.printSymbolName(getSymName());
1832 cir::FuncType fnType = getFunctionType();
1833 function_interface_impl::printFunctionSignature(
1834 p, *this, fnType.getInputs(), fnType.isVarArg(), fnType.getReturnTypes());
1835
1836 if (std::optional<StringRef> aliaseeName = getAliasee()) {
1837 p << " alias(";
1838 p.printSymbolName(*aliaseeName);
1839 p << ")";
1840 }
1841
1842 if (auto globalCtorPriority = getGlobalCtorPriority()) {
1843 p << " global_ctor";
1844 if (globalCtorPriority.value() != 65535)
1845 p << "(" << globalCtorPriority.value() << ")";
1846 }
1847
1848 if (auto globalDtorPriority = getGlobalDtorPriority()) {
1849 p << " global_dtor";
1850 if (globalDtorPriority.value() != 65535)
1851 p << "(" << globalDtorPriority.value() << ")";
1852 }
1853
1854 // Print the body if this is not an external function.
1855 Region &body = getOperation()->getRegion(0);
1856 if (!body.empty()) {
1857 p << ' ';
1858 p.printRegion(body, /*printEntryBlockArgs=*/false,
1859 /*printBlockTerminators=*/true);
1860 }
1861}
1862
1863mlir::LogicalResult cir::FuncOp::verify() {
1864
1865 llvm::SmallSet<llvm::StringRef, 16> labels;
1866 llvm::SmallSet<llvm::StringRef, 16> gotos;
1867
1868 getOperation()->walk([&](mlir::Operation *op) {
1869 if (auto lab = dyn_cast<cir::LabelOp>(op)) {
1870 labels.insert(lab.getLabel());
1871 } else if (auto goTo = dyn_cast<cir::GotoOp>(op)) {
1872 gotos.insert(goTo.getLabel());
1873 }
1874 });
1875
1876 if (!labels.empty() || !gotos.empty()) {
1877 llvm::SmallSet<llvm::StringRef, 16> mismatched =
1878 llvm::set_difference(gotos, labels);
1879
1880 if (!mismatched.empty())
1881 return emitOpError() << "goto/label mismatch";
1882 }
1883 return success();
1884}
1885
1886//===----------------------------------------------------------------------===//
1887// BinOp
1888//===----------------------------------------------------------------------===//
1889LogicalResult cir::BinOp::verify() {
1890 bool noWrap = getNoUnsignedWrap() || getNoSignedWrap();
1891 bool saturated = getSaturated();
1892
1893 if (!isa<cir::IntType>(getType()) && noWrap)
1894 return emitError()
1895 << "only operations on integer values may have nsw/nuw flags";
1896
1897 bool noWrapOps = getKind() == cir::BinOpKind::Add ||
1898 getKind() == cir::BinOpKind::Sub ||
1899 getKind() == cir::BinOpKind::Mul;
1900
1901 bool saturatedOps =
1902 getKind() == cir::BinOpKind::Add || getKind() == cir::BinOpKind::Sub;
1903
1904 if (noWrap && !noWrapOps)
1905 return emitError() << "The nsw/nuw flags are applicable to opcodes: 'add', "
1906 "'sub' and 'mul'";
1907 if (saturated && !saturatedOps)
1908 return emitError() << "The saturated flag is applicable to opcodes: 'add' "
1909 "and 'sub'";
1910 if (noWrap && saturated)
1911 return emitError() << "The nsw/nuw flags and the saturated flag are "
1912 "mutually exclusive";
1913
1914 return mlir::success();
1915}
1916
1917//===----------------------------------------------------------------------===//
1918// TernaryOp
1919//===----------------------------------------------------------------------===//
1920
1921/// Given the region at `point`, or the parent operation if `point` is None,
1922/// return the successor regions. These are the regions that may be selected
1923/// during the flow of control. `operands` is a set of optional attributes that
1924/// correspond to a constant value for each operand, or null if that operand is
1925/// not a constant.
1926void cir::TernaryOp::getSuccessorRegions(
1927 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &regions) {
1928 // The `true` and the `false` region branch back to the parent operation.
1929 if (!point.isParent()) {
1930 regions.push_back(RegionSuccessor(this->getODSResults(0)));
1931 return;
1932 }
1933
1934 // When branching from the parent operation, both the true and false
1935 // regions are considered possible successors
1936 regions.push_back(RegionSuccessor(&getTrueRegion()));
1937 regions.push_back(RegionSuccessor(&getFalseRegion()));
1938}
1939
1940void cir::TernaryOp::build(
1941 OpBuilder &builder, OperationState &result, Value cond,
1942 function_ref<void(OpBuilder &, Location)> trueBuilder,
1943 function_ref<void(OpBuilder &, Location)> falseBuilder) {
1944 result.addOperands(cond);
1945 OpBuilder::InsertionGuard guard(builder);
1946 Region *trueRegion = result.addRegion();
1947 Block *block = builder.createBlock(trueRegion);
1948 trueBuilder(builder, result.location);
1949 Region *falseRegion = result.addRegion();
1950 builder.createBlock(falseRegion);
1951 falseBuilder(builder, result.location);
1952
1953 auto yield = dyn_cast<YieldOp>(block->getTerminator());
1954 assert((yield && yield.getNumOperands() <= 1) &&
1955 "expected zero or one result type");
1956 if (yield.getNumOperands() == 1)
1957 result.addTypes(TypeRange{yield.getOperandTypes().front()});
1958}
1959
1960//===----------------------------------------------------------------------===//
1961// SelectOp
1962//===----------------------------------------------------------------------===//
1963
1964OpFoldResult cir::SelectOp::fold(FoldAdaptor adaptor) {
1965 mlir::Attribute condition = adaptor.getCondition();
1966 if (condition) {
1967 bool conditionValue = mlir::cast<cir::BoolAttr>(condition).getValue();
1968 return conditionValue ? getTrueValue() : getFalseValue();
1969 }
1970
1971 // cir.select if %0 then x else x -> x
1972 mlir::Attribute trueValue = adaptor.getTrueValue();
1973 mlir::Attribute falseValue = adaptor.getFalseValue();
1974 if (trueValue == falseValue)
1975 return trueValue;
1976 if (getTrueValue() == getFalseValue())
1977 return getTrueValue();
1978
1979 return {};
1980}
1981
1982//===----------------------------------------------------------------------===//
1983// ShiftOp
1984//===----------------------------------------------------------------------===//
1985LogicalResult cir::ShiftOp::verify() {
1986 mlir::Operation *op = getOperation();
1987 auto op0VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(0).getType());
1988 auto op1VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(1).getType());
1989 if (!op0VecTy ^ !op1VecTy)
1990 return emitOpError() << "input types cannot be one vector and one scalar";
1991
1992 if (op0VecTy) {
1993 if (op0VecTy.getSize() != op1VecTy.getSize())
1994 return emitOpError() << "input vector types must have the same size";
1995
1996 auto opResultTy = mlir::dyn_cast<cir::VectorType>(getType());
1997 if (!opResultTy)
1998 return emitOpError() << "the type of the result must be a vector "
1999 << "if it is vector shift";
2000
2001 auto op0VecEleTy = mlir::cast<cir::IntType>(op0VecTy.getElementType());
2002 auto op1VecEleTy = mlir::cast<cir::IntType>(op1VecTy.getElementType());
2003 if (op0VecEleTy.getWidth() != op1VecEleTy.getWidth())
2004 return emitOpError()
2005 << "vector operands do not have the same elements sizes";
2006
2007 auto resVecEleTy = mlir::cast<cir::IntType>(opResultTy.getElementType());
2008 if (op0VecEleTy.getWidth() != resVecEleTy.getWidth())
2009 return emitOpError() << "vector operands and result type do not have the "
2010 "same elements sizes";
2011 }
2012
2013 return mlir::success();
2014}
2015
2016//===----------------------------------------------------------------------===//
2017// LabelOp Definitions
2018//===----------------------------------------------------------------------===//
2019
2020LogicalResult cir::LabelOp::verify() {
2021 mlir::Operation *op = getOperation();
2022 mlir::Block *blk = op->getBlock();
2023 if (&blk->front() != op)
2024 return emitError() << "must be the first operation in a block";
2025
2026 return mlir::success();
2027}
2028
2029//===----------------------------------------------------------------------===//
2030// UnaryOp
2031//===----------------------------------------------------------------------===//
2032
2033LogicalResult cir::UnaryOp::verify() {
2034 switch (getKind()) {
2035 case cir::UnaryOpKind::Inc:
2036 case cir::UnaryOpKind::Dec:
2037 case cir::UnaryOpKind::Plus:
2038 case cir::UnaryOpKind::Minus:
2039 case cir::UnaryOpKind::Not:
2040 // Nothing to verify.
2041 return success();
2042 }
2043
2044 llvm_unreachable("Unknown UnaryOp kind?");
2045}
2046
2047static bool isBoolNot(cir::UnaryOp op) {
2048 return isa<cir::BoolType>(op.getInput().getType()) &&
2049 op.getKind() == cir::UnaryOpKind::Not;
2050}
2051
2052// This folder simplifies the sequential boolean not operations.
2053// For instance, the next two unary operations will be eliminated:
2054//
2055// ```mlir
2056// %1 = cir.unary(not, %0) : !cir.bool, !cir.bool
2057// %2 = cir.unary(not, %1) : !cir.bool, !cir.bool
2058// ```
2059//
2060// and the argument of the first one (%0) will be used instead.
2061OpFoldResult cir::UnaryOp::fold(FoldAdaptor adaptor) {
2062 if (auto poison =
2063 mlir::dyn_cast_if_present<cir::PoisonAttr>(adaptor.getInput())) {
2064 // Propagate poison values
2065 return poison;
2066 }
2067
2068 if (isBoolNot(*this))
2069 if (auto previous = getInput().getDefiningOp<cir::UnaryOp>())
2070 if (isBoolNot(previous))
2071 return previous.getInput();
2072
2073 return {};
2074}
2075
2076//===----------------------------------------------------------------------===//
2077// CopyOp Definitions
2078//===----------------------------------------------------------------------===//
2079
2080LogicalResult cir::CopyOp::verify() {
2081 // A data layout is required for us to know the number of bytes to be copied.
2082 if (!getType().getPointee().hasTrait<DataLayoutTypeInterface::Trait>())
2083 return emitError() << "missing data layout for pointee type";
2084
2085 if (getSrc() == getDst())
2086 return emitError() << "source and destination are the same";
2087
2088 return mlir::success();
2089}
2090
2091//===----------------------------------------------------------------------===//
2092// GetMemberOp Definitions
2093//===----------------------------------------------------------------------===//
2094
2095LogicalResult cir::GetMemberOp::verify() {
2096 const auto recordTy = dyn_cast<RecordType>(getAddrTy().getPointee());
2097 if (!recordTy)
2098 return emitError() << "expected pointer to a record type";
2099
2100 if (recordTy.getMembers().size() <= getIndex())
2101 return emitError() << "member index out of bounds";
2102
2103 if (recordTy.getMembers()[getIndex()] != getType().getPointee())
2104 return emitError() << "member type mismatch";
2105
2106 return mlir::success();
2107}
2108
2109//===----------------------------------------------------------------------===//
2110// VecCreateOp
2111//===----------------------------------------------------------------------===//
2112
2113OpFoldResult cir::VecCreateOp::fold(FoldAdaptor adaptor) {
2114 if (llvm::any_of(getElements(), [](mlir::Value value) {
2115 return !value.getDefiningOp<cir::ConstantOp>();
2116 }))
2117 return {};
2118
2119 return cir::ConstVectorAttr::get(
2120 getType(), mlir::ArrayAttr::get(getContext(), adaptor.getElements()));
2121}
2122
2123LogicalResult cir::VecCreateOp::verify() {
2124 // Verify that the number of arguments matches the number of elements in the
2125 // vector, and that the type of all the arguments matches the type of the
2126 // elements in the vector.
2127 const cir::VectorType vecTy = getType();
2128 if (getElements().size() != vecTy.getSize()) {
2129 return emitOpError() << "operand count of " << getElements().size()
2130 << " doesn't match vector type " << vecTy
2131 << " element count of " << vecTy.getSize();
2132 }
2133
2134 const mlir::Type elementType = vecTy.getElementType();
2135 for (const mlir::Value element : getElements()) {
2136 if (element.getType() != elementType) {
2137 return emitOpError() << "operand type " << element.getType()
2138 << " doesn't match vector element type "
2139 << elementType;
2140 }
2141 }
2142
2143 return success();
2144}
2145
2146//===----------------------------------------------------------------------===//
2147// VecExtractOp
2148//===----------------------------------------------------------------------===//
2149
2150OpFoldResult cir::VecExtractOp::fold(FoldAdaptor adaptor) {
2151 const auto vectorAttr =
2152 llvm::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec());
2153 if (!vectorAttr)
2154 return {};
2155
2156 const auto indexAttr =
2157 llvm::dyn_cast_if_present<cir::IntAttr>(adaptor.getIndex());
2158 if (!indexAttr)
2159 return {};
2160
2161 const mlir::ArrayAttr elements = vectorAttr.getElts();
2162 const uint64_t index = indexAttr.getUInt();
2163 if (index >= elements.size())
2164 return {};
2165
2166 return elements[index];
2167}
2168
2169//===----------------------------------------------------------------------===//
2170// VecCmpOp
2171//===----------------------------------------------------------------------===//
2172
2173OpFoldResult cir::VecCmpOp::fold(FoldAdaptor adaptor) {
2174 auto lhsVecAttr =
2175 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getLhs());
2176 auto rhsVecAttr =
2177 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getRhs());
2178 if (!lhsVecAttr || !rhsVecAttr)
2179 return {};
2180
2181 mlir::Type inputElemTy =
2182 mlir::cast<cir::VectorType>(lhsVecAttr.getType()).getElementType();
2183 if (!isAnyIntegerOrFloatingPointType(inputElemTy))
2184 return {};
2185
2186 cir::CmpOpKind opKind = adaptor.getKind();
2187 mlir::ArrayAttr lhsVecElhs = lhsVecAttr.getElts();
2188 mlir::ArrayAttr rhsVecElhs = rhsVecAttr.getElts();
2189 uint64_t vecSize = lhsVecElhs.size();
2190
2191 SmallVector<mlir::Attribute, 16> elements(vecSize);
2192 bool isIntAttr = vecSize && mlir::isa<cir::IntAttr>(lhsVecElhs[0]);
2193 for (uint64_t i = 0; i < vecSize; i++) {
2194 mlir::Attribute lhsAttr = lhsVecElhs[i];
2195 mlir::Attribute rhsAttr = rhsVecElhs[i];
2196 int cmpResult = 0;
2197 switch (opKind) {
2198 case cir::CmpOpKind::lt: {
2199 if (isIntAttr) {
2200 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <
2201 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2202 } else {
2203 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <
2204 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2205 }
2206 break;
2207 }
2208 case cir::CmpOpKind::le: {
2209 if (isIntAttr) {
2210 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <=
2211 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2212 } else {
2213 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <=
2214 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2215 }
2216 break;
2217 }
2218 case cir::CmpOpKind::gt: {
2219 if (isIntAttr) {
2220 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >
2221 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2222 } else {
2223 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >
2224 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2225 }
2226 break;
2227 }
2228 case cir::CmpOpKind::ge: {
2229 if (isIntAttr) {
2230 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >=
2231 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2232 } else {
2233 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >=
2234 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2235 }
2236 break;
2237 }
2238 case cir::CmpOpKind::eq: {
2239 if (isIntAttr) {
2240 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() ==
2241 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2242 } else {
2243 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() ==
2244 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2245 }
2246 break;
2247 }
2248 case cir::CmpOpKind::ne: {
2249 if (isIntAttr) {
2250 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() !=
2251 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2252 } else {
2253 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() !=
2254 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2255 }
2256 break;
2257 }
2258 }
2259
2260 elements[i] = cir::IntAttr::get(getType().getElementType(), cmpResult);
2261 }
2262
2263 return cir::ConstVectorAttr::get(
2264 getType(), mlir::ArrayAttr::get(getContext(), elements));
2265}
2266
2267//===----------------------------------------------------------------------===//
2268// VecShuffleOp
2269//===----------------------------------------------------------------------===//
2270
2271OpFoldResult cir::VecShuffleOp::fold(FoldAdaptor adaptor) {
2272 auto vec1Attr =
2273 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec1());
2274 auto vec2Attr =
2275 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec2());
2276 if (!vec1Attr || !vec2Attr)
2277 return {};
2278
2279 mlir::Type vec1ElemTy =
2280 mlir::cast<cir::VectorType>(vec1Attr.getType()).getElementType();
2281
2282 mlir::ArrayAttr vec1Elts = vec1Attr.getElts();
2283 mlir::ArrayAttr vec2Elts = vec2Attr.getElts();
2284 mlir::ArrayAttr indicesElts = adaptor.getIndices();
2285
2287 elements.reserve(indicesElts.size());
2288
2289 uint64_t vec1Size = vec1Elts.size();
2290 for (const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
2291 if (idxAttr.getSInt() == -1) {
2292 elements.push_back(cir::UndefAttr::get(vec1ElemTy));
2293 continue;
2294 }
2295
2296 uint64_t idxValue = idxAttr.getUInt();
2297 elements.push_back(idxValue < vec1Size ? vec1Elts[idxValue]
2298 : vec2Elts[idxValue - vec1Size]);
2299 }
2300
2301 return cir::ConstVectorAttr::get(
2302 getType(), mlir::ArrayAttr::get(getContext(), elements));
2303}
2304
2305LogicalResult cir::VecShuffleOp::verify() {
2306 // The number of elements in the indices array must match the number of
2307 // elements in the result type.
2308 if (getIndices().size() != getResult().getType().getSize()) {
2309 return emitOpError() << ": the number of elements in " << getIndices()
2310 << " and " << getResult().getType() << " don't match";
2311 }
2312
2313 // The element types of the two input vectors and of the result type must
2314 // match.
2315 if (getVec1().getType().getElementType() !=
2316 getResult().getType().getElementType()) {
2317 return emitOpError() << ": element types of " << getVec1().getType()
2318 << " and " << getResult().getType() << " don't match";
2319 }
2320
2321 const uint64_t maxValidIndex =
2322 getVec1().getType().getSize() + getVec2().getType().getSize() - 1;
2323 if (llvm::any_of(
2324 getIndices().getAsRange<cir::IntAttr>(), [&](cir::IntAttr idxAttr) {
2325 return idxAttr.getSInt() != -1 && idxAttr.getUInt() > maxValidIndex;
2326 })) {
2327 return emitOpError() << ": index for __builtin_shufflevector must be "
2328 "less than the total number of vector elements";
2329 }
2330 return success();
2331}
2332
2333//===----------------------------------------------------------------------===//
2334// VecShuffleDynamicOp
2335//===----------------------------------------------------------------------===//
2336
2337OpFoldResult cir::VecShuffleDynamicOp::fold(FoldAdaptor adaptor) {
2338 mlir::Attribute vec = adaptor.getVec();
2339 mlir::Attribute indices = adaptor.getIndices();
2340 if (mlir::isa_and_nonnull<cir::ConstVectorAttr>(vec) &&
2341 mlir::isa_and_nonnull<cir::ConstVectorAttr>(indices)) {
2342 auto vecAttr = mlir::cast<cir::ConstVectorAttr>(vec);
2343 auto indicesAttr = mlir::cast<cir::ConstVectorAttr>(indices);
2344
2345 mlir::ArrayAttr vecElts = vecAttr.getElts();
2346 mlir::ArrayAttr indicesElts = indicesAttr.getElts();
2347
2348 const uint64_t numElements = vecElts.size();
2349
2351 elements.reserve(numElements);
2352
2353 const uint64_t maskBits = llvm::NextPowerOf2(numElements - 1) - 1;
2354 for (const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
2355 uint64_t idxValue = idxAttr.getUInt();
2356 uint64_t newIdx = idxValue & maskBits;
2357 elements.push_back(vecElts[newIdx]);
2358 }
2359
2360 return cir::ConstVectorAttr::get(
2361 getType(), mlir::ArrayAttr::get(getContext(), elements));
2362 }
2363
2364 return {};
2365}
2366
2367LogicalResult cir::VecShuffleDynamicOp::verify() {
2368 // The number of elements in the two input vectors must match.
2369 if (getVec().getType().getSize() !=
2370 mlir::cast<cir::VectorType>(getIndices().getType()).getSize()) {
2371 return emitOpError() << ": the number of elements in " << getVec().getType()
2372 << " and " << getIndices().getType() << " don't match";
2373 }
2374 return success();
2375}
2376
2377//===----------------------------------------------------------------------===//
2378// VecTernaryOp
2379//===----------------------------------------------------------------------===//
2380
2381LogicalResult cir::VecTernaryOp::verify() {
2382 // Verify that the condition operand has the same number of elements as the
2383 // other operands. (The automatic verification already checked that all
2384 // operands are vector types and that the second and third operands are the
2385 // same type.)
2386 if (getCond().getType().getSize() != getLhs().getType().getSize()) {
2387 return emitOpError() << ": the number of elements in "
2388 << getCond().getType() << " and " << getLhs().getType()
2389 << " don't match";
2390 }
2391 return success();
2392}
2393
2394OpFoldResult cir::VecTernaryOp::fold(FoldAdaptor adaptor) {
2395 mlir::Attribute cond = adaptor.getCond();
2396 mlir::Attribute lhs = adaptor.getLhs();
2397 mlir::Attribute rhs = adaptor.getRhs();
2398
2399 if (!mlir::isa_and_nonnull<cir::ConstVectorAttr>(cond) ||
2400 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(lhs) ||
2401 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(rhs))
2402 return {};
2403 auto condVec = mlir::cast<cir::ConstVectorAttr>(cond);
2404 auto lhsVec = mlir::cast<cir::ConstVectorAttr>(lhs);
2405 auto rhsVec = mlir::cast<cir::ConstVectorAttr>(rhs);
2406
2407 mlir::ArrayAttr condElts = condVec.getElts();
2408
2410 elements.reserve(condElts.size());
2411
2412 for (const auto &[idx, condAttr] :
2413 llvm::enumerate(condElts.getAsRange<cir::IntAttr>())) {
2414 if (condAttr.getSInt()) {
2415 elements.push_back(lhsVec.getElts()[idx]);
2416 } else {
2417 elements.push_back(rhsVec.getElts()[idx]);
2418 }
2419 }
2420
2421 cir::VectorType vecTy = getLhs().getType();
2422 return cir::ConstVectorAttr::get(
2423 vecTy, mlir::ArrayAttr::get(getContext(), elements));
2424}
2425
2426//===----------------------------------------------------------------------===//
2427// ComplexCreateOp
2428//===----------------------------------------------------------------------===//
2429
2430LogicalResult cir::ComplexCreateOp::verify() {
2431 if (getType().getElementType() != getReal().getType()) {
2432 emitOpError()
2433 << "operand type of cir.complex.create does not match its result type";
2434 return failure();
2435 }
2436
2437 return success();
2438}
2439
2440OpFoldResult cir::ComplexCreateOp::fold(FoldAdaptor adaptor) {
2441 mlir::Attribute real = adaptor.getReal();
2442 mlir::Attribute imag = adaptor.getImag();
2443 if (!real || !imag)
2444 return {};
2445
2446 // When both of real and imag are constants, we can fold the operation into an
2447 // `#cir.const_complex` operation.
2448 auto realAttr = mlir::cast<mlir::TypedAttr>(real);
2449 auto imagAttr = mlir::cast<mlir::TypedAttr>(imag);
2450 return cir::ConstComplexAttr::get(realAttr, imagAttr);
2451}
2452
2453//===----------------------------------------------------------------------===//
2454// ComplexRealOp
2455//===----------------------------------------------------------------------===//
2456
2457LogicalResult cir::ComplexRealOp::verify() {
2458 mlir::Type operandTy = getOperand().getType();
2459 if (auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
2460 operandTy = complexOperandTy.getElementType();
2461
2462 if (getType() != operandTy) {
2463 emitOpError() << ": result type does not match operand type";
2464 return failure();
2465 }
2466
2467 return success();
2468}
2469
2470OpFoldResult cir::ComplexRealOp::fold(FoldAdaptor adaptor) {
2471 if (!mlir::isa<cir::ComplexType>(getOperand().getType()))
2472 return nullptr;
2473
2474 if (auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
2475 return complexCreateOp.getOperand(0);
2476
2477 auto complex =
2478 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
2479 return complex ? complex.getReal() : nullptr;
2480}
2481
2482//===----------------------------------------------------------------------===//
2483// ComplexImagOp
2484//===----------------------------------------------------------------------===//
2485
2486LogicalResult cir::ComplexImagOp::verify() {
2487 mlir::Type operandTy = getOperand().getType();
2488 if (auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
2489 operandTy = complexOperandTy.getElementType();
2490
2491 if (getType() != operandTy) {
2492 emitOpError() << ": result type does not match operand type";
2493 return failure();
2494 }
2495
2496 return success();
2497}
2498
2499OpFoldResult cir::ComplexImagOp::fold(FoldAdaptor adaptor) {
2500 if (!mlir::isa<cir::ComplexType>(getOperand().getType()))
2501 return nullptr;
2502
2503 if (auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
2504 return complexCreateOp.getOperand(1);
2505
2506 auto complex =
2507 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
2508 return complex ? complex.getImag() : nullptr;
2509}
2510
2511//===----------------------------------------------------------------------===//
2512// ComplexRealPtrOp
2513//===----------------------------------------------------------------------===//
2514
2515LogicalResult cir::ComplexRealPtrOp::verify() {
2516 mlir::Type resultPointeeTy = getType().getPointee();
2517 cir::PointerType operandPtrTy = getOperand().getType();
2518 auto operandPointeeTy =
2519 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
2520
2521 if (resultPointeeTy != operandPointeeTy.getElementType()) {
2522 return emitOpError() << ": result type does not match operand type";
2523 }
2524
2525 return success();
2526}
2527
2528//===----------------------------------------------------------------------===//
2529// ComplexImagPtrOp
2530//===----------------------------------------------------------------------===//
2531
2532LogicalResult cir::ComplexImagPtrOp::verify() {
2533 mlir::Type resultPointeeTy = getType().getPointee();
2534 cir::PointerType operandPtrTy = getOperand().getType();
2535 auto operandPointeeTy =
2536 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
2537
2538 if (resultPointeeTy != operandPointeeTy.getElementType()) {
2539 return emitOpError()
2540 << "cir.complex.imag_ptr result type does not match operand type";
2541 }
2542 return success();
2543}
2544
2545//===----------------------------------------------------------------------===//
2546// Bit manipulation operations
2547//===----------------------------------------------------------------------===//
2548
2549static OpFoldResult
2550foldUnaryBitOp(mlir::Attribute inputAttr,
2551 llvm::function_ref<llvm::APInt(const llvm::APInt &)> func,
2552 bool poisonZero = false) {
2553 if (mlir::isa_and_present<cir::PoisonAttr>(inputAttr)) {
2554 // Propagate poison value
2555 return inputAttr;
2556 }
2557
2558 auto input = mlir::dyn_cast_if_present<IntAttr>(inputAttr);
2559 if (!input)
2560 return nullptr;
2561
2562 llvm::APInt inputValue = input.getValue();
2563 if (poisonZero && inputValue.isZero())
2564 return cir::PoisonAttr::get(input.getType());
2565
2566 llvm::APInt resultValue = func(inputValue);
2567 return IntAttr::get(input.getType(), resultValue);
2568}
2569
2570OpFoldResult BitClrsbOp::fold(FoldAdaptor adaptor) {
2571 return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
2572 unsigned resultValue =
2573 inputValue.getBitWidth() - inputValue.getSignificantBits();
2574 return llvm::APInt(inputValue.getBitWidth(), resultValue);
2575 });
2576}
2577
2578OpFoldResult BitClzOp::fold(FoldAdaptor adaptor) {
2579 return foldUnaryBitOp(
2580 adaptor.getInput(),
2581 [](const llvm::APInt &inputValue) {
2582 unsigned resultValue = inputValue.countLeadingZeros();
2583 return llvm::APInt(inputValue.getBitWidth(), resultValue);
2584 },
2585 getPoisonZero());
2586}
2587
2588OpFoldResult BitCtzOp::fold(FoldAdaptor adaptor) {
2589 return foldUnaryBitOp(
2590 adaptor.getInput(),
2591 [](const llvm::APInt &inputValue) {
2592 return llvm::APInt(inputValue.getBitWidth(),
2593 inputValue.countTrailingZeros());
2594 },
2595 getPoisonZero());
2596}
2597
2598OpFoldResult BitFfsOp::fold(FoldAdaptor adaptor) {
2599 return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
2600 unsigned trailingZeros = inputValue.countTrailingZeros();
2601 unsigned result =
2602 trailingZeros == inputValue.getBitWidth() ? 0 : trailingZeros + 1;
2603 return llvm::APInt(inputValue.getBitWidth(), result);
2604 });
2605}
2606
2607OpFoldResult BitParityOp::fold(FoldAdaptor adaptor) {
2608 return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
2609 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount() % 2);
2610 });
2611}
2612
2613OpFoldResult BitPopcountOp::fold(FoldAdaptor adaptor) {
2614 return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
2615 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount());
2616 });
2617}
2618
2619OpFoldResult BitReverseOp::fold(FoldAdaptor adaptor) {
2620 return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
2621 return inputValue.reverseBits();
2622 });
2623}
2624
2625OpFoldResult ByteSwapOp::fold(FoldAdaptor adaptor) {
2626 return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
2627 return inputValue.byteSwap();
2628 });
2629}
2630
2631OpFoldResult RotateOp::fold(FoldAdaptor adaptor) {
2632 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()) ||
2633 mlir::isa_and_present<cir::PoisonAttr>(adaptor.getAmount())) {
2634 // Propagate poison values
2635 return cir::PoisonAttr::get(getType());
2636 }
2637
2638 auto input = mlir::dyn_cast_if_present<IntAttr>(adaptor.getInput());
2639 auto amount = mlir::dyn_cast_if_present<IntAttr>(adaptor.getAmount());
2640 if (!input && !amount)
2641 return nullptr;
2642
2643 // We could fold cir.rotate even if one of its two operands is not a constant:
2644 // - `cir.rotate left/right %0, 0` could be folded into just %0 even if %0
2645 // is not a constant.
2646 // - `cir.rotate left/right 0/0b111...111, %0` could be folded into 0 or
2647 // 0b111...111 even if %0 is not a constant.
2648
2649 llvm::APInt inputValue;
2650 if (input) {
2651 inputValue = input.getValue();
2652 if (inputValue.isZero() || inputValue.isAllOnes()) {
2653 // An input value of all 0s or all 1s will not change after rotation
2654 return input;
2655 }
2656 }
2657
2658 uint64_t amountValue;
2659 if (amount) {
2660 amountValue = amount.getValue().urem(getInput().getType().getWidth());
2661 if (amountValue == 0) {
2662 // A shift amount of 0 will not change the input value
2663 return getInput();
2664 }
2665 }
2666
2667 if (!input || !amount)
2668 return nullptr;
2669
2670 assert(inputValue.getBitWidth() == getInput().getType().getWidth() &&
2671 "input value must have the same bit width as the input type");
2672
2673 llvm::APInt resultValue;
2674 if (isRotateLeft())
2675 resultValue = inputValue.rotl(amountValue);
2676 else
2677 resultValue = inputValue.rotr(amountValue);
2678
2679 return IntAttr::get(input.getContext(), input.getType(), resultValue);
2680}
2681
2682//===----------------------------------------------------------------------===//
2683// InlineAsmOp
2684//===----------------------------------------------------------------------===//
2685
2686void cir::InlineAsmOp::print(OpAsmPrinter &p) {
2687 p << '(' << getAsmFlavor() << ", ";
2688 p.increaseIndent();
2689 p.printNewline();
2690
2691 llvm::SmallVector<std::string, 3> names{"out", "in", "in_out"};
2692 auto *nameIt = names.begin();
2693 auto *attrIt = getOperandAttrs().begin();
2694
2695 for (mlir::OperandRange ops : getAsmOperands()) {
2696 p << *nameIt << " = ";
2697
2698 p << '[';
2699 llvm::interleaveComma(llvm::make_range(ops.begin(), ops.end()), p,
2700 [&](Value value) {
2701 p.printOperand(value);
2702 p << " : " << value.getType();
2703 if (*attrIt)
2704 p << " (maybe_memory)";
2705 attrIt++;
2706 });
2707 p << "],";
2708 p.printNewline();
2709 ++nameIt;
2710 }
2711
2712 p << "{";
2713 p.printString(getAsmString());
2714 p << " ";
2715 p.printString(getConstraints());
2716 p << "}";
2717 p.decreaseIndent();
2718 p << ')';
2719 if (getSideEffects())
2720 p << " side_effects";
2721
2722 std::array elidedAttrs{
2723 llvm::StringRef("asm_flavor"), llvm::StringRef("asm_string"),
2724 llvm::StringRef("constraints"), llvm::StringRef("operand_attrs"),
2725 llvm::StringRef("operands_segments"), llvm::StringRef("side_effects")};
2726 p.printOptionalAttrDict(getOperation()->getAttrs(), elidedAttrs);
2727
2728 if (auto v = getRes())
2729 p << " -> " << v.getType();
2730}
2731
2732void cir::InlineAsmOp::build(OpBuilder &odsBuilder, OperationState &odsState,
2733 ArrayRef<ValueRange> asmOperands,
2734 StringRef asmString, StringRef constraints,
2735 bool sideEffects, cir::AsmFlavor asmFlavor,
2736 ArrayRef<Attribute> operandAttrs) {
2737 // Set up the operands_segments for VariadicOfVariadic
2738 SmallVector<int32_t> segments;
2739 for (auto operandRange : asmOperands) {
2740 segments.push_back(operandRange.size());
2741 odsState.addOperands(operandRange);
2742 }
2743
2744 odsState.addAttribute(
2745 "operands_segments",
2746 DenseI32ArrayAttr::get(odsBuilder.getContext(), segments));
2747 odsState.addAttribute("asm_string", odsBuilder.getStringAttr(asmString));
2748 odsState.addAttribute("constraints", odsBuilder.getStringAttr(constraints));
2749 odsState.addAttribute("asm_flavor",
2750 AsmFlavorAttr::get(odsBuilder.getContext(), asmFlavor));
2751
2752 if (sideEffects)
2753 odsState.addAttribute("side_effects", odsBuilder.getUnitAttr());
2754
2755 odsState.addAttribute("operand_attrs", odsBuilder.getArrayAttr(operandAttrs));
2756}
2757
2758ParseResult cir::InlineAsmOp::parse(OpAsmParser &parser,
2759 OperationState &result) {
2761 llvm::SmallVector<int32_t> operandsGroupSizes;
2762 std::string asmString, constraints;
2763 Type resType;
2764 MLIRContext *ctxt = parser.getBuilder().getContext();
2765
2766 auto error = [&](const Twine &msg) -> LogicalResult {
2767 return parser.emitError(parser.getCurrentLocation(), msg);
2768 };
2769
2770 auto expected = [&](const std::string &c) {
2771 return error("expected '" + c + "'");
2772 };
2773
2774 if (parser.parseLParen().failed())
2775 return expected("(");
2776
2777 auto flavor = FieldParser<AsmFlavor, AsmFlavor>::parse(parser);
2778 if (failed(flavor))
2779 return error("Unknown AsmFlavor");
2780
2781 if (parser.parseComma().failed())
2782 return expected(",");
2783
2784 auto parseValue = [&](Value &v) {
2785 OpAsmParser::UnresolvedOperand op;
2786
2787 if (parser.parseOperand(op) || parser.parseColon())
2788 return error("can't parse operand");
2789
2790 Type typ;
2791 if (parser.parseType(typ).failed())
2792 return error("can't parse operand type");
2794 if (parser.resolveOperand(op, typ, tmp))
2795 return error("can't resolve operand");
2796 v = tmp[0];
2797 return mlir::success();
2798 };
2799
2800 auto parseOperands = [&](llvm::StringRef name) {
2801 if (parser.parseKeyword(name).failed())
2802 return error("expected " + name + " operands here");
2803 if (parser.parseEqual().failed())
2804 return expected("=");
2805 if (parser.parseLSquare().failed())
2806 return expected("[");
2807
2808 int size = 0;
2809 if (parser.parseOptionalRSquare().succeeded()) {
2810 operandsGroupSizes.push_back(size);
2811 if (parser.parseComma())
2812 return expected(",");
2813 return mlir::success();
2814 }
2815
2816 auto parseOperand = [&]() {
2817 Value val;
2818 if (parseValue(val).succeeded()) {
2819 result.operands.push_back(val);
2820 size++;
2821
2822 if (parser.parseOptionalLParen().failed()) {
2823 operandAttrs.push_back(mlir::Attribute());
2824 return mlir::success();
2825 }
2826
2827 if (parser.parseKeyword("maybe_memory").succeeded()) {
2828 operandAttrs.push_back(mlir::UnitAttr::get(ctxt));
2829 if (parser.parseRParen())
2830 return expected(")");
2831 return mlir::success();
2832 } else {
2833 return expected("maybe_memory");
2834 }
2835 }
2836 return mlir::failure();
2837 };
2838
2839 if (parser.parseCommaSeparatedList(parseOperand).failed())
2840 return mlir::failure();
2841
2842 if (parser.parseRSquare().failed() || parser.parseComma().failed())
2843 return expected("]");
2844 operandsGroupSizes.push_back(size);
2845 return mlir::success();
2846 };
2847
2848 if (parseOperands("out").failed() || parseOperands("in").failed() ||
2849 parseOperands("in_out").failed())
2850 return error("failed to parse operands");
2851
2852 if (parser.parseLBrace())
2853 return expected("{");
2854 if (parser.parseString(&asmString))
2855 return error("asm string parsing failed");
2856 if (parser.parseString(&constraints))
2857 return error("constraints string parsing failed");
2858 if (parser.parseRBrace())
2859 return expected("}");
2860 if (parser.parseRParen())
2861 return expected(")");
2862
2863 if (parser.parseOptionalKeyword("side_effects").succeeded())
2864 result.attributes.set("side_effects", UnitAttr::get(ctxt));
2865
2866 if (parser.parseOptionalArrow().succeeded() &&
2867 parser.parseType(resType).failed())
2868 return mlir::failure();
2869
2870 if (parser.parseOptionalAttrDict(result.attributes).failed())
2871 return mlir::failure();
2872
2873 result.attributes.set("asm_flavor", AsmFlavorAttr::get(ctxt, *flavor));
2874 result.attributes.set("asm_string", StringAttr::get(ctxt, asmString));
2875 result.attributes.set("constraints", StringAttr::get(ctxt, constraints));
2876 result.attributes.set("operand_attrs", ArrayAttr::get(ctxt, operandAttrs));
2877 result.getOrAddProperties<InlineAsmOp::Properties>().operands_segments =
2878 parser.getBuilder().getDenseI32ArrayAttr(operandsGroupSizes);
2879 if (resType)
2880 result.addTypes(TypeRange{resType});
2881
2882 return mlir::success();
2883}
2884
2885//===----------------------------------------------------------------------===//
2886// ThrowOp
2887//===----------------------------------------------------------------------===//
2888
2889mlir::LogicalResult cir::ThrowOp::verify() {
2890 // For the no-rethrow version, it must have at least the exception pointer.
2891 if (rethrows())
2892 return success();
2893
2894 if (getNumOperands() != 0) {
2895 if (getTypeInfo())
2896 return success();
2897 return emitOpError() << "'type_info' symbol attribute missing";
2898 }
2899
2900 return failure();
2901}
2902
2903//===----------------------------------------------------------------------===//
2904// TypeInfoAttr
2905//===----------------------------------------------------------------------===//
2906
2907LogicalResult cir::TypeInfoAttr::verify(
2908 ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError,
2909 ::mlir::Type type, ::mlir::ArrayAttr typeInfoData) {
2910
2911 if (cir::ConstRecordAttr::verify(emitError, type, typeInfoData).failed())
2912 return failure();
2913
2914 return success();
2915}
2916
2917//===----------------------------------------------------------------------===//
2918// TableGen'd op method definitions
2919//===----------------------------------------------------------------------===//
2920
2921#define GET_OP_CLASSES
2922#include "clang/CIR/Dialect/IR/CIROps.cpp.inc"
static const MemRegion * getRegion(const CallEvent &Call, const MutexDescriptor &Descriptor, bool IsLock)
static mlir::LogicalResult checkReturnAndFunction(cir::ReturnOp op, cir::FuncOp function)
static bool isBoolNot(cir::UnaryOp op)
static bool isIntOrBoolCast(cir::CastOp op)
static void printConstant(OpAsmPrinter &p, Attribute value)
static mlir::ParseResult parseOmittedTerminatorRegion(mlir::OpAsmParser &parser, mlir::Region &region)
void printVisibilityAttr(OpAsmPrinter &printer, cir::VisibilityAttr &visibility)
static ParseResult parseSwitchFlatOpCases(OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues, SmallVectorImpl< Block * > &caseDestinations, SmallVectorImpl< llvm::SmallVector< OpAsmParser::UnresolvedOperand > > &caseOperands, SmallVectorImpl< llvm::SmallVector< Type > > &caseOperandTypes)
<cases> ::= [ (case (, case )* )?
static LogicalResult verifyCallCommInSymbolUses(mlir::Operation *op, SymbolTableCollection &symbolTable)
static LogicalResult ensureRegionTerm(OpAsmParser &parser, Region &region, SMLoc errLoc)
static ParseResult parseGlobalOpTypeAndInitialValue(OpAsmParser &parser, TypeAttr &typeAttr, Attribute &initialValueAttr, mlir::Region &ctorRegion, mlir::Region &dtorRegion)
static OpFoldResult foldUnaryBitOp(mlir::Attribute inputAttr, llvm::function_ref< llvm::APInt(const llvm::APInt &)> func, bool poisonZero=false)
static llvm::StringRef getLinkageAttrNameString()
Returns the name used for the linkage attribute.
static RetTy parseOptionalCIRKeyword(AsmParser &parser, EnumTy defaultValue)
Parse an enum from the keyword, or default to the provided default value.
static void printSwitchFlatOpCases(OpAsmPrinter &p, cir::SwitchFlatOp op, Type flagType, mlir::ArrayAttr caseValues, SuccessorRange caseDestinations, OperandRangeRange caseOperands, const TypeRangeRange &caseOperandTypes)
static void printSwitchOp(OpAsmPrinter &p, cir::SwitchOp op, mlir::Region &bodyRegion, mlir::Value condition, mlir::Type condType)
static void printGlobalOpTypeAndInitialValue(OpAsmPrinter &p, cir::GlobalOp op, TypeAttr type, Attribute initAttr, mlir::Region &ctorRegion, mlir::Region &dtorRegion)
static ParseResult parseCIRKeyword(AsmParser &parser, RetTy &result)
Parse an enum from the keyword, return failure if the keyword is not found.
static Value tryFoldCastChain(cir::CastOp op)
void parseVisibilityAttr(OpAsmParser &parser, cir::VisibilityAttr &visibility)
static bool omitRegionTerm(mlir::Region &r)
static void printOmittedTerminatorRegion(mlir::OpAsmPrinter &printer, cir::ScopeOp &op, mlir::Region &region)
static ParseResult parseConstantValue(OpAsmParser &parser, mlir::Attribute &valueAttr)
static void printCallCommon(mlir::Operation *op, mlir::FlatSymbolRefAttr calleeSym, mlir::Value indirectCallee, mlir::OpAsmPrinter &printer, bool isNothrow, cir::SideEffect sideEffect)
static LogicalResult checkConstantTypes(mlir::Operation *op, mlir::Type opType, mlir::Attribute attrType)
static ParseResult parseSwitchOp(OpAsmParser &parser, mlir::Region &regions, mlir::OpAsmParser::UnresolvedOperand &cond, mlir::Type &condType)
static mlir::ParseResult parseCallCommon(mlir::OpAsmParser &parser, mlir::OperationState &result)
#define REGISTER_ENUM_TYPE(Ty)
static int parseOptionalKeywordAlternative(AsmParser &parser, ArrayRef< llvm::StringRef > keywords)
llvm::function_ref< void(mlir::OpBuilder &, mlir::Location)> BuilderCallbackRef
Definition CIRDialect.h:37
llvm::function_ref< void( mlir::OpBuilder &, mlir::Location, mlir::OperationState &)> BuilderOpStateCallbackRef
Definition CIRDialect.h:39
static std::optional< NonLoc > getIndex(ProgramStateRef State, const ElementRegion *ER, CharKind CK)
static Decl::Kind getKind(const Decl *D)
TokenType getType() const
Returns the token's type, e.g.
__device__ __2f16 float c
void buildTerminatedBody(mlir::OpBuilder &builder, mlir::Location loc)
const AstTypeMatcher< RecordType > recordType
StringRef getName(const HeaderType T)
Definition HeaderFile.h:38
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
static bool addressSpace()
static bool opGlobalThreadLocal()
static bool opCallCallConv()
static bool opScopeCleanupRegion()
static bool supportIFuncAttr()