12#include "mlir/Dialect/OpenACC/OpenACCOpsDialect.h.inc"
13#include "mlir/Dialect/OpenMP/OpenMPOpsDialect.h.inc"
14#include "mlir/IR/PatternMatch.h"
15#include "mlir/Interfaces/DataLayoutInterfaces.h"
16#include "mlir/Pass/Pass.h"
17#include "mlir/Transforms/DialectConversion.h"
27#include "llvm/ADT/ScopeExit.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"
70 if (isa<cir::DataMemberAttr, cir::MethodAttr>(
attr))
73 return llvm::TypeSwitch<mlir::Attribute, bool>(
attr)
76 [&tc](cir::ZeroAttr za) {
return tc.isLegal(za.getType()); })
77 .Case<cir::PoisonAttr>(
78 [&tc](cir::PoisonAttr pa) {
return tc.isLegal(pa.getType()); })
79 .Case<cir::UndefAttr>(
80 [&tc](cir::UndefAttr uda) {
return tc.isLegal(uda.getType()); })
81 .Case<mlir::TypeAttr>(
82 [&tc](mlir::TypeAttr ta) {
return tc.isLegal(ta.getValue()); })
83 .Case<cir::ConstPtrAttr>(
84 [&tc](cir::ConstPtrAttr cpa) {
return tc.isLegal(cpa.getType()); })
85 .Case<cir::CXXCtorAttr>(
86 [&tc](cir::CXXCtorAttr ca) {
return tc.isLegal(ca.getType()); })
87 .Case<cir::CXXDtorAttr>(
88 [&tc](cir::CXXDtorAttr da) {
return tc.isLegal(da.getType()); })
89 .Case<cir::CXXAssignAttr>(
90 [&tc](cir::CXXAssignAttr aa) {
return tc.isLegal(aa.getType()); })
94 .Case<mlir::ArrayAttr>([&tc](mlir::ArrayAttr array) {
95 return llvm::all_of(array.getValue(), [&tc](mlir::Attribute
attr) {
96 return isCXXABIAttributeLegal(tc, attr);
99 .Case<mlir::DictionaryAttr>([&tc](mlir::DictionaryAttr dict) {
100 return llvm::all_of(dict.getValue(), [&tc](mlir::NamedAttribute na) {
101 return isCXXABIAttributeLegal(tc, na.getValue());
105 .Case<cir::ConstArrayAttr>([&tc](cir::ConstArrayAttr array) {
106 return tc.isLegal(array.getType()) &&
107 isCXXABIAttributeLegal(tc, array.getElts());
109 .Case<cir::GlobalViewAttr>([&tc](cir::GlobalViewAttr gva) {
110 return tc.isLegal(gva.getType()) &&
111 isCXXABIAttributeLegal(tc, gva.getIndices());
113 .Case<cir::VTableAttr>([&tc](cir::VTableAttr vta) {
114 return tc.isLegal(vta.getType()) &&
115 isCXXABIAttributeLegal(tc, vta.getData());
117 .Case<cir::TypeInfoAttr>([&tc](cir::TypeInfoAttr tia) {
118 return tc.isLegal(tia.getType()) &&
119 isCXXABIAttributeLegal(tc, tia.getData());
121 .Case<cir::DynamicCastInfoAttr>([&tc](cir::DynamicCastInfoAttr dcia) {
122 return isCXXABIAttributeLegal(tc, dcia.getSrcRtti()) &&
123 isCXXABIAttributeLegal(tc, dcia.getDestRtti()) &&
124 isCXXABIAttributeLegal(tc, dcia.getRuntimeFunc()) &&
125 isCXXABIAttributeLegal(tc, dcia.getBadCastFunc());
127 .Case<cir::ConstRecordAttr>([&tc](cir::ConstRecordAttr cra) {
128 return tc.isLegal(cra.getType()) &&
129 isCXXABIAttributeLegal(tc, cra.getMembers());
140mlir::Attribute rewriteAttribute(
const mlir::TypeConverter &tc,
141 mlir::MLIRContext *ctx, mlir::Attribute attr) {
144 if (isCXXABIAttributeLegal(tc, attr))
152 return llvm::TypeSwitch<mlir::Attribute, mlir::Attribute>(attr)
154 .Case<cir::ZeroAttr>([&tc](cir::ZeroAttr za) {
155 return cir::ZeroAttr::get(tc.convertType(za.getType()));
157 .Case<cir::PoisonAttr>([&tc](cir::PoisonAttr pa) {
158 return cir::PoisonAttr::get(tc.convertType(pa.getType()));
160 .Case<cir::UndefAttr>([&tc](cir::UndefAttr uda) {
161 return cir::UndefAttr::get(tc.convertType(uda.getType()));
163 .Case<mlir::TypeAttr>([&tc](mlir::TypeAttr ta) {
164 return mlir::TypeAttr::get(tc.convertType(ta.getValue()));
166 .Case<cir::ConstPtrAttr>([&tc](cir::ConstPtrAttr cpa) {
167 return cir::ConstPtrAttr::get(tc.convertType(cpa.getType()),
170 .Case<cir::CXXCtorAttr>([&tc](cir::CXXCtorAttr ca) {
171 return cir::CXXCtorAttr::get(tc.convertType(ca.getType()),
172 ca.getCtorKind(), ca.getIsTrivial());
174 .Case<cir::CXXDtorAttr>([&tc](cir::CXXDtorAttr da) {
175 return cir::CXXDtorAttr::get(tc.convertType(da.getType()),
178 .Case<cir::CXXAssignAttr>([&tc](cir::CXXAssignAttr aa) {
179 return cir::CXXAssignAttr::get(tc.convertType(aa.getType()),
180 aa.getAssignKind(), aa.getIsTrivial());
184 .Case<mlir::ArrayAttr>([&tc, ctx](mlir::ArrayAttr array) {
186 for (mlir::Attribute a : array.getValue())
187 elts.push_back(rewriteAttribute(tc, ctx, a));
188 return mlir::ArrayAttr::get(ctx, elts);
190 .Case<mlir::DictionaryAttr>([&tc, ctx](mlir::DictionaryAttr dict) {
192 for (mlir::NamedAttribute na : dict.getValue())
193 elts.emplace_back(na.getName(),
194 rewriteAttribute(tc, ctx, na.getValue()));
196 return mlir::DictionaryAttr::get(ctx, elts);
199 .Case<cir::ConstArrayAttr>([&tc, ctx](cir::ConstArrayAttr array) {
200 return cir::ConstArrayAttr::get(
201 ctx, tc.convertType(array.getType()),
202 rewriteAttribute(tc, ctx, array.getElts()),
203 array.getTrailingZerosNum());
205 .Case<cir::GlobalViewAttr>([&tc, ctx](cir::GlobalViewAttr gva) {
206 return cir::GlobalViewAttr::get(
207 tc.convertType(gva.getType()), gva.getSymbol(),
208 mlir::cast<mlir::ArrayAttr>(
209 rewriteAttribute(tc, ctx, gva.getIndices())));
211 .Case<cir::VTableAttr>([&tc, ctx](cir::VTableAttr vta) {
212 return cir::VTableAttr::get(
213 tc.convertType(vta.getType()),
214 mlir::cast<mlir::ArrayAttr>(
215 rewriteAttribute(tc, ctx, vta.getData())));
217 .Case<cir::TypeInfoAttr>([&tc, ctx](cir::TypeInfoAttr tia) {
218 return cir::TypeInfoAttr::get(
219 tc.convertType(tia.getType()),
220 mlir::cast<mlir::ArrayAttr>(
221 rewriteAttribute(tc, ctx, tia.getData())));
223 .Case<cir::DynamicCastInfoAttr>([&tc,
224 ctx](cir::DynamicCastInfoAttr dcia) {
225 return cir::DynamicCastInfoAttr::get(
226 mlir::cast<cir::GlobalViewAttr>(
227 rewriteAttribute(tc, ctx, dcia.getSrcRtti())),
228 mlir::cast<cir::GlobalViewAttr>(
229 rewriteAttribute(tc, ctx, dcia.getDestRtti())),
230 dcia.getRuntimeFunc(), dcia.getBadCastFunc(), dcia.getOffsetHint());
232 .Case<cir::ConstRecordAttr>([&tc, ctx](cir::ConstRecordAttr cra) {
233 return cir::ConstRecordAttr::get(
234 ctx, tc.convertType(cra.getType()),
235 mlir::cast<mlir::ArrayAttr>(
236 rewriteAttribute(tc, ctx, cra.getMembers())));
238 .DefaultUnreachable(
"unrewritten illegal attribute kind");
241#define GET_ABI_LOWERING_PATTERNS
242#include "clang/CIR/Dialect/IR/CIRLowering.inc"
243#undef GET_ABI_LOWERING_PATTERNS
245struct CXXABILoweringPass
246 :
public impl::CXXABILoweringBase<CXXABILoweringPass> {
247 CXXABILoweringPass() =
default;
248 void runOnOperation()
override;
256class CIRGenericCXXABILoweringPattern :
public mlir::ConversionPattern {
258 CIRGenericCXXABILoweringPattern(mlir::MLIRContext *context,
259 const mlir::TypeConverter &typeConverter)
260 : mlir::ConversionPattern(typeConverter, MatchAnyOpTypeTag(),
264 matchAndRewrite(mlir::Operation *op, llvm::ArrayRef<mlir::Value> operands,
265 mlir::ConversionPatternRewriter &rewriter)
const override {
267 if (llvm::isa<cir::AllocaOp, cir::BaseDataMemberOp, cir::BaseMethodOp,
268 cir::CastOp, cir::CmpOp, cir::ConstantOp, cir::DeleteArrayOp,
269 cir::DerivedDataMemberOp, cir::DerivedMethodOp, cir::FuncOp,
270 cir::GetMethodOp, cir::GetRuntimeMemberOp, cir::GlobalOp>(op))
271 return mlir::failure();
273 const mlir::TypeConverter *typeConverter = getTypeConverter();
274 assert(typeConverter &&
275 "CIRGenericCXXABILoweringPattern requires a type converter");
276 bool operandsAndResultsLegal = typeConverter->isLegal(op);
278 std::all_of(op->getRegions().begin(), op->getRegions().end(),
279 [typeConverter](mlir::Region ®ion) {
280 return typeConverter->isLegal(®ion);
283 llvm::all_of(op->getAttrs(), [typeConverter](mlir::NamedAttribute na) {
284 return isCXXABIAttributeLegal(*typeConverter, na.getValue());
287 if (operandsAndResultsLegal && regionsLegal && attrsLegal) {
290 return mlir::failure();
293 mlir::OperationState loweredOpState(op->getLoc(), op->getName());
294 loweredOpState.addOperands(operands);
295 loweredOpState.addSuccessors(op->getSuccessors());
298 llvm::SmallVector<mlir::NamedAttribute> attrs;
299 for (
const mlir::NamedAttribute &na : op->getAttrs())
302 rewriteAttribute(*typeConverter, op->getContext(), na.getValue())});
303 loweredOpState.addAttributes(attrs);
306 llvm::SmallVector<mlir::Type> loweredResultTypes;
307 loweredResultTypes.reserve(op->getNumResults());
308 for (mlir::Type result : op->getResultTypes())
309 loweredResultTypes.push_back(typeConverter->convertType(result));
310 loweredOpState.addTypes(loweredResultTypes);
313 for (mlir::Region ®ion : op->getRegions()) {
314 mlir::Region *loweredRegion = loweredOpState.addRegion();
315 rewriter.inlineRegionBefore(region, *loweredRegion, loweredRegion->end());
317 rewriter.convertRegionTypes(loweredRegion, *getTypeConverter())))
318 return mlir::failure();
322 mlir::Operation *loweredOp = rewriter.create(loweredOpState);
324 rewriter.replaceOp(op, loweredOp);
325 return mlir::success();
331mlir::LogicalResult CIRAllocaOpABILowering::matchAndRewrite(
332 cir::AllocaOp op, OpAdaptor adaptor,
333 mlir::ConversionPatternRewriter &rewriter)
const {
334 mlir::Type allocaPtrTy = op.getType();
335 mlir::Type loweredAllocaPtrTy = getTypeConverter()->convertType(allocaPtrTy);
337 cir::AllocaOp loweredOp = cir::AllocaOp::create(
338 rewriter, op.getLoc(), loweredAllocaPtrTy, op.getName(),
339 op.getAlignmentAttr(), adaptor.getDynAllocSize());
340 loweredOp.setInit(op.getInit());
341 loweredOp.setConstant(op.getConstant());
342 loweredOp.setAnnotationsAttr(op.getAnnotationsAttr());
344 rewriter.replaceOp(op, loweredOp);
345 return mlir::success();
348mlir::LogicalResult CIRCastOpABILowering::matchAndRewrite(
349 cir::CastOp op, OpAdaptor adaptor,
350 mlir::ConversionPatternRewriter &rewriter)
const {
351 mlir::Type srcTy = op.getSrc().getType();
353 if (mlir::isa<cir::DataMemberType, cir::MethodType>(srcTy)) {
354 switch (op.getKind()) {
355 case cir::CastKind::bitcast: {
356 mlir::Type destTy = getTypeConverter()->convertType(op.getType());
357 mlir::Value loweredResult;
358 if (mlir::isa<cir::DataMemberType>(srcTy))
359 loweredResult = lowerModule->getCXXABI().lowerDataMemberBitcast(
360 op, destTy, adaptor.getSrc(), rewriter);
362 loweredResult = lowerModule->getCXXABI().lowerMethodBitcast(
363 op, destTy, adaptor.getSrc(), rewriter);
364 rewriter.replaceOp(op, loweredResult);
365 return mlir::success();
367 case cir::CastKind::member_ptr_to_bool: {
368 mlir::Value loweredResult;
369 if (mlir::isa<cir::DataMemberType>(srcTy))
370 loweredResult = lowerModule->getCXXABI().lowerDataMemberToBoolCast(
371 op, adaptor.getSrc(), rewriter);
373 loweredResult = lowerModule->getCXXABI().lowerMethodToBoolCast(
374 op, adaptor.getSrc(), rewriter);
375 rewriter.replaceOp(op, loweredResult);
376 return mlir::success();
383 mlir::Value loweredResult = cir::CastOp::create(
384 rewriter, op.getLoc(), getTypeConverter()->convertType(op.getType()),
385 adaptor.getKind(), adaptor.getSrc());
386 rewriter.replaceOp(op, loweredResult);
387 return mlir::success();
392 const mlir::DataLayout &layout,
393 const mlir::TypeConverter &tc,
395 mlir::Attribute initVal) {
396 if (mlir::isa<cir::DataMemberType>(ty)) {
397 auto dataMemberVal = mlir::cast_if_present<cir::DataMemberAttr>(initVal);
401 if (mlir::isa<cir::MethodType>(ty)) {
402 auto methodVal = mlir::cast_if_present<cir::MethodAttr>(initVal);
406 if (
auto arrTy = mlir::dyn_cast<cir::ArrayType>(ty)) {
407 auto loweredArrTy = mlir::cast<cir::ArrayType>(tc.convertType(arrTy));
412 if (
auto zeroVal = mlir::dyn_cast_if_present<cir::ZeroAttr>(initVal))
413 return cir::ZeroAttr::get(loweredArrTy);
415 auto arrayVal = mlir::cast<cir::ConstArrayAttr>(initVal);
421 if (mlir::isa<mlir::StringAttr>(arrayVal.getElts())) {
422 assert(loweredArrTy == arrTy &&
423 "string-literal array type should not change under CXX ABI");
427 auto arrayElts = mlir::cast<ArrayAttr>(arrayVal.getElts());
429 loweredElements.reserve(arrTy.getSize());
430 for (
const mlir::Attribute &attr : arrayElts) {
431 auto typedAttr = cast<mlir::TypedAttr>(attr);
433 lowerModule, layout, tc, typedAttr.getType(), typedAttr));
436 return cir::ConstArrayAttr::get(
437 loweredArrTy, mlir::ArrayAttr::get(ty.getContext(), loweredElements),
438 arrayVal.getTrailingZerosNum());
441 if (
auto recordTy = mlir::dyn_cast<cir::RecordType>(ty)) {
443 mlir::dyn_cast<cir::RecordType>(tc.convertType(recordTy));
447 if (
auto recVal = mlir::dyn_cast_if_present<cir::ZeroAttr>(initVal))
448 return cir::ZeroAttr::get(convertedTy);
450 if (
auto undefVal = mlir::dyn_cast_if_present<cir::UndefAttr>(initVal))
451 return cir::UndefAttr::get(convertedTy);
455 if (
auto poisonVal = mlir::dyn_cast_if_present<cir::PoisonAttr>(initVal))
456 return cir::PoisonAttr::get(convertedTy);
459 mlir::dyn_cast_if_present<cir::ConstRecordAttr>(initVal)) {
460 auto recordMembers = mlir::cast<ArrayAttr>(recVal.getMembers());
463 loweredMembers.reserve(recordMembers.size());
465 for (
const mlir::Attribute &attr : recordMembers) {
466 auto typedAttr = cast<mlir::TypedAttr>(attr);
468 lowerModule, layout, tc, typedAttr.getType(), typedAttr));
471 return cir::ConstRecordAttr::get(
472 convertedTy, mlir::ArrayAttr::get(ty.getContext(), loweredMembers));
475 assert(!initVal &&
"Record init val type not handled");
480 if (
auto ptrTy = mlir::dyn_cast<cir::PointerType>(ty)) {
481 auto convertedTy = mlir::cast<cir::PointerType>(tc.convertType(ptrTy));
484 if (
auto gva = mlir::dyn_cast_if_present<cir::GlobalViewAttr>(initVal))
485 return cir::GlobalViewAttr::get(convertedTy, gva.getSymbol(),
488 auto constPtr = mlir::cast_if_present<cir::ConstPtrAttr>(initVal);
491 return cir::ConstPtrAttr::get(convertedTy, constPtr.getValue());
494 assert(ty == tc.convertType(ty) &&
495 "cir.global or constant operand is not an CXXABI-dependent type");
498 return cast<mlir::TypedAttr>(initVal);
501mlir::LogicalResult CIRConstantOpABILowering::matchAndRewrite(
502 cir::ConstantOp op, OpAdaptor adaptor,
503 mlir::ConversionPatternRewriter &rewriter)
const {
505 mlir::DataLayout layout(op->getParentOfType<mlir::ModuleOp>());
507 lowerModule, layout, *getTypeConverter(), op.getType(), op.getValue());
508 rewriter.replaceOpWithNewOp<ConstantOp>(op, newValue);
509 return mlir::success();
512mlir::LogicalResult CIRCmpOpABILowering::matchAndRewrite(
513 cir::CmpOp op, OpAdaptor adaptor,
514 mlir::ConversionPatternRewriter &rewriter)
const {
515 mlir::Type type = op.getLhs().getType();
517 mlir::Value loweredResult;
518 if (mlir::isa<cir::DataMemberType>(type))
519 loweredResult = lowerModule->getCXXABI().lowerDataMemberCmp(
520 op, adaptor.getLhs(), adaptor.getRhs(), rewriter);
521 else if (mlir::isa<cir::MethodType>(type))
522 loweredResult = lowerModule->getCXXABI().lowerMethodCmp(
523 op, adaptor.getLhs(), adaptor.getRhs(), rewriter);
525 loweredResult = cir::CmpOp::create(
526 rewriter, op.getLoc(), getTypeConverter()->convertType(op.getType()),
527 adaptor.getKind(), adaptor.getLhs(), adaptor.getRhs());
529 rewriter.replaceOp(op, loweredResult);
530 return mlir::success();
533mlir::LogicalResult CIRFuncOpABILowering::matchAndRewrite(
534 cir::FuncOp op, OpAdaptor adaptor,
535 mlir::ConversionPatternRewriter &rewriter)
const {
536 cir::FuncType opFuncType = op.getFunctionType();
537 mlir::TypeConverter::SignatureConversion signatureConversion(
538 opFuncType.getNumInputs());
540 for (
const auto &[i, argType] : llvm::enumerate(opFuncType.getInputs())) {
541 mlir::Type loweredArgType = getTypeConverter()->convertType(argType);
543 return mlir::failure();
544 signatureConversion.addInputs(i, loweredArgType);
547 mlir::Type loweredResultType =
548 getTypeConverter()->convertType(opFuncType.getReturnType());
549 if (!loweredResultType)
550 return mlir::failure();
552 auto loweredFuncType =
553 cir::FuncType::get(signatureConversion.getConvertedTypes(),
554 loweredResultType, opFuncType.isVarArg());
557 cir::FuncOp loweredFuncOp = rewriter.cloneWithoutRegions(op);
558 loweredFuncOp.setFunctionType(loweredFuncType);
561 for (
const mlir::NamedAttribute &na : op->getAttrs())
563 {na.getName(), rewriteAttribute(*getTypeConverter(), op->getContext(),
566 loweredFuncOp->setAttrs(attrs);
568 rewriter.inlineRegionBefore(op.getBody(), loweredFuncOp.getBody(),
569 loweredFuncOp.end());
570 if (mlir::failed(rewriter.convertRegionTypes(
571 &loweredFuncOp.getBody(), *getTypeConverter(), &signatureConversion)))
572 return mlir::failure();
574 rewriter.eraseOp(op);
575 return mlir::success();
578mlir::LogicalResult CIRGlobalOpABILowering::matchAndRewrite(
579 cir::GlobalOp op, OpAdaptor adaptor,
580 mlir::ConversionPatternRewriter &rewriter)
const {
581 mlir::Type ty = op.getSymType();
582 mlir::Type loweredTy = getTypeConverter()->convertType(ty);
584 return mlir::failure();
586 mlir::DataLayout layout(op->getParentOfType<mlir::ModuleOp>());
589 lowerModule, layout, *getTypeConverter(), ty, op.getInitialValueAttr());
591 auto newOp = mlir::cast<cir::GlobalOp>(rewriter.clone(*op.getOperation()));
592 newOp.setInitialValueAttr(loweredInit);
593 newOp.setSymType(loweredTy);
594 rewriter.replaceOp(op, newOp);
595 return mlir::success();
598mlir::LogicalResult CIRBaseDataMemberOpABILowering::matchAndRewrite(
599 cir::BaseDataMemberOp op, OpAdaptor adaptor,
600 mlir::ConversionPatternRewriter &rewriter)
const {
601 mlir::Value loweredResult = lowerModule->getCXXABI().lowerBaseDataMember(
602 op, adaptor.getSrc(), rewriter);
603 rewriter.replaceOp(op, loweredResult);
604 return mlir::success();
607mlir::LogicalResult CIRBaseMethodOpABILowering::matchAndRewrite(
608 cir::BaseMethodOp op, OpAdaptor adaptor,
609 mlir::ConversionPatternRewriter &rewriter)
const {
610 mlir::Value loweredResult =
611 lowerModule->getCXXABI().lowerBaseMethod(op, adaptor.getSrc(), rewriter);
612 rewriter.replaceOp(op, loweredResult);
613 return mlir::success();
616mlir::LogicalResult CIRDeleteArrayOpABILowering::matchAndRewrite(
617 cir::DeleteArrayOp op, OpAdaptor adaptor,
618 mlir::ConversionPatternRewriter &rewriter)
const {
619 mlir::FlatSymbolRefAttr deleteFn = op.getDeleteFnAttr();
620 mlir::Location loc = op->getLoc();
621 mlir::Value loweredAddress = adaptor.getAddress();
623 cir::UsualDeleteParamsAttr deleteParams = op.getDeleteParams();
624 bool cookieRequired = deleteParams.getSize() || op.getElementDtorAttr();
626 if (deleteParams.getTypeAwareDelete() || deleteParams.getDestroyingDelete() ||
627 deleteParams.getAlignment())
628 return rewriter.notifyMatchFailure(
629 op,
"type-aware, destroying, or aligned delete not yet supported");
631 const CIRCXXABI &cxxABI = lowerModule->getCXXABI();
640 mlir::Value deletePtr;
641 mlir::Value numElements;
642 cir::PointerType ptrTy;
644 mlir::DataLayout dl(op->getParentOfType<mlir::ModuleOp>());
647 cir::IntType sizeTy = cirBuilder.getUIntNTy(ptrWidth);
649 if (cookieRequired) {
650 ptrTy = mlir::cast<cir::PointerType>(loweredAddress.getType());
651 cxxABI.
readArrayCookie(loc, loweredAddress, dl, cirBuilder, numElements,
652 deletePtr, cookieSize);
654 deletePtr = cir::CastOp::create(rewriter, loc, cirBuilder.getVoidPtrTy(),
655 cir::CastKind::bitcast, loweredAddress);
665 mlir::FlatSymbolRefAttr dtorFn = op.getElementDtorAttr();
666 cir::CleanupKind cleanupKind =
667 op.getDtorMayThrow() ? cir::CleanupKind::All : cir::CleanupKind::Normal;
668 cir::CleanupScopeOp::create(
669 rewriter, loc, cleanupKind,
671 [&](mlir::OpBuilder &b, mlir::Location l) {
673 auto eltPtrTy = cir::PointerType::get(ptrTy.getPointee());
674 auto arrayDtor = cir::ArrayDtor::create(
675 b, l, loweredAddress, numElements,
676 [&](mlir::OpBuilder &bb, mlir::Location ll) {
678 bb.getInsertionBlock()->addArgument(eltPtrTy, ll);
679 auto dtorCall = cir::CallOp::create(
680 bb, ll, dtorFn, cir::VoidType(), mlir::ValueRange{
arg});
681 if (!op.getDtorMayThrow())
682 dtorCall.setNothrowAttr(bb.getUnitAttr());
683 cir::YieldOp::create(bb, ll);
685 if (op.getDtorMayThrow())
686 arrayDtor.setDtorMayThrow(
true);
688 cir::YieldOp::create(b, l);
691 [&](mlir::OpBuilder &b, mlir::Location l) {
694 if (deleteParams.getSize()) {
695 uint64_t eltSizeBytes = dl.getTypeSizeInBits(ptrTy.getPointee()) / 8;
696 auto eltSizeVal = cir::ConstantOp::create(
697 b, l, cir::IntAttr::get(sizeTy, eltSizeBytes));
698 mlir::Value allocSize =
699 cir::MulOp::create(b, l, sizeTy, eltSizeVal, numElements);
700 auto cookieSizeVal = cir::ConstantOp::create(
701 b, l, cir::IntAttr::get(sizeTy, cookieSize.
getQuantity()));
703 cir::AddOp::create(b, l, sizeTy, allocSize, cookieSizeVal);
707 cir::CallOp::create(b, l, deleteFn, cir::VoidType(), callArgs);
710 deleteCall.setNothrowAttr(b.getUnitAttr());
711 cir::YieldOp::create(b, l);
714 rewriter.eraseOp(op);
715 return mlir::success();
718mlir::LogicalResult CIRDerivedDataMemberOpABILowering::matchAndRewrite(
719 cir::DerivedDataMemberOp op, OpAdaptor adaptor,
720 mlir::ConversionPatternRewriter &rewriter)
const {
721 mlir::Value loweredResult = lowerModule->getCXXABI().lowerDerivedDataMember(
722 op, adaptor.getSrc(), rewriter);
723 rewriter.replaceOp(op, loweredResult);
724 return mlir::success();
727mlir::LogicalResult CIRDerivedMethodOpABILowering::matchAndRewrite(
728 cir::DerivedMethodOp op, OpAdaptor adaptor,
729 mlir::ConversionPatternRewriter &rewriter)
const {
730 mlir::Value loweredResult = lowerModule->getCXXABI().lowerDerivedMethod(
731 op, adaptor.getSrc(), rewriter);
732 rewriter.replaceOp(op, loweredResult);
733 return mlir::success();
736mlir::LogicalResult CIRDynamicCastOpABILowering::matchAndRewrite(
737 cir::DynamicCastOp op, OpAdaptor adaptor,
738 mlir::ConversionPatternRewriter &rewriter)
const {
739 mlir::Value loweredResult =
740 lowerModule->getCXXABI().lowerDynamicCast(op, rewriter);
741 rewriter.replaceOp(op, loweredResult);
742 return mlir::success();
745mlir::LogicalResult CIRGetMethodOpABILowering::matchAndRewrite(
746 cir::GetMethodOp op, OpAdaptor adaptor,
747 mlir::ConversionPatternRewriter &rewriter)
const {
750 lowerModule->getCXXABI().lowerGetMethod(
751 op, callee, thisArg, adaptor.getMethod(), adaptor.getObject(), rewriter);
752 rewriter.replaceOp(op, {callee, thisArg});
753 return mlir::success();
756mlir::LogicalResult CIRGetRuntimeMemberOpABILowering::matchAndRewrite(
757 cir::GetRuntimeMemberOp op, OpAdaptor adaptor,
758 mlir::ConversionPatternRewriter &rewriter)
const {
759 mlir::Type resTy = getTypeConverter()->convertType(op.getType());
760 mlir::Operation *newOp = lowerModule->getCXXABI().lowerGetRuntimeMember(
761 op, resTy, adaptor.getAddr(), adaptor.getMember(), rewriter);
762 rewriter.replaceOp(op, newOp);
763 return mlir::success();
766mlir::LogicalResult CIRVTableGetTypeInfoOpABILowering::matchAndRewrite(
767 cir::VTableGetTypeInfoOp op, OpAdaptor adaptor,
768 mlir::ConversionPatternRewriter &rewriter)
const {
769 mlir::Value loweredResult =
770 lowerModule->getCXXABI().lowerVTableGetTypeInfo(op, rewriter);
771 rewriter.replaceOp(op, loweredResult);
772 return mlir::success();
780class CIRABITypeConverter :
public mlir::TypeConverter {
782 mlir::MLIRContext &context;
787 DenseMap<uint64_t, std::unique_ptr<SmallVector<cir::RecordType>>>
789 llvm::sys::SmartRWMutex<true> callStackMutex;
794 llvm::SmallVector<cir::RecordType> convertedRecordTypes;
795 llvm::sys::SmartRWMutex<true> recordTypeMutex;
801 SmallVector<cir::RecordType> &getCurrentThreadRecursiveStack() {
804 std::shared_lock<
decltype(callStackMutex)> lock(callStackMutex,
806 if (context.isMultithreadingEnabled())
808 auto recursiveStack = conversionCallStack.find(llvm::get_threadid());
809 if (recursiveStack != conversionCallStack.end())
810 return *recursiveStack->second;
815 std::unique_lock<
decltype(callStackMutex)> lock(callStackMutex);
816 auto recursiveStackInserted = conversionCallStack.insert(
817 std::make_pair(llvm::get_threadid(),
818 std::make_unique<SmallVector<cir::RecordType>>()));
819 return *recursiveStackInserted.first->second;
822 void addConvertedRecordType(cir::RecordType rt) {
823 std::unique_lock<
decltype(recordTypeMutex)> lock(recordTypeMutex);
824 convertedRecordTypes.push_back(rt);
827 llvm::SmallVector<mlir::Type> convertRecordMemberTypes(cir::RecordType type) {
828 llvm::SmallVector<mlir::Type> loweredMemberTypes;
829 loweredMemberTypes.reserve(
type.getNumElements());
831 if (mlir::failed(convertTypes(
type.getMembers(), loweredMemberTypes)))
834 return loweredMemberTypes;
837 cir::RecordType convertRecordType(cir::RecordType type) {
841 if (!
type.getName()) {
842 llvm::SmallVector<mlir::Type> converted = convertRecordMemberTypes(type);
843 if (
auto u = mlir::dyn_cast<cir::UnionType>(type)) {
844 mlir::Type loweredPadding;
845 if (mlir::Type pad = u.getPadding())
846 loweredPadding = convertType(pad);
847 return cir::UnionType::get(
type.getContext(), converted,
848 type.getPacked(), loweredPadding);
850 auto s = mlir::cast<cir::StructType>(type);
851 return cir::StructType::get(
type.getContext(), converted,
856 assert(!
type.isIncomplete() ||
type.getMembers().empty());
861 if (
type.isIncomplete() ||
type.isABIConvertedRecord())
864 SmallVectorImpl<cir::RecordType> &recursiveStack =
865 getCurrentThreadRecursiveStack();
867 cir::RecordType convertedType;
868 if (mlir::isa<cir::UnionType>(type))
870 cir::UnionType::get(
type.getContext(),
type.getABIConvertedName());
873 cir::StructType::get(
type.getContext(),
type.getABIConvertedName(),
874 mlir::cast<cir::StructType>(type).getIsClass());
878 return convertedType;
884 if (llvm::is_contained(recursiveStack, type))
885 return convertedType;
887 recursiveStack.push_back(type);
888 llvm::scope_exit popConvertingType(
889 [&recursiveStack]() { recursiveStack.pop_back(); });
891 SmallVector<mlir::Type> convertedMembers = convertRecordMemberTypes(type);
893 mlir::Type loweredPadding;
894 if (
auto u = mlir::dyn_cast<cir::UnionType>(type))
895 if (mlir::Type pad = u.getPadding())
896 loweredPadding = convertType(pad);
897 convertedType.
complete(convertedMembers,
type.getPacked(),
type.getPadded(),
899 addConvertedRecordType(convertedType);
900 return convertedType;
904 CIRABITypeConverter(mlir::MLIRContext &ctx, mlir::DataLayout &dataLayout,
905 cir::LowerModule &lowerModule)
907 addConversion([&](mlir::Type type) -> mlir::Type {
return type; });
910 addConversion([&](cir::PointerType type) -> mlir::Type {
911 mlir::Type loweredPointeeType = convertType(
type.getPointee());
912 if (!loweredPointeeType)
914 return cir::PointerType::get(
type.getContext(), loweredPointeeType,
915 type.getAddrSpace());
917 addConversion([&](cir::ArrayType type) -> mlir::Type {
918 mlir::Type loweredElementType = convertType(
type.getElementType());
919 if (!loweredElementType)
921 return cir::ArrayType::get(loweredElementType,
type.getSize());
924 addConversion([&](cir::DataMemberType type) -> mlir::Type {
927 return convertType(abiType);
929 addConversion([&](cir::MethodType type) -> mlir::Type {
931 return convertType(abiType);
936 addConversion([&](cir::FuncType type) -> mlir::Type {
937 llvm::SmallVector<mlir::Type> loweredInputTypes;
938 loweredInputTypes.reserve(
type.getNumInputs());
939 if (mlir::failed(convertTypes(
type.getInputs(), loweredInputTypes)))
942 mlir::Type loweredReturnType = convertType(
type.getReturnType());
943 if (!loweredReturnType)
946 return cir::FuncType::get(loweredInputTypes, loweredReturnType,
949 addConversion([&](cir::StructType type) -> mlir::Type {
950 return convertRecordType(type);
952 addConversion([&](cir::UnionType type) -> mlir::Type {
953 return convertRecordType(type);
957 void restoreRecordTypeNames() {
958 std::unique_lock<
decltype(recordTypeMutex)> lock(recordTypeMutex);
960 for (
auto rt : convertedRecordTypes)
968 const mlir::TypeConverter &typeConverter) {
969 target.addLegalOp<mlir::ModuleOp>();
974 target.addDynamicallyLegalDialect<cir::CIRDialect>(
975 [&typeConverter](mlir::Operation *op) {
976 if (!typeConverter.isLegal(op))
979 bool attrs = llvm::all_of(
980 op->getAttrs(), [&typeConverter](
const mlir::NamedAttribute &a) {
981 return isCXXABIAttributeLegal(typeConverter, a.getValue());
985 std::all_of(op->getRegions().begin(), op->getRegions().end(),
986 [&typeConverter](mlir::Region ®ion) {
987 return typeConverter.isLegal(®ion);
991 target.addDynamicallyLegalDialect<mlir::acc::OpenACCDialect>(
992 [&typeConverter](mlir::Operation *op) {
993 if (!typeConverter.isLegal(op))
996 bool attrs = llvm::all_of(
997 op->getAttrs(), [&typeConverter](
const mlir::NamedAttribute &a) {
998 return isCXXABIAttributeLegal(typeConverter, a.getValue());
1002 std::all_of(op->getRegions().begin(), op->getRegions().end(),
1003 [&typeConverter](mlir::Region ®ion) {
1004 return typeConverter.isLegal(®ion);
1009 target.addDynamicallyLegalOp<cir::FuncOp>([&typeConverter](cir::FuncOp op) {
1010 bool attrs = llvm::all_of(
1011 op->getAttrs(), [&typeConverter](
const mlir::NamedAttribute &a) {
1012 return isCXXABIAttributeLegal(typeConverter, a.getValue());
1015 return attrs && typeConverter.isLegal(op.getFunctionType());
1017 target.addDynamicallyLegalOp<cir::GlobalOp>(
1018 [&typeConverter](cir::GlobalOp op) {
1019 return typeConverter.isLegal(op.getSymType());
1023 target.addIllegalOp<cir::DeleteArrayOp>();
1024 target.addIllegalOp<cir::DynamicCastOp>();
1025 target.addIllegalOp<cir::VTableGetTypeInfoOp>();
1032void CXXABILoweringPass::runOnOperation() {
1033 auto mod = mlir::cast<mlir::ModuleOp>(getOperation());
1034 mlir::MLIRContext *ctx = mod.getContext();
1039 mod.emitWarning(
"Cannot create a CIR lower module, skipping the ")
1044 mlir::DataLayout dataLayout(mod);
1045 CIRABITypeConverter typeConverter(*ctx, dataLayout, *lowerModule);
1047 mlir::RewritePatternSet patterns(ctx);
1048 patterns.add<CIRGenericCXXABILoweringPattern>(patterns.getContext(),
1051#define GET_ABI_LOWERING_PATTERNS_LIST
1052#include "clang/CIR/Dialect/IR/CIRLowering.inc"
1053#undef GET_ABI_LOWERING_PATTERNS_LIST
1054 >(patterns.getContext(), typeConverter, dataLayout, *lowerModule);
1056 mlir::ConversionTarget target(*ctx);
1059 llvm::SmallVector<mlir::Operation *> ops;
1063 if (failed(mlir::applyPartialConversion(ops, target, std::move(patterns))))
1064 signalPassFailure();
1066 typeConverter.restoreRecordTypeNames();
1070 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)
virtual mlir::Type lowerMethodType(cir::MethodType type, const mlir::TypeConverter &typeConverter) const =0
Lower the given member function pointer type to its ABI type.
void readArrayCookie(mlir::Location loc, mlir::Value elementPtr, 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.
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 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.
CIRCXXABI & getCXXABI() const
void removeABIConversionNamePrefix()
void complete(llvm::ArrayRef< mlir::Type > members, bool packed, bool padded, mlir::Type padding={})
CharUnits - This is an opaque type for sizes expressed in character units.
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
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
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
StringRef getName(const HeaderType T)
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)