13#include "mlir/Dialect/OpenACC/OpenACCOpsDialect.h.inc"
14#include "mlir/Dialect/OpenMP/OpenMPOpsDialect.h.inc"
15#include "mlir/IR/PatternMatch.h"
16#include "mlir/Interfaces/DataLayoutInterfaces.h"
17#include "mlir/Pass/Pass.h"
18#include "mlir/Transforms/DialectConversion.h"
28#include "llvm/ADT/TypeSwitch.h"
34#define GEN_PASS_DEF_CXXABILOWERING
35#include "clang/CIR/Dialect/Passes.h.inc"
42bool isCXXABIAttributeLegal(
const mlir::TypeConverter &tc,
43 mlir::Attribute
attr) {
50 if (isa<mlir::acc::OpenACCDialect, mlir::omp::OpenMPDialect>(
56 if (
isa<mlir::DenseArrayAttr, mlir::FloatAttr, mlir::UnitAttr,
57 mlir::StringAttr, mlir::IntegerAttr, mlir::SymbolRefAttr,
58 cir::AnnotationAttr>(
attr))
64#include
"clang/CIR/Dialect/IR/CIRLowering.inc"
71 if (isa<mlir::DistinctAttr>(
attr))
75 if (isa<cir::DataMemberAttr, cir::DataMemberOffsetAttr, cir::MethodAttr>(
79 return llvm::TypeSwitch<mlir::Attribute, bool>(
attr)
82 [&tc](cir::ZeroAttr za) {
return tc.isLegal(za.getType()); })
83 .Case<cir::PoisonAttr>(
84 [&tc](cir::PoisonAttr pa) {
return tc.isLegal(pa.getType()); })
85 .Case<cir::UndefAttr>(
86 [&tc](cir::UndefAttr uda) {
return tc.isLegal(uda.getType()); })
87 .Case<mlir::TypeAttr>(
88 [&tc](mlir::TypeAttr ta) {
return tc.isLegal(ta.getValue()); })
89 .Case<cir::ConstPtrAttr>(
90 [&tc](cir::ConstPtrAttr cpa) {
return tc.isLegal(cpa.getType()); })
91 .Case<cir::CXXCtorAttr>(
92 [&tc](cir::CXXCtorAttr ca) {
return tc.isLegal(ca.getType()); })
93 .Case<cir::CXXDtorAttr>(
94 [&tc](cir::CXXDtorAttr da) {
return tc.isLegal(da.getType()); })
95 .Case<cir::CXXAssignAttr>(
96 [&tc](cir::CXXAssignAttr aa) {
return tc.isLegal(aa.getType()); })
100 .Case<mlir::ArrayAttr>([&tc](mlir::ArrayAttr array) {
101 return llvm::all_of(array.getValue(), [&tc](mlir::Attribute
attr) {
102 return isCXXABIAttributeLegal(tc, attr);
105 .Case<mlir::DictionaryAttr>([&tc](mlir::DictionaryAttr dict) {
106 return llvm::all_of(dict.getValue(), [&tc](mlir::NamedAttribute na) {
107 return isCXXABIAttributeLegal(tc, na.getValue());
111 .Case<cir::ConstArrayAttr>([&tc](cir::ConstArrayAttr array) {
112 return tc.isLegal(array.getType()) &&
113 isCXXABIAttributeLegal(tc, array.getElts());
115 .Case<cir::GlobalViewAttr>([&tc](cir::GlobalViewAttr gva) {
116 return tc.isLegal(gva.getType()) &&
117 isCXXABIAttributeLegal(tc, gva.getIndices());
119 .Case<cir::GlobalOffsetAttr>([&tc](cir::GlobalOffsetAttr goa) {
120 return tc.isLegal(goa.getType());
122 .Case<cir::VTableAttr>([&tc](cir::VTableAttr vta) {
123 return tc.isLegal(vta.getType()) &&
124 isCXXABIAttributeLegal(tc, vta.getData());
126 .Case<cir::TypeInfoAttr>([&tc](cir::TypeInfoAttr tia) {
127 return tc.isLegal(tia.getType()) &&
128 isCXXABIAttributeLegal(tc, tia.getData());
130 .Case<cir::DynamicCastInfoAttr>([&tc](cir::DynamicCastInfoAttr dcia) {
131 return isCXXABIAttributeLegal(tc, dcia.getSrcRtti()) &&
132 isCXXABIAttributeLegal(tc, dcia.getDestRtti()) &&
133 isCXXABIAttributeLegal(tc, dcia.getRuntimeFunc()) &&
134 isCXXABIAttributeLegal(tc, dcia.getBadCastFunc());
136 .Case<cir::ConstRecordAttr>([&tc](cir::ConstRecordAttr cra) {
137 return tc.isLegal(cra.getType()) &&
138 isCXXABIAttributeLegal(tc, cra.getMembers());
149mlir::Attribute rewriteAttribute(
const mlir::TypeConverter &tc,
150 mlir::MLIRContext *ctx, mlir::Attribute attr) {
153 if (isCXXABIAttributeLegal(tc, attr))
161 return llvm::TypeSwitch<mlir::Attribute, mlir::Attribute>(attr)
163 .Case<cir::ZeroAttr>([&tc](cir::ZeroAttr za) {
164 return cir::ZeroAttr::get(tc.convertType(za.getType()));
166 .Case<cir::PoisonAttr>([&tc](cir::PoisonAttr pa) {
167 return cir::PoisonAttr::get(tc.convertType(pa.getType()));
169 .Case<cir::UndefAttr>([&tc](cir::UndefAttr uda) {
170 return cir::UndefAttr::get(tc.convertType(uda.getType()));
172 .Case<mlir::TypeAttr>([&tc](mlir::TypeAttr ta) {
173 return mlir::TypeAttr::get(tc.convertType(ta.getValue()));
175 .Case<cir::ConstPtrAttr>([&tc](cir::ConstPtrAttr cpa) {
176 return cir::ConstPtrAttr::get(tc.convertType(cpa.getType()),
179 .Case<cir::CXXCtorAttr>([&tc](cir::CXXCtorAttr ca) {
180 return cir::CXXCtorAttr::get(tc.convertType(ca.getType()),
181 ca.getCtorKind(), ca.getIsTrivial());
183 .Case<cir::CXXDtorAttr>([&tc](cir::CXXDtorAttr da) {
184 return cir::CXXDtorAttr::get(tc.convertType(da.getType()),
187 .Case<cir::CXXAssignAttr>([&tc](cir::CXXAssignAttr aa) {
188 return cir::CXXAssignAttr::get(tc.convertType(aa.getType()),
189 aa.getAssignKind(), aa.getIsTrivial());
193 .Case<mlir::ArrayAttr>([&tc, ctx](mlir::ArrayAttr array) {
195 for (mlir::Attribute a : array.getValue())
196 elts.push_back(rewriteAttribute(tc, ctx, a));
197 return mlir::ArrayAttr::get(ctx, elts);
199 .Case<mlir::DictionaryAttr>([&tc, ctx](mlir::DictionaryAttr dict) {
201 for (mlir::NamedAttribute na : dict.getValue())
202 elts.emplace_back(na.getName(),
203 rewriteAttribute(tc, ctx, na.getValue()));
205 return mlir::DictionaryAttr::get(ctx, elts);
208 .Case<cir::ConstArrayAttr>([&tc, ctx](cir::ConstArrayAttr array) {
209 return cir::ConstArrayAttr::get(
210 ctx, tc.convertType(array.getType()),
211 rewriteAttribute(tc, ctx, array.getElts()),
212 array.getTrailingZerosNum());
214 .Case<cir::GlobalViewAttr>([&tc, ctx](cir::GlobalViewAttr gva) {
215 return cir::GlobalViewAttr::get(
216 tc.convertType(gva.getType()), gva.getSymbol(),
217 mlir::cast<mlir::ArrayAttr>(
218 rewriteAttribute(tc, ctx, gva.getIndices())),
219 gva.getAddressPoint());
221 .Case<cir::GlobalOffsetAttr>([&tc](cir::GlobalOffsetAttr goa) {
222 return cir::GlobalOffsetAttr::get(tc.convertType(goa.getType()),
223 goa.getSymbol(), goa.getOffset());
225 .Case<cir::VTableAttr>([&tc, ctx](cir::VTableAttr vta) {
226 return cir::VTableAttr::get(
227 tc.convertType(vta.getType()),
228 mlir::cast<mlir::ArrayAttr>(
229 rewriteAttribute(tc, ctx, vta.getData())));
231 .Case<cir::TypeInfoAttr>([&tc, ctx](cir::TypeInfoAttr tia) {
232 return cir::TypeInfoAttr::get(
233 tc.convertType(tia.getType()),
234 mlir::cast<mlir::ArrayAttr>(
235 rewriteAttribute(tc, ctx, tia.getData())));
237 .Case<cir::DynamicCastInfoAttr>([&tc,
238 ctx](cir::DynamicCastInfoAttr dcia) {
239 return cir::DynamicCastInfoAttr::get(
240 mlir::cast<cir::GlobalViewAttr>(
241 rewriteAttribute(tc, ctx, dcia.getSrcRtti())),
242 mlir::cast<cir::GlobalViewAttr>(
243 rewriteAttribute(tc, ctx, dcia.getDestRtti())),
244 dcia.getRuntimeFunc(), dcia.getBadCastFunc(), dcia.getOffsetHint());
246 .Case<cir::ConstRecordAttr>([&tc, ctx](cir::ConstRecordAttr cra) {
247 return cir::ConstRecordAttr::get(
248 ctx, tc.convertType(cra.getType()),
249 mlir::cast<mlir::ArrayAttr>(
250 rewriteAttribute(tc, ctx, cra.getMembers())));
252 .DefaultUnreachable(
"unrewritten illegal attribute kind");
255bool areCXXABIInherentAttrsLegal(mlir::Operation *op,
256 const mlir::TypeConverter &typeConverter) {
258 op->getName().walkInherentAttrs(
259 op, [&](llvm::StringRef, mlir::Attribute &attr) {
260 legal &= isCXXABIAttributeLegal(typeConverter, attr);
265#define GET_ABI_LOWERING_PATTERNS
266#include "clang/CIR/Dialect/IR/CIRLowering.inc"
267#undef GET_ABI_LOWERING_PATTERNS
269struct CXXABILoweringPass
270 :
public impl::CXXABILoweringBase<CXXABILoweringPass> {
271 CXXABILoweringPass() =
default;
272 void runOnOperation()
override;
280class CIRGenericCXXABILoweringPattern :
public mlir::ConversionPattern {
282 CIRGenericCXXABILoweringPattern(mlir::MLIRContext *context,
283 const mlir::TypeConverter &typeConverter)
284 : mlir::ConversionPattern(typeConverter, MatchAnyOpTypeTag(),
288 matchAndRewrite(mlir::Operation *op, llvm::ArrayRef<mlir::Value> operands,
289 mlir::ConversionPatternRewriter &rewriter)
const override {
291 if (llvm::isa<cir::AllocaOp, cir::BaseDataMemberOp, cir::BaseMethodOp,
292 cir::CastOp, cir::CmpOp, cir::ConstantOp, cir::DeleteArrayOp,
293 cir::DerivedDataMemberOp, cir::DerivedMethodOp, cir::FuncOp,
294 cir::GetMethodOp, cir::GetRuntimeMemberOp, cir::GlobalOp>(op))
295 return mlir::failure();
297 const mlir::TypeConverter *typeConverter = getTypeConverter();
298 assert(typeConverter &&
299 "CIRGenericCXXABILoweringPattern requires a type converter");
300 bool operandsAndResultsLegal = typeConverter->isLegal(op);
302 std::all_of(op->getRegions().begin(), op->getRegions().end(),
303 [typeConverter](mlir::Region ®ion) {
304 return typeConverter->isLegal(®ion);
306 bool attrsLegal = areCXXABIInherentAttrsLegal(op, *typeConverter);
308 if (operandsAndResultsLegal && regionsLegal && attrsLegal) {
311 return mlir::failure();
314 mlir::OperationState loweredOpState(op->getLoc(), op->getName());
315 loweredOpState.addOperands(operands);
316 loweredOpState.addSuccessors(op->getSuccessors());
319 loweredOpState.propertiesAttr = op->getPropertiesAsAttribute();
320 loweredOpState.addAttributes(op->getDiscardableAttrDictionary().getValue());
323 llvm::SmallVector<mlir::Type> loweredResultTypes;
324 loweredResultTypes.reserve(op->getNumResults());
325 for (mlir::Type result : op->getResultTypes())
326 loweredResultTypes.push_back(typeConverter->convertType(result));
327 loweredOpState.addTypes(loweredResultTypes);
330 for (mlir::Region ®ion : op->getRegions()) {
332 rewriter.convertRegionTypes(®ion, *getTypeConverter())))
333 return mlir::failure();
335 for (mlir::Region ®ion : op->getRegions()) {
336 mlir::Region *loweredRegion = loweredOpState.addRegion();
337 rewriter.inlineRegionBefore(region, *loweredRegion, loweredRegion->end());
341 mlir::Operation *loweredOp = rewriter.create(loweredOpState);
342 loweredOp->getName().walkInherentAttrs(
343 loweredOp, [&](llvm::StringRef, mlir::Attribute &attr) {
344 attr = rewriteAttribute(*typeConverter, op->getContext(), attr);
347 rewriter.replaceOp(op, loweredOp);
348 return mlir::success();
354mlir::LogicalResult CIRAllocaOpABILowering::matchAndRewrite(
355 cir::AllocaOp op, OpAdaptor adaptor,
356 mlir::ConversionPatternRewriter &rewriter)
const {
357 mlir::Type allocaPtrTy = op.getType();
358 mlir::Type loweredAllocaPtrTy = getTypeConverter()->convertType(allocaPtrTy);
360 cir::AllocaOp loweredOp = cir::AllocaOp::create(
361 rewriter, op.getLoc(), loweredAllocaPtrTy, op.getName(),
362 op.getAlignmentAttr(), adaptor.getDynAllocSize());
363 loweredOp.setInit(op.getInit());
364 loweredOp.setConstant(op.getConstant());
366 rewriter.replaceOp(op, loweredOp);
367 return mlir::success();
370mlir::LogicalResult CIRCastOpABILowering::matchAndRewrite(
371 cir::CastOp op, OpAdaptor adaptor,
372 mlir::ConversionPatternRewriter &rewriter)
const {
373 mlir::Type srcTy = op.getSrc().getType();
375 if (mlir::isa<cir::DataMemberType, cir::MethodType>(srcTy)) {
376 switch (op.getKind()) {
377 case cir::CastKind::bitcast: {
378 mlir::Type destTy = getTypeConverter()->convertType(op.getType());
379 mlir::Value loweredResult;
380 if (mlir::isa<cir::DataMemberType>(srcTy))
381 loweredResult = lowerModule->getCXXABI().lowerDataMemberBitcast(
382 op, destTy, adaptor.getSrc(), rewriter);
384 loweredResult = lowerModule->getCXXABI().lowerMethodBitcast(
385 op, destTy, adaptor.getSrc(), rewriter);
386 rewriter.replaceOp(op, loweredResult);
387 return mlir::success();
389 case cir::CastKind::member_ptr_to_bool: {
390 mlir::Value loweredResult;
391 if (mlir::isa<cir::DataMemberType>(srcTy))
392 loweredResult = lowerModule->getCXXABI().lowerDataMemberToBoolCast(
393 op, adaptor.getSrc(), rewriter);
395 loweredResult = lowerModule->getCXXABI().lowerMethodToBoolCast(
396 op, adaptor.getSrc(), rewriter);
397 rewriter.replaceOp(op, loweredResult);
398 return mlir::success();
405 mlir::Value loweredResult = cir::CastOp::create(
406 rewriter, op.getLoc(), getTypeConverter()->convertType(op.getType()),
407 adaptor.getKind(), adaptor.getSrc());
408 rewriter.replaceOp(op, loweredResult);
409 return mlir::success();
414 const mlir::DataLayout &layout,
415 const mlir::TypeConverter &tc,
417 mlir::Attribute initVal) {
418 if (mlir::isa_and_present<cir::UndefAttr>(initVal))
419 return cir::UndefAttr::get(tc.convertType(ty));
421 if (mlir::isa_and_present<cir::PoisonAttr>(initVal))
422 return cir::PoisonAttr::get(tc.convertType(ty));
424 if (mlir::isa<cir::DataMemberType>(ty)) {
428 mlir::dyn_cast_if_present<cir::DataMemberOffsetAttr>(initVal))
431 auto dataMemberVal = mlir::cast_if_present<cir::DataMemberAttr>(initVal);
435 if (mlir::isa<cir::MethodType>(ty)) {
436 auto methodVal = mlir::cast_if_present<cir::MethodAttr>(initVal);
440 if (
auto arrTy = mlir::dyn_cast<cir::ArrayType>(ty)) {
441 auto loweredArrTy = mlir::cast<cir::ArrayType>(tc.convertType(arrTy));
446 if (
auto zeroVal = mlir::dyn_cast_if_present<cir::ZeroAttr>(initVal))
447 return cir::ZeroAttr::get(loweredArrTy);
449 auto arrayVal = mlir::cast<cir::ConstArrayAttr>(initVal);
455 if (mlir::isa<mlir::StringAttr>(arrayVal.getElts())) {
456 assert(loweredArrTy == arrTy &&
457 "string-literal array type should not change under CXX ABI");
461 auto arrayElts = mlir::cast<ArrayAttr>(arrayVal.getElts());
463 loweredElements.reserve(arrTy.getSize());
464 for (
const mlir::Attribute &attr : arrayElts) {
465 auto typedAttr = cast<mlir::TypedAttr>(attr);
467 lowerModule, layout, tc, typedAttr.getType(), typedAttr));
470 return cir::ConstArrayAttr::get(
471 loweredArrTy, mlir::ArrayAttr::get(ty.getContext(), loweredElements),
472 arrayVal.getTrailingZerosNum());
475 if (
auto recordTy = mlir::dyn_cast<cir::RecordType>(ty)) {
477 mlir::dyn_cast<cir::RecordType>(tc.convertType(recordTy));
481 if (
auto recVal = mlir::dyn_cast_if_present<cir::ZeroAttr>(initVal))
482 return cir::ZeroAttr::get(convertedTy);
485 mlir::dyn_cast_if_present<cir::ConstRecordAttr>(initVal)) {
486 auto recordMembers = mlir::cast<ArrayAttr>(recVal.getMembers());
489 loweredMembers.reserve(recordMembers.size());
491 for (
const mlir::Attribute &attr : recordMembers) {
492 auto typedAttr = cast<mlir::TypedAttr>(attr);
494 lowerModule, layout, tc, typedAttr.getType(), typedAttr));
497 return cir::ConstRecordAttr::get(
498 convertedTy, mlir::ArrayAttr::get(ty.getContext(), loweredMembers));
501 assert(!initVal &&
"Record init val type not handled");
506 if (
auto ptrTy = mlir::dyn_cast<cir::PointerType>(ty)) {
507 auto convertedTy = mlir::cast<cir::PointerType>(tc.convertType(ptrTy));
510 if (
auto gva = mlir::dyn_cast_if_present<cir::GlobalViewAttr>(initVal))
511 return cir::GlobalViewAttr::get(convertedTy, gva.getSymbol(),
512 gva.getIndices(), gva.getAddressPoint());
514 if (
auto goa = mlir::dyn_cast_if_present<cir::GlobalOffsetAttr>(initVal))
515 return cir::GlobalOffsetAttr::get(convertedTy, goa.getSymbol(),
519 mlir::dyn_cast_if_present<cir::BlockAddrInfoAttr>(initVal)) {
520 assert(convertedTy == ptrTy &&
"BlockAddrInfo type should not change");
524 auto constPtr = mlir::cast_if_present<cir::ConstPtrAttr>(initVal);
527 return cir::ConstPtrAttr::get(convertedTy, constPtr.getValue());
530 assert(ty == tc.convertType(ty) &&
531 "cir.global or constant operand is not an CXXABI-dependent type");
534 return cast<mlir::TypedAttr>(initVal);
537mlir::LogicalResult CIRConstantOpABILowering::matchAndRewrite(
538 cir::ConstantOp op, OpAdaptor adaptor,
539 mlir::ConversionPatternRewriter &rewriter)
const {
541 mlir::DataLayout layout(op->getParentOfType<mlir::ModuleOp>());
543 lowerModule, layout, *getTypeConverter(), op.getType(), op.getValue());
544 rewriter.replaceOpWithNewOp<ConstantOp>(op, newValue);
545 return mlir::success();
548mlir::LogicalResult CIRCmpOpABILowering::matchAndRewrite(
549 cir::CmpOp op, OpAdaptor adaptor,
550 mlir::ConversionPatternRewriter &rewriter)
const {
551 mlir::Type type = op.getLhs().getType();
553 mlir::Value loweredResult;
554 if (mlir::isa<cir::DataMemberType>(type))
555 loweredResult = lowerModule->getCXXABI().lowerDataMemberCmp(
556 op, adaptor.getLhs(), adaptor.getRhs(), rewriter);
557 else if (mlir::isa<cir::MethodType>(type))
558 loweredResult = lowerModule->getCXXABI().lowerMethodCmp(
559 op, adaptor.getLhs(), adaptor.getRhs(), rewriter);
561 loweredResult = cir::CmpOp::create(
562 rewriter, op.getLoc(), getTypeConverter()->convertType(op.getType()),
563 adaptor.getKind(), adaptor.getLhs(), adaptor.getRhs());
565 rewriter.replaceOp(op, loweredResult);
566 return mlir::success();
569mlir::LogicalResult CIRFuncOpABILowering::matchAndRewrite(
570 cir::FuncOp op, OpAdaptor adaptor,
571 mlir::ConversionPatternRewriter &rewriter)
const {
572 cir::FuncType opFuncType = op.getFunctionType();
573 mlir::TypeConverter::SignatureConversion signatureConversion(
574 opFuncType.getNumInputs());
576 for (
const auto &[i, argType] : llvm::enumerate(opFuncType.getInputs())) {
577 mlir::Type loweredArgType = getTypeConverter()->convertType(argType);
579 return mlir::failure();
580 signatureConversion.addInputs(i, loweredArgType);
583 mlir::Type loweredResultType =
584 getTypeConverter()->convertType(opFuncType.getReturnType());
585 if (!loweredResultType)
586 return mlir::failure();
588 auto loweredFuncType =
589 cir::FuncType::get(signatureConversion.getConvertedTypes(),
590 loweredResultType, opFuncType.isVarArg());
593 if (mlir::failed(rewriter.convertRegionTypes(
594 &op.getBody(), *getTypeConverter(), &signatureConversion)))
595 return mlir::failure();
598 cir::FuncOp loweredFuncOp = rewriter.cloneWithoutRegions(op);
599 loweredFuncOp.setFunctionType(loweredFuncType);
601 loweredFuncOp->getName().walkInherentAttrs(
602 loweredFuncOp, [&](llvm::StringRef, mlir::Attribute &attr) {
603 attr = rewriteAttribute(*getTypeConverter(), op->getContext(), attr);
605 rewriter.inlineRegionBefore(op.getBody(), loweredFuncOp.getBody(),
606 loweredFuncOp.end());
608 rewriter.eraseOp(op);
609 return mlir::success();
612mlir::LogicalResult CIRGlobalOpABILowering::matchAndRewrite(
613 cir::GlobalOp op, OpAdaptor adaptor,
614 mlir::ConversionPatternRewriter &rewriter)
const {
615 mlir::Type ty = op.getSymType();
616 mlir::Type loweredTy = getTypeConverter()->convertType(ty);
618 return mlir::failure();
620 mlir::DataLayout layout(op->getParentOfType<mlir::ModuleOp>());
623 lowerModule, layout, *getTypeConverter(), ty, op.getInitialValueAttr());
625 cir::GlobalOp newOp = rewriter.cloneWithoutRegions(op);
626 newOp.setInitialValueAttr(loweredInit);
627 newOp.setSymType(loweredTy);
631 rewriter.inlineRegionBefore(op.getCtorRegion(), newOp.getCtorRegion(),
632 newOp.getCtorRegion().end());
633 rewriter.inlineRegionBefore(op.getDtorRegion(), newOp.getDtorRegion(),
634 newOp.getDtorRegion().end());
635 rewriter.replaceOp(op, newOp);
636 return mlir::success();
639mlir::LogicalResult CIRBaseDataMemberOpABILowering::matchAndRewrite(
640 cir::BaseDataMemberOp op, OpAdaptor adaptor,
641 mlir::ConversionPatternRewriter &rewriter)
const {
642 mlir::Value loweredResult = lowerModule->getCXXABI().lowerBaseDataMember(
643 op, adaptor.getSrc(), rewriter);
644 rewriter.replaceOp(op, loweredResult);
645 return mlir::success();
648mlir::LogicalResult CIRBaseMethodOpABILowering::matchAndRewrite(
649 cir::BaseMethodOp op, OpAdaptor adaptor,
650 mlir::ConversionPatternRewriter &rewriter)
const {
651 mlir::Value loweredResult =
652 lowerModule->getCXXABI().lowerBaseMethod(op, adaptor.getSrc(), rewriter);
653 rewriter.replaceOp(op, loweredResult);
654 return mlir::success();
657mlir::LogicalResult CIRDeleteArrayOpABILowering::matchAndRewrite(
658 cir::DeleteArrayOp op, OpAdaptor adaptor,
659 mlir::ConversionPatternRewriter &rewriter)
const {
660 mlir::FlatSymbolRefAttr deleteFn = op.getDeleteFnAttr();
661 mlir::Location loc = op->getLoc();
662 mlir::Value loweredAddress = adaptor.getAddress();
664 cir::UsualDeleteParamsAttr deleteParams = op.getDeleteParamsAttr();
666 deleteParams = cir::UsualDeleteParamsAttr::get(op.getContext(),
false,
667 std::nullopt,
false,
false);
668 bool cookieRequired = deleteParams.getSize() || op.getElementDtorAttr();
670 assert(!deleteParams.getDestroyingDelete() &&
671 "destroying delete not legal on arrays");
672 assert(!deleteParams.getTypeAwareDelete() &&
673 "type-aware delete not legal on arrays");
675 const CIRCXXABI &cxxABI = lowerModule->getCXXABI();
684 mlir::Value deletePtr;
685 mlir::Value numElements;
686 auto ptrTy = mlir::cast<cir::PointerType>(loweredAddress.getType());
688 mlir::DataLayout dl(op->getParentOfType<mlir::ModuleOp>());
691 cir::IntType sizeTy = cirBuilder.getUIntNTy(ptrWidth);
693 if (cookieRequired) {
696 cxxABI.
readArrayCookie(loc, loweredAddress, elementAlign, dl, cirBuilder,
697 numElements, deletePtr, cookieSize);
699 deletePtr = cir::CastOp::create(
700 rewriter, loc, cirBuilder.getVoidPtrTy(ptrTy.getAddrSpace()),
701 cir::CastKind::bitcast, loweredAddress);
711 mlir::FlatSymbolRefAttr dtorFn = op.getElementDtorAttr();
714 auto getCalleeCallingConv = [&](mlir::FlatSymbolRefAttr callee) {
716 mlir::SymbolTable::lookupNearestSymbolFrom<cir::FuncOp>(op, callee))
717 return fn.getCallingConv();
718 return cir::CallingConv::C;
721 cir::CleanupKind cleanupKind =
722 op.getDtorMayThrow() ? cir::CleanupKind::All : cir::CleanupKind::Normal;
723 cir::CleanupScopeOp::create(
724 rewriter, loc, cleanupKind,
726 [&](mlir::OpBuilder &b, mlir::Location l) {
728 auto arrayDtor = cir::ArrayDtor::create(
729 b, l, loweredAddress, numElements,
730 [&](mlir::OpBuilder &bb, mlir::Location ll) {
732 bb.getInsertionBlock()->addArgument(ptrTy, ll);
733 auto dtorCall = cir::CallOp::create(
734 bb, ll, dtorFn, cir::VoidType(), mlir::ValueRange{
arg});
735 dtorCall.setCallingConv(getCalleeCallingConv(dtorFn));
736 if (!op.getDtorMayThrow())
737 dtorCall.setNothrowAttr(bb.getUnitAttr());
738 cir::YieldOp::create(bb, ll);
740 if (op.getDtorMayThrow())
741 arrayDtor.setDtorMayThrow(
true);
743 cir::YieldOp::create(b, l);
746 [&](mlir::OpBuilder &b, mlir::Location l) {
749 if (deleteParams.getSize()) {
750 uint64_t eltSizeBytes = dl.getTypeSizeInBits(ptrTy.getPointee()) / 8;
751 auto eltSizeVal = cir::ConstantOp::create(
752 b, l, cir::IntAttr::get(sizeTy, eltSizeBytes));
753 mlir::Value allocSize =
754 cir::MulOp::create(b, l, sizeTy, eltSizeVal, numElements);
755 auto cookieSizeVal = cir::ConstantOp::create(
756 b, l, cir::IntAttr::get(sizeTy, cookieSize.
getQuantity()));
758 cir::AddOp::create(b, l, sizeTy, allocSize, cookieSizeVal);
761 if (deleteParams.getAlignment()) {
762 auto alignVal = cir::ConstantOp::create(
763 b, l, cir::IntAttr::get(sizeTy, *deleteParams.getAlignment()));
768 cir::CallOp::create(b, l, deleteFn, cir::VoidType(), callArgs);
769 deleteCall.setCallingConv(getCalleeCallingConv(deleteFn));
772 deleteCall.setNothrowAttr(b.getUnitAttr());
773 cir::YieldOp::create(b, l);
776 rewriter.eraseOp(op);
777 return mlir::success();
780mlir::LogicalResult CIRDerivedDataMemberOpABILowering::matchAndRewrite(
781 cir::DerivedDataMemberOp op, OpAdaptor adaptor,
782 mlir::ConversionPatternRewriter &rewriter)
const {
783 mlir::Value loweredResult = lowerModule->getCXXABI().lowerDerivedDataMember(
784 op, adaptor.getSrc(), rewriter);
785 rewriter.replaceOp(op, loweredResult);
786 return mlir::success();
789mlir::LogicalResult CIRDerivedMethodOpABILowering::matchAndRewrite(
790 cir::DerivedMethodOp op, OpAdaptor adaptor,
791 mlir::ConversionPatternRewriter &rewriter)
const {
792 mlir::Value loweredResult = lowerModule->getCXXABI().lowerDerivedMethod(
793 op, adaptor.getSrc(), rewriter);
794 rewriter.replaceOp(op, loweredResult);
795 return mlir::success();
798mlir::LogicalResult CIRDynamicCastOpABILowering::matchAndRewrite(
799 cir::DynamicCastOp op, OpAdaptor adaptor,
800 mlir::ConversionPatternRewriter &rewriter)
const {
801 mlir::Value loweredResult =
802 lowerModule->getCXXABI().lowerDynamicCast(op, rewriter);
803 rewriter.replaceOp(op, loweredResult);
804 return mlir::success();
807mlir::LogicalResult CIRGetMethodOpABILowering::matchAndRewrite(
808 cir::GetMethodOp op, OpAdaptor adaptor,
809 mlir::ConversionPatternRewriter &rewriter)
const {
812 lowerModule->getCXXABI().lowerGetMethod(
813 op, callee, thisArg, adaptor.getMethod(), adaptor.getObject(), rewriter);
814 rewriter.replaceOp(op, {callee, thisArg});
815 return mlir::success();
818mlir::LogicalResult CIRGetRuntimeMemberOpABILowering::matchAndRewrite(
819 cir::GetRuntimeMemberOp op, OpAdaptor adaptor,
820 mlir::ConversionPatternRewriter &rewriter)
const {
821 mlir::Type resTy = getTypeConverter()->convertType(op.getType());
822 mlir::Operation *newOp = lowerModule->getCXXABI().lowerGetRuntimeMember(
823 op, resTy, adaptor.getAddr(), adaptor.getMember(), rewriter);
824 rewriter.replaceOp(op, newOp);
825 return mlir::success();
828mlir::LogicalResult CIRVTableGetTypeInfoOpABILowering::matchAndRewrite(
829 cir::VTableGetTypeInfoOp op, OpAdaptor adaptor,
830 mlir::ConversionPatternRewriter &rewriter)
const {
831 mlir::Value loweredResult =
832 lowerModule->getCXXABI().lowerVTableGetTypeInfo(op, rewriter);
833 rewriter.replaceOp(op, loweredResult);
834 return mlir::success();
843 CIRABITypeConverter(mlir::MLIRContext &ctx, mlir::DataLayout &dataLayout,
844 cir::LowerModule &lowerModule)
845 : RecordRewritingTypeConverter(ctx) {
846 addConversion([&](cir::DataMemberType type) -> mlir::Type {
849 return convertType(abiType);
851 addConversion([&](cir::MethodType type) -> mlir::Type {
853 return convertType(abiType);
860 bool typeMayChange(mlir::Type type)
const override {
861 return mlir::isa<cir::DataMemberType, cir::MethodType>(type);
868 const mlir::TypeConverter &typeConverter) {
869 target.addLegalOp<mlir::ModuleOp>();
874 target.addDynamicallyLegalDialect<cir::CIRDialect>(
875 [&typeConverter](mlir::Operation *op) {
876 if (!typeConverter.isLegal(op))
879 bool attrs = areCXXABIInherentAttrsLegal(op, typeConverter);
882 std::all_of(op->getRegions().begin(), op->getRegions().end(),
883 [&typeConverter](mlir::Region ®ion) {
884 return typeConverter.isLegal(®ion);
888 target.addDynamicallyLegalDialect<mlir::acc::OpenACCDialect>(
889 [&typeConverter](mlir::Operation *op) {
890 if (!typeConverter.isLegal(op))
893 bool attrs = areCXXABIInherentAttrsLegal(op, typeConverter);
896 std::all_of(op->getRegions().begin(), op->getRegions().end(),
897 [&typeConverter](mlir::Region ®ion) {
898 return typeConverter.isLegal(®ion);
904 target.addDynamicallyLegalOp<cir::CastOp>([&typeConverter](cir::CastOp op) {
905 if (op.getSrc().getType() == op.getType()) {
906 switch (op.getKind()) {
907 case cir::CastKind::bitcast:
908 case cir::CastKind::address_space:
909 case cir::CastKind::float_complex:
910 case cir::CastKind::int_complex:
916 if (!typeConverter.isLegal(op.getOperation()))
920 return areCXXABIInherentAttrsLegal(op, typeConverter);
924 target.addDynamicallyLegalOp<cir::FuncOp>([&typeConverter](cir::FuncOp op) {
925 bool attrs = areCXXABIInherentAttrsLegal(op, typeConverter);
927 return attrs && typeConverter.isLegal(op.getFunctionType());
929 target.addDynamicallyLegalOp<cir::GlobalOp>(
930 [&typeConverter](cir::GlobalOp op) {
931 return typeConverter.isLegal(op.getSymType());
935 target.addIllegalOp<cir::DeleteArrayOp>();
936 target.addIllegalOp<cir::DynamicCastOp>();
937 target.addIllegalOp<cir::VTableGetTypeInfoOp>();
944void CXXABILoweringPass::runOnOperation() {
945 auto mod = mlir::cast<mlir::ModuleOp>(getOperation());
946 mlir::MLIRContext *ctx = mod.getContext();
949 assert(lowerModule &&
"LowerModule shouldn't be null");
950 if (!lowerModule->hasTarget()) {
951 mod.emitError() <<
getArgument() <<
" requires a module with a supported '"
952 << cir::CIRDialect::getTripleAttrName() <<
"' attribute";
953 return signalPassFailure();
956 if (!lowerModule->hasCXXABI()) {
957 mod.emitError() <<
"C++ ABI '"
959 lowerModule->getCXXABIKind())
960 <<
"' is not yet supported by CIR";
961 return signalPassFailure();
964 mlir::DataLayout dataLayout(mod);
965 CIRABITypeConverter typeConverter(*ctx, dataLayout, *lowerModule);
967 mlir::RewritePatternSet patterns(ctx);
968 patterns.add<CIRGenericCXXABILoweringPattern>(patterns.getContext(),
971#define GET_ABI_LOWERING_PATTERNS_LIST
972#include "clang/CIR/Dialect/IR/CIRLowering.inc"
973#undef GET_ABI_LOWERING_PATTERNS_LIST
974 >(patterns.getContext(), typeConverter, dataLayout, *lowerModule);
976 mlir::ConversionTarget target(*ctx);
979 llvm::SmallVector<mlir::Operation *> ops;
985 mlir::ConversionConfig config;
986 config.allowPatternRollback =
false;
987 if (failed(mlir::applyPartialConversion(ops, target, std::move(patterns),
991 typeConverter.restoreRecordTypeNames();
995 return std::make_unique<CXXABILoweringPass>();
#define CXX_ABI_ALWAYS_LEGAL_ATTRS
static void populateCXXABIConversionTarget(mlir::ConversionTarget &target, const mlir::TypeConverter &typeConverter)
static mlir::TypedAttr lowerInitialValue(const LowerModule *lowerModule, const mlir::DataLayout &layout, const mlir::TypeConverter &tc, mlir::Type ty, mlir::Attribute initVal)
static const TemplateArgument & getArgument(const TemplateArgument &A)
virtual mlir::Type lowerMethodType(cir::MethodType type, const mlir::TypeConverter &typeConverter) const =0
Lower the given member function pointer type to its ABI type.
virtual mlir::TypedAttr lowerDataMemberConstant(cir::DataMemberAttr attr, const mlir::DataLayout &layout, const mlir::TypeConverter &typeConverter) const =0
Lower the given data member pointer constant to a constant of the ABI type.
virtual mlir::TypedAttr lowerDataMemberOffsetConstant(cir::DataMemberOffsetAttr attr, const mlir::DataLayout &layout, const mlir::TypeConverter &typeConverter) const =0
Lower the given by-offset data member pointer constant (used for members with no CIR field index,...
virtual mlir::TypedAttr lowerMethodConstant(cir::MethodAttr attr, const mlir::DataLayout &layout, const mlir::TypeConverter &typeConverter) const =0
Lower the given member function pointer constant to a constant of the ABI type.
virtual mlir::Type lowerDataMemberType(cir::DataMemberType type, const mlir::TypeConverter &typeConverter) const =0
Lower the given data member pointer type to its ABI type.
void readArrayCookie(mlir::Location loc, mlir::Value elementPtr, clang::CharUnits elementAlign, const mlir::DataLayout &dataLayout, CIRBaseBuilderTy &builder, mlir::Value &numElements, mlir::Value &allocPtr, clang::CharUnits &cookieSize) const
Read the array cookie for a dynamically-allocated array whose first element is at elementPtr.
CIRCXXABI & getCXXABI() const
A type converter that converts the types nested in pointers, arrays, functions and records.
This is an opaque type for sizes expressed in character units.
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
static const auto & getSpelling(Kind ABIKind)
void collectUnreachable(mlir::Operation *parent, llvm::SmallVectorImpl< mlir::Operation * > &ops)
Collect ops in blocks that are unreachable from their region's entry, appending them to ops.
std::unique_ptr< LowerModule > createLowerModule(mlir::ModuleOp module)
const internal::VariadicAllOfMatcher< Attr > attr
bool isa(CodeGen::Address addr)
@ Default
Set to the current date and time.
std::unique_ptr< Pass > createCXXABILoweringPass()
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)