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::DataMemberOffsetAttr, cir::MethodAttr>(
74 return llvm::TypeSwitch<mlir::Attribute, bool>(
attr)
77 [&tc](cir::ZeroAttr za) {
return tc.isLegal(za.getType()); })
78 .Case<cir::PoisonAttr>(
79 [&tc](cir::PoisonAttr pa) {
return tc.isLegal(pa.getType()); })
80 .Case<cir::UndefAttr>(
81 [&tc](cir::UndefAttr uda) {
return tc.isLegal(uda.getType()); })
82 .Case<mlir::TypeAttr>(
83 [&tc](mlir::TypeAttr ta) {
return tc.isLegal(ta.getValue()); })
84 .Case<cir::ConstPtrAttr>(
85 [&tc](cir::ConstPtrAttr cpa) {
return tc.isLegal(cpa.getType()); })
86 .Case<cir::CXXCtorAttr>(
87 [&tc](cir::CXXCtorAttr ca) {
return tc.isLegal(ca.getType()); })
88 .Case<cir::CXXDtorAttr>(
89 [&tc](cir::CXXDtorAttr da) {
return tc.isLegal(da.getType()); })
90 .Case<cir::CXXAssignAttr>(
91 [&tc](cir::CXXAssignAttr aa) {
return tc.isLegal(aa.getType()); })
95 .Case<mlir::ArrayAttr>([&tc](mlir::ArrayAttr array) {
96 return llvm::all_of(array.getValue(), [&tc](mlir::Attribute
attr) {
97 return isCXXABIAttributeLegal(tc, attr);
100 .Case<mlir::DictionaryAttr>([&tc](mlir::DictionaryAttr dict) {
101 return llvm::all_of(dict.getValue(), [&tc](mlir::NamedAttribute na) {
102 return isCXXABIAttributeLegal(tc, na.getValue());
106 .Case<cir::ConstArrayAttr>([&tc](cir::ConstArrayAttr array) {
107 return tc.isLegal(array.getType()) &&
108 isCXXABIAttributeLegal(tc, array.getElts());
110 .Case<cir::GlobalViewAttr>([&tc](cir::GlobalViewAttr gva) {
111 return tc.isLegal(gva.getType()) &&
112 isCXXABIAttributeLegal(tc, gva.getIndices());
114 .Case<cir::VTableAttr>([&tc](cir::VTableAttr vta) {
115 return tc.isLegal(vta.getType()) &&
116 isCXXABIAttributeLegal(tc, vta.getData());
118 .Case<cir::TypeInfoAttr>([&tc](cir::TypeInfoAttr tia) {
119 return tc.isLegal(tia.getType()) &&
120 isCXXABIAttributeLegal(tc, tia.getData());
122 .Case<cir::DynamicCastInfoAttr>([&tc](cir::DynamicCastInfoAttr dcia) {
123 return isCXXABIAttributeLegal(tc, dcia.getSrcRtti()) &&
124 isCXXABIAttributeLegal(tc, dcia.getDestRtti()) &&
125 isCXXABIAttributeLegal(tc, dcia.getRuntimeFunc()) &&
126 isCXXABIAttributeLegal(tc, dcia.getBadCastFunc());
128 .Case<cir::ConstRecordAttr>([&tc](cir::ConstRecordAttr cra) {
129 return tc.isLegal(cra.getType()) &&
130 isCXXABIAttributeLegal(tc, cra.getMembers());
141mlir::Attribute rewriteAttribute(
const mlir::TypeConverter &tc,
142 mlir::MLIRContext *ctx, mlir::Attribute attr) {
145 if (isCXXABIAttributeLegal(tc, attr))
153 return llvm::TypeSwitch<mlir::Attribute, mlir::Attribute>(attr)
155 .Case<cir::ZeroAttr>([&tc](cir::ZeroAttr za) {
156 return cir::ZeroAttr::get(tc.convertType(za.getType()));
158 .Case<cir::PoisonAttr>([&tc](cir::PoisonAttr pa) {
159 return cir::PoisonAttr::get(tc.convertType(pa.getType()));
161 .Case<cir::UndefAttr>([&tc](cir::UndefAttr uda) {
162 return cir::UndefAttr::get(tc.convertType(uda.getType()));
164 .Case<mlir::TypeAttr>([&tc](mlir::TypeAttr ta) {
165 return mlir::TypeAttr::get(tc.convertType(ta.getValue()));
167 .Case<cir::ConstPtrAttr>([&tc](cir::ConstPtrAttr cpa) {
168 return cir::ConstPtrAttr::get(tc.convertType(cpa.getType()),
171 .Case<cir::CXXCtorAttr>([&tc](cir::CXXCtorAttr ca) {
172 return cir::CXXCtorAttr::get(tc.convertType(ca.getType()),
173 ca.getCtorKind(), ca.getIsTrivial());
175 .Case<cir::CXXDtorAttr>([&tc](cir::CXXDtorAttr da) {
176 return cir::CXXDtorAttr::get(tc.convertType(da.getType()),
179 .Case<cir::CXXAssignAttr>([&tc](cir::CXXAssignAttr aa) {
180 return cir::CXXAssignAttr::get(tc.convertType(aa.getType()),
181 aa.getAssignKind(), aa.getIsTrivial());
185 .Case<mlir::ArrayAttr>([&tc, ctx](mlir::ArrayAttr array) {
187 for (mlir::Attribute a : array.getValue())
188 elts.push_back(rewriteAttribute(tc, ctx, a));
189 return mlir::ArrayAttr::get(ctx, elts);
191 .Case<mlir::DictionaryAttr>([&tc, ctx](mlir::DictionaryAttr dict) {
193 for (mlir::NamedAttribute na : dict.getValue())
194 elts.emplace_back(na.getName(),
195 rewriteAttribute(tc, ctx, na.getValue()));
197 return mlir::DictionaryAttr::get(ctx, elts);
200 .Case<cir::ConstArrayAttr>([&tc, ctx](cir::ConstArrayAttr array) {
201 return cir::ConstArrayAttr::get(
202 ctx, tc.convertType(array.getType()),
203 rewriteAttribute(tc, ctx, array.getElts()),
204 array.getTrailingZerosNum());
206 .Case<cir::GlobalViewAttr>([&tc, ctx](cir::GlobalViewAttr gva) {
207 return cir::GlobalViewAttr::get(
208 tc.convertType(gva.getType()), gva.getSymbol(),
209 mlir::cast<mlir::ArrayAttr>(
210 rewriteAttribute(tc, ctx, gva.getIndices())));
212 .Case<cir::VTableAttr>([&tc, ctx](cir::VTableAttr vta) {
213 return cir::VTableAttr::get(
214 tc.convertType(vta.getType()),
215 mlir::cast<mlir::ArrayAttr>(
216 rewriteAttribute(tc, ctx, vta.getData())));
218 .Case<cir::TypeInfoAttr>([&tc, ctx](cir::TypeInfoAttr tia) {
219 return cir::TypeInfoAttr::get(
220 tc.convertType(tia.getType()),
221 mlir::cast<mlir::ArrayAttr>(
222 rewriteAttribute(tc, ctx, tia.getData())));
224 .Case<cir::DynamicCastInfoAttr>([&tc,
225 ctx](cir::DynamicCastInfoAttr dcia) {
226 return cir::DynamicCastInfoAttr::get(
227 mlir::cast<cir::GlobalViewAttr>(
228 rewriteAttribute(tc, ctx, dcia.getSrcRtti())),
229 mlir::cast<cir::GlobalViewAttr>(
230 rewriteAttribute(tc, ctx, dcia.getDestRtti())),
231 dcia.getRuntimeFunc(), dcia.getBadCastFunc(), dcia.getOffsetHint());
233 .Case<cir::ConstRecordAttr>([&tc, ctx](cir::ConstRecordAttr cra) {
234 return cir::ConstRecordAttr::get(
235 ctx, tc.convertType(cra.getType()),
236 mlir::cast<mlir::ArrayAttr>(
237 rewriteAttribute(tc, ctx, cra.getMembers())));
239 .DefaultUnreachable(
"unrewritten illegal attribute kind");
242#define GET_ABI_LOWERING_PATTERNS
243#include "clang/CIR/Dialect/IR/CIRLowering.inc"
244#undef GET_ABI_LOWERING_PATTERNS
246struct CXXABILoweringPass
247 :
public impl::CXXABILoweringBase<CXXABILoweringPass> {
248 CXXABILoweringPass() =
default;
249 void runOnOperation()
override;
257class CIRGenericCXXABILoweringPattern :
public mlir::ConversionPattern {
259 CIRGenericCXXABILoweringPattern(mlir::MLIRContext *context,
260 const mlir::TypeConverter &typeConverter)
261 : mlir::ConversionPattern(typeConverter, MatchAnyOpTypeTag(),
265 matchAndRewrite(mlir::Operation *op, llvm::ArrayRef<mlir::Value> operands,
266 mlir::ConversionPatternRewriter &rewriter)
const override {
268 if (llvm::isa<cir::AllocaOp, cir::BaseDataMemberOp, cir::BaseMethodOp,
269 cir::CastOp, cir::CmpOp, cir::ConstantOp, cir::DeleteArrayOp,
270 cir::DerivedDataMemberOp, cir::DerivedMethodOp, cir::FuncOp,
271 cir::GetMethodOp, cir::GetRuntimeMemberOp, cir::GlobalOp>(op))
272 return mlir::failure();
274 const mlir::TypeConverter *typeConverter = getTypeConverter();
275 assert(typeConverter &&
276 "CIRGenericCXXABILoweringPattern requires a type converter");
277 bool operandsAndResultsLegal = typeConverter->isLegal(op);
279 std::all_of(op->getRegions().begin(), op->getRegions().end(),
280 [typeConverter](mlir::Region ®ion) {
281 return typeConverter->isLegal(®ion);
284 llvm::all_of(op->getAttrs(), [typeConverter](mlir::NamedAttribute na) {
285 return isCXXABIAttributeLegal(*typeConverter, na.getValue());
288 if (operandsAndResultsLegal && regionsLegal && attrsLegal) {
291 return mlir::failure();
294 mlir::OperationState loweredOpState(op->getLoc(), op->getName());
295 loweredOpState.addOperands(operands);
296 loweredOpState.addSuccessors(op->getSuccessors());
299 llvm::SmallVector<mlir::NamedAttribute> attrs;
300 for (
const mlir::NamedAttribute &na : op->getAttrs())
303 rewriteAttribute(*typeConverter, op->getContext(), na.getValue())});
304 loweredOpState.addAttributes(attrs);
307 llvm::SmallVector<mlir::Type> loweredResultTypes;
308 loweredResultTypes.reserve(op->getNumResults());
309 for (mlir::Type result : op->getResultTypes())
310 loweredResultTypes.push_back(typeConverter->convertType(result));
311 loweredOpState.addTypes(loweredResultTypes);
314 for (mlir::Region ®ion : op->getRegions()) {
315 mlir::Region *loweredRegion = loweredOpState.addRegion();
316 rewriter.inlineRegionBefore(region, *loweredRegion, loweredRegion->end());
318 rewriter.convertRegionTypes(loweredRegion, *getTypeConverter())))
319 return mlir::failure();
323 mlir::Operation *loweredOp = rewriter.create(loweredOpState);
325 rewriter.replaceOp(op, loweredOp);
326 return mlir::success();
332mlir::LogicalResult CIRAllocaOpABILowering::matchAndRewrite(
333 cir::AllocaOp op, OpAdaptor adaptor,
334 mlir::ConversionPatternRewriter &rewriter)
const {
335 mlir::Type allocaPtrTy = op.getType();
336 mlir::Type loweredAllocaPtrTy = getTypeConverter()->convertType(allocaPtrTy);
338 cir::AllocaOp loweredOp = cir::AllocaOp::create(
339 rewriter, op.getLoc(), loweredAllocaPtrTy, op.getName(),
340 op.getAlignmentAttr(), adaptor.getDynAllocSize());
341 loweredOp.setInit(op.getInit());
342 loweredOp.setConstant(op.getConstant());
343 loweredOp.setAnnotationsAttr(op.getAnnotationsAttr());
345 rewriter.replaceOp(op, loweredOp);
346 return mlir::success();
349mlir::LogicalResult CIRCastOpABILowering::matchAndRewrite(
350 cir::CastOp op, OpAdaptor adaptor,
351 mlir::ConversionPatternRewriter &rewriter)
const {
352 mlir::Type srcTy = op.getSrc().getType();
354 if (mlir::isa<cir::DataMemberType, cir::MethodType>(srcTy)) {
355 switch (op.getKind()) {
356 case cir::CastKind::bitcast: {
357 mlir::Type destTy = getTypeConverter()->convertType(op.getType());
358 mlir::Value loweredResult;
359 if (mlir::isa<cir::DataMemberType>(srcTy))
360 loweredResult = lowerModule->getCXXABI().lowerDataMemberBitcast(
361 op, destTy, adaptor.getSrc(), rewriter);
363 loweredResult = lowerModule->getCXXABI().lowerMethodBitcast(
364 op, destTy, adaptor.getSrc(), rewriter);
365 rewriter.replaceOp(op, loweredResult);
366 return mlir::success();
368 case cir::CastKind::member_ptr_to_bool: {
369 mlir::Value loweredResult;
370 if (mlir::isa<cir::DataMemberType>(srcTy))
371 loweredResult = lowerModule->getCXXABI().lowerDataMemberToBoolCast(
372 op, adaptor.getSrc(), rewriter);
374 loweredResult = lowerModule->getCXXABI().lowerMethodToBoolCast(
375 op, adaptor.getSrc(), rewriter);
376 rewriter.replaceOp(op, loweredResult);
377 return mlir::success();
384 mlir::Value loweredResult = cir::CastOp::create(
385 rewriter, op.getLoc(), getTypeConverter()->convertType(op.getType()),
386 adaptor.getKind(), adaptor.getSrc());
387 rewriter.replaceOp(op, loweredResult);
388 return mlir::success();
393 const mlir::DataLayout &layout,
394 const mlir::TypeConverter &tc,
396 mlir::Attribute initVal) {
397 if (mlir::isa<cir::DataMemberType>(ty)) {
401 mlir::dyn_cast_if_present<cir::DataMemberOffsetAttr>(initVal))
404 auto dataMemberVal = mlir::cast_if_present<cir::DataMemberAttr>(initVal);
408 if (mlir::isa<cir::MethodType>(ty)) {
409 auto methodVal = mlir::cast_if_present<cir::MethodAttr>(initVal);
413 if (
auto arrTy = mlir::dyn_cast<cir::ArrayType>(ty)) {
414 auto loweredArrTy = mlir::cast<cir::ArrayType>(tc.convertType(arrTy));
419 if (
auto zeroVal = mlir::dyn_cast_if_present<cir::ZeroAttr>(initVal))
420 return cir::ZeroAttr::get(loweredArrTy);
422 auto arrayVal = mlir::cast<cir::ConstArrayAttr>(initVal);
428 if (mlir::isa<mlir::StringAttr>(arrayVal.getElts())) {
429 assert(loweredArrTy == arrTy &&
430 "string-literal array type should not change under CXX ABI");
434 auto arrayElts = mlir::cast<ArrayAttr>(arrayVal.getElts());
436 loweredElements.reserve(arrTy.getSize());
437 for (
const mlir::Attribute &attr : arrayElts) {
438 auto typedAttr = cast<mlir::TypedAttr>(attr);
440 lowerModule, layout, tc, typedAttr.getType(), typedAttr));
443 return cir::ConstArrayAttr::get(
444 loweredArrTy, mlir::ArrayAttr::get(ty.getContext(), loweredElements),
445 arrayVal.getTrailingZerosNum());
448 if (
auto recordTy = mlir::dyn_cast<cir::RecordType>(ty)) {
450 mlir::dyn_cast<cir::RecordType>(tc.convertType(recordTy));
454 if (
auto recVal = mlir::dyn_cast_if_present<cir::ZeroAttr>(initVal))
455 return cir::ZeroAttr::get(convertedTy);
457 if (
auto undefVal = mlir::dyn_cast_if_present<cir::UndefAttr>(initVal))
458 return cir::UndefAttr::get(convertedTy);
462 if (
auto poisonVal = mlir::dyn_cast_if_present<cir::PoisonAttr>(initVal))
463 return cir::PoisonAttr::get(convertedTy);
466 mlir::dyn_cast_if_present<cir::ConstRecordAttr>(initVal)) {
467 auto recordMembers = mlir::cast<ArrayAttr>(recVal.getMembers());
470 loweredMembers.reserve(recordMembers.size());
472 for (
const mlir::Attribute &attr : recordMembers) {
473 auto typedAttr = cast<mlir::TypedAttr>(attr);
475 lowerModule, layout, tc, typedAttr.getType(), typedAttr));
478 return cir::ConstRecordAttr::get(
479 convertedTy, mlir::ArrayAttr::get(ty.getContext(), loweredMembers));
482 assert(!initVal &&
"Record init val type not handled");
487 if (
auto ptrTy = mlir::dyn_cast<cir::PointerType>(ty)) {
488 auto convertedTy = mlir::cast<cir::PointerType>(tc.convertType(ptrTy));
491 if (
auto gva = mlir::dyn_cast_if_present<cir::GlobalViewAttr>(initVal))
492 return cir::GlobalViewAttr::get(convertedTy, gva.getSymbol(),
496 mlir::dyn_cast_if_present<cir::BlockAddrInfoAttr>(initVal)) {
497 assert(convertedTy == ptrTy &&
"BlockAddrInfo type should not change");
501 auto constPtr = mlir::cast_if_present<cir::ConstPtrAttr>(initVal);
504 return cir::ConstPtrAttr::get(convertedTy, constPtr.getValue());
507 assert(ty == tc.convertType(ty) &&
508 "cir.global or constant operand is not an CXXABI-dependent type");
511 return cast<mlir::TypedAttr>(initVal);
514mlir::LogicalResult CIRConstantOpABILowering::matchAndRewrite(
515 cir::ConstantOp op, OpAdaptor adaptor,
516 mlir::ConversionPatternRewriter &rewriter)
const {
518 mlir::DataLayout layout(op->getParentOfType<mlir::ModuleOp>());
520 lowerModule, layout, *getTypeConverter(), op.getType(), op.getValue());
521 rewriter.replaceOpWithNewOp<ConstantOp>(op, newValue);
522 return mlir::success();
525mlir::LogicalResult CIRCmpOpABILowering::matchAndRewrite(
526 cir::CmpOp op, OpAdaptor adaptor,
527 mlir::ConversionPatternRewriter &rewriter)
const {
528 mlir::Type type = op.getLhs().getType();
530 mlir::Value loweredResult;
531 if (mlir::isa<cir::DataMemberType>(type))
532 loweredResult = lowerModule->getCXXABI().lowerDataMemberCmp(
533 op, adaptor.getLhs(), adaptor.getRhs(), rewriter);
534 else if (mlir::isa<cir::MethodType>(type))
535 loweredResult = lowerModule->getCXXABI().lowerMethodCmp(
536 op, adaptor.getLhs(), adaptor.getRhs(), rewriter);
538 loweredResult = cir::CmpOp::create(
539 rewriter, op.getLoc(), getTypeConverter()->convertType(op.getType()),
540 adaptor.getKind(), adaptor.getLhs(), adaptor.getRhs());
542 rewriter.replaceOp(op, loweredResult);
543 return mlir::success();
546mlir::LogicalResult CIRFuncOpABILowering::matchAndRewrite(
547 cir::FuncOp op, OpAdaptor adaptor,
548 mlir::ConversionPatternRewriter &rewriter)
const {
549 cir::FuncType opFuncType = op.getFunctionType();
550 mlir::TypeConverter::SignatureConversion signatureConversion(
551 opFuncType.getNumInputs());
553 for (
const auto &[i, argType] : llvm::enumerate(opFuncType.getInputs())) {
554 mlir::Type loweredArgType = getTypeConverter()->convertType(argType);
556 return mlir::failure();
557 signatureConversion.addInputs(i, loweredArgType);
560 mlir::Type loweredResultType =
561 getTypeConverter()->convertType(opFuncType.getReturnType());
562 if (!loweredResultType)
563 return mlir::failure();
565 auto loweredFuncType =
566 cir::FuncType::get(signatureConversion.getConvertedTypes(),
567 loweredResultType, opFuncType.isVarArg());
570 cir::FuncOp loweredFuncOp = rewriter.cloneWithoutRegions(op);
571 loweredFuncOp.setFunctionType(loweredFuncType);
574 for (
const mlir::NamedAttribute &na : op->getAttrs())
576 {na.getName(), rewriteAttribute(*getTypeConverter(), op->getContext(),
579 loweredFuncOp->setAttrs(attrs);
581 rewriter.inlineRegionBefore(op.getBody(), loweredFuncOp.getBody(),
582 loweredFuncOp.end());
583 if (mlir::failed(rewriter.convertRegionTypes(
584 &loweredFuncOp.getBody(), *getTypeConverter(), &signatureConversion)))
585 return mlir::failure();
587 rewriter.eraseOp(op);
588 return mlir::success();
591mlir::LogicalResult CIRGlobalOpABILowering::matchAndRewrite(
592 cir::GlobalOp op, OpAdaptor adaptor,
593 mlir::ConversionPatternRewriter &rewriter)
const {
594 mlir::Type ty = op.getSymType();
595 mlir::Type loweredTy = getTypeConverter()->convertType(ty);
597 return mlir::failure();
599 mlir::DataLayout layout(op->getParentOfType<mlir::ModuleOp>());
602 lowerModule, layout, *getTypeConverter(), ty, op.getInitialValueAttr());
604 auto newOp = mlir::cast<cir::GlobalOp>(rewriter.clone(*op.getOperation()));
605 newOp.setInitialValueAttr(loweredInit);
606 newOp.setSymType(loweredTy);
607 rewriter.replaceOp(op, newOp);
608 return mlir::success();
611mlir::LogicalResult CIRBaseDataMemberOpABILowering::matchAndRewrite(
612 cir::BaseDataMemberOp op, OpAdaptor adaptor,
613 mlir::ConversionPatternRewriter &rewriter)
const {
614 mlir::Value loweredResult = lowerModule->getCXXABI().lowerBaseDataMember(
615 op, adaptor.getSrc(), rewriter);
616 rewriter.replaceOp(op, loweredResult);
617 return mlir::success();
620mlir::LogicalResult CIRBaseMethodOpABILowering::matchAndRewrite(
621 cir::BaseMethodOp op, OpAdaptor adaptor,
622 mlir::ConversionPatternRewriter &rewriter)
const {
623 mlir::Value loweredResult =
624 lowerModule->getCXXABI().lowerBaseMethod(op, adaptor.getSrc(), rewriter);
625 rewriter.replaceOp(op, loweredResult);
626 return mlir::success();
629mlir::LogicalResult CIRDeleteArrayOpABILowering::matchAndRewrite(
630 cir::DeleteArrayOp op, OpAdaptor adaptor,
631 mlir::ConversionPatternRewriter &rewriter)
const {
632 mlir::FlatSymbolRefAttr deleteFn = op.getDeleteFnAttr();
633 mlir::Location loc = op->getLoc();
634 mlir::Value loweredAddress = adaptor.getAddress();
636 cir::UsualDeleteParamsAttr deleteParams = op.getDeleteParams();
637 bool cookieRequired = deleteParams.getSize() || op.getElementDtorAttr();
639 if (deleteParams.getTypeAwareDelete() || deleteParams.getDestroyingDelete() ||
640 deleteParams.getAlignment())
641 return rewriter.notifyMatchFailure(
642 op,
"type-aware, destroying, or aligned delete not yet supported");
644 const CIRCXXABI &cxxABI = lowerModule->getCXXABI();
653 mlir::Value deletePtr;
654 mlir::Value numElements;
655 cir::PointerType ptrTy;
657 mlir::DataLayout dl(op->getParentOfType<mlir::ModuleOp>());
660 cir::IntType sizeTy = cirBuilder.getUIntNTy(ptrWidth);
662 if (cookieRequired) {
663 ptrTy = mlir::cast<cir::PointerType>(loweredAddress.getType());
664 cxxABI.
readArrayCookie(loc, loweredAddress, dl, cirBuilder, numElements,
665 deletePtr, cookieSize);
667 deletePtr = cir::CastOp::create(rewriter, loc, cirBuilder.getVoidPtrTy(),
668 cir::CastKind::bitcast, loweredAddress);
678 mlir::FlatSymbolRefAttr dtorFn = op.getElementDtorAttr();
679 cir::CleanupKind cleanupKind =
680 op.getDtorMayThrow() ? cir::CleanupKind::All : cir::CleanupKind::Normal;
681 cir::CleanupScopeOp::create(
682 rewriter, loc, cleanupKind,
684 [&](mlir::OpBuilder &b, mlir::Location l) {
686 auto eltPtrTy = cir::PointerType::get(ptrTy.getPointee());
687 auto arrayDtor = cir::ArrayDtor::create(
688 b, l, loweredAddress, numElements,
689 [&](mlir::OpBuilder &bb, mlir::Location ll) {
691 bb.getInsertionBlock()->addArgument(eltPtrTy, ll);
692 auto dtorCall = cir::CallOp::create(
693 bb, ll, dtorFn, cir::VoidType(), mlir::ValueRange{
arg});
694 if (!op.getDtorMayThrow())
695 dtorCall.setNothrowAttr(bb.getUnitAttr());
696 cir::YieldOp::create(bb, ll);
698 if (op.getDtorMayThrow())
699 arrayDtor.setDtorMayThrow(
true);
701 cir::YieldOp::create(b, l);
704 [&](mlir::OpBuilder &b, mlir::Location l) {
707 if (deleteParams.getSize()) {
708 uint64_t eltSizeBytes = dl.getTypeSizeInBits(ptrTy.getPointee()) / 8;
709 auto eltSizeVal = cir::ConstantOp::create(
710 b, l, cir::IntAttr::get(sizeTy, eltSizeBytes));
711 mlir::Value allocSize =
712 cir::MulOp::create(b, l, sizeTy, eltSizeVal, numElements);
713 auto cookieSizeVal = cir::ConstantOp::create(
714 b, l, cir::IntAttr::get(sizeTy, cookieSize.
getQuantity()));
716 cir::AddOp::create(b, l, sizeTy, allocSize, cookieSizeVal);
720 cir::CallOp::create(b, l, deleteFn, cir::VoidType(), callArgs);
723 deleteCall.setNothrowAttr(b.getUnitAttr());
724 cir::YieldOp::create(b, l);
727 rewriter.eraseOp(op);
728 return mlir::success();
731mlir::LogicalResult CIRDerivedDataMemberOpABILowering::matchAndRewrite(
732 cir::DerivedDataMemberOp op, OpAdaptor adaptor,
733 mlir::ConversionPatternRewriter &rewriter)
const {
734 mlir::Value loweredResult = lowerModule->getCXXABI().lowerDerivedDataMember(
735 op, adaptor.getSrc(), rewriter);
736 rewriter.replaceOp(op, loweredResult);
737 return mlir::success();
740mlir::LogicalResult CIRDerivedMethodOpABILowering::matchAndRewrite(
741 cir::DerivedMethodOp op, OpAdaptor adaptor,
742 mlir::ConversionPatternRewriter &rewriter)
const {
743 mlir::Value loweredResult = lowerModule->getCXXABI().lowerDerivedMethod(
744 op, adaptor.getSrc(), rewriter);
745 rewriter.replaceOp(op, loweredResult);
746 return mlir::success();
749mlir::LogicalResult CIRDynamicCastOpABILowering::matchAndRewrite(
750 cir::DynamicCastOp op, OpAdaptor adaptor,
751 mlir::ConversionPatternRewriter &rewriter)
const {
752 mlir::Value loweredResult =
753 lowerModule->getCXXABI().lowerDynamicCast(op, rewriter);
754 rewriter.replaceOp(op, loweredResult);
755 return mlir::success();
758mlir::LogicalResult CIRGetMethodOpABILowering::matchAndRewrite(
759 cir::GetMethodOp op, OpAdaptor adaptor,
760 mlir::ConversionPatternRewriter &rewriter)
const {
763 lowerModule->getCXXABI().lowerGetMethod(
764 op, callee, thisArg, adaptor.getMethod(), adaptor.getObject(), rewriter);
765 rewriter.replaceOp(op, {callee, thisArg});
766 return mlir::success();
769mlir::LogicalResult CIRGetRuntimeMemberOpABILowering::matchAndRewrite(
770 cir::GetRuntimeMemberOp op, OpAdaptor adaptor,
771 mlir::ConversionPatternRewriter &rewriter)
const {
772 mlir::Type resTy = getTypeConverter()->convertType(op.getType());
773 mlir::Operation *newOp = lowerModule->getCXXABI().lowerGetRuntimeMember(
774 op, resTy, adaptor.getAddr(), adaptor.getMember(), rewriter);
775 rewriter.replaceOp(op, newOp);
776 return mlir::success();
779mlir::LogicalResult CIRVTableGetTypeInfoOpABILowering::matchAndRewrite(
780 cir::VTableGetTypeInfoOp op, OpAdaptor adaptor,
781 mlir::ConversionPatternRewriter &rewriter)
const {
782 mlir::Value loweredResult =
783 lowerModule->getCXXABI().lowerVTableGetTypeInfo(op, rewriter);
784 rewriter.replaceOp(op, loweredResult);
785 return mlir::success();
793class CIRABITypeConverter :
public mlir::TypeConverter {
795 mlir::MLIRContext &context;
800 DenseMap<uint64_t, std::unique_ptr<SmallVector<cir::RecordType>>>
802 llvm::sys::SmartRWMutex<true> callStackMutex;
807 llvm::SmallVector<cir::RecordType> convertedRecordTypes;
808 llvm::sys::SmartRWMutex<true> recordTypeMutex;
814 SmallVector<cir::RecordType> &getCurrentThreadRecursiveStack() {
817 std::shared_lock<
decltype(callStackMutex)> lock(callStackMutex,
819 if (context.isMultithreadingEnabled())
821 auto recursiveStack = conversionCallStack.find(llvm::get_threadid());
822 if (recursiveStack != conversionCallStack.end())
823 return *recursiveStack->second;
828 std::unique_lock<
decltype(callStackMutex)> lock(callStackMutex);
829 auto recursiveStackInserted = conversionCallStack.insert(
830 std::make_pair(llvm::get_threadid(),
831 std::make_unique<SmallVector<cir::RecordType>>()));
832 return *recursiveStackInserted.first->second;
835 void addConvertedRecordType(cir::RecordType rt) {
836 std::unique_lock<
decltype(recordTypeMutex)> lock(recordTypeMutex);
837 convertedRecordTypes.push_back(rt);
840 llvm::SmallVector<mlir::Type> convertRecordMemberTypes(cir::RecordType type) {
841 llvm::SmallVector<mlir::Type> loweredMemberTypes;
842 loweredMemberTypes.reserve(
type.getNumElements());
844 if (mlir::failed(convertTypes(
type.getMembers(), loweredMemberTypes)))
847 return loweredMemberTypes;
850 cir::RecordType convertRecordType(cir::RecordType type) {
854 if (!
type.getName()) {
855 llvm::SmallVector<mlir::Type> converted = convertRecordMemberTypes(type);
856 if (
auto u = mlir::dyn_cast<cir::UnionType>(type)) {
857 mlir::Type loweredPadding;
858 if (mlir::Type pad = u.getPadding())
859 loweredPadding = convertType(pad);
860 return cir::UnionType::get(
type.getContext(), converted,
861 type.getPacked(), loweredPadding);
863 auto s = mlir::cast<cir::StructType>(type);
864 return cir::StructType::get(
type.getContext(), converted,
869 assert(!
type.isIncomplete() ||
type.getMembers().empty());
874 if (
type.isIncomplete() ||
type.isABIConvertedRecord())
877 SmallVectorImpl<cir::RecordType> &recursiveStack =
878 getCurrentThreadRecursiveStack();
880 cir::RecordType convertedType;
881 if (mlir::isa<cir::UnionType>(type))
883 cir::UnionType::get(
type.getContext(),
type.getABIConvertedName());
886 cir::StructType::get(
type.getContext(),
type.getABIConvertedName(),
887 mlir::cast<cir::StructType>(type).getIsClass());
891 return convertedType;
897 if (llvm::is_contained(recursiveStack, type))
898 return convertedType;
900 recursiveStack.push_back(type);
901 llvm::scope_exit popConvertingType(
902 [&recursiveStack]() { recursiveStack.pop_back(); });
904 SmallVector<mlir::Type> convertedMembers = convertRecordMemberTypes(type);
906 mlir::Type loweredPadding;
907 if (
auto u = mlir::dyn_cast<cir::UnionType>(type))
908 if (mlir::Type pad = u.getPadding())
909 loweredPadding = convertType(pad);
910 convertedType.
complete(convertedMembers,
type.getPacked(),
type.getPadded(),
912 addConvertedRecordType(convertedType);
913 return convertedType;
917 CIRABITypeConverter(mlir::MLIRContext &ctx, mlir::DataLayout &dataLayout,
918 cir::LowerModule &lowerModule)
920 addConversion([&](mlir::Type type) -> mlir::Type {
return type; });
923 addConversion([&](cir::PointerType type) -> mlir::Type {
924 mlir::Type loweredPointeeType = convertType(
type.getPointee());
925 if (!loweredPointeeType)
927 return cir::PointerType::get(
type.getContext(), loweredPointeeType,
928 type.getAddrSpace());
930 addConversion([&](cir::ArrayType type) -> mlir::Type {
931 mlir::Type loweredElementType = convertType(
type.getElementType());
932 if (!loweredElementType)
934 return cir::ArrayType::get(loweredElementType,
type.getSize());
937 addConversion([&](cir::DataMemberType type) -> mlir::Type {
940 return convertType(abiType);
942 addConversion([&](cir::MethodType type) -> mlir::Type {
944 return convertType(abiType);
949 addConversion([&](cir::FuncType type) -> mlir::Type {
950 llvm::SmallVector<mlir::Type> loweredInputTypes;
951 loweredInputTypes.reserve(
type.getNumInputs());
952 if (mlir::failed(convertTypes(
type.getInputs(), loweredInputTypes)))
955 mlir::Type loweredReturnType = convertType(
type.getReturnType());
956 if (!loweredReturnType)
959 return cir::FuncType::get(loweredInputTypes, loweredReturnType,
962 addConversion([&](cir::StructType type) -> mlir::Type {
963 return convertRecordType(type);
965 addConversion([&](cir::UnionType type) -> mlir::Type {
966 return convertRecordType(type);
970 void restoreRecordTypeNames() {
971 std::unique_lock<
decltype(recordTypeMutex)> lock(recordTypeMutex);
973 for (
auto rt : convertedRecordTypes)
981 const mlir::TypeConverter &typeConverter) {
982 target.addLegalOp<mlir::ModuleOp>();
987 target.addDynamicallyLegalDialect<cir::CIRDialect>(
988 [&typeConverter](mlir::Operation *op) {
989 if (!typeConverter.isLegal(op))
992 bool attrs = llvm::all_of(
993 op->getAttrs(), [&typeConverter](
const mlir::NamedAttribute &a) {
994 return isCXXABIAttributeLegal(typeConverter, a.getValue());
998 std::all_of(op->getRegions().begin(), op->getRegions().end(),
999 [&typeConverter](mlir::Region ®ion) {
1000 return typeConverter.isLegal(®ion);
1004 target.addDynamicallyLegalDialect<mlir::acc::OpenACCDialect>(
1005 [&typeConverter](mlir::Operation *op) {
1006 if (!typeConverter.isLegal(op))
1009 bool attrs = llvm::all_of(
1010 op->getAttrs(), [&typeConverter](
const mlir::NamedAttribute &a) {
1011 return isCXXABIAttributeLegal(typeConverter, a.getValue());
1015 std::all_of(op->getRegions().begin(), op->getRegions().end(),
1016 [&typeConverter](mlir::Region ®ion) {
1017 return typeConverter.isLegal(®ion);
1022 target.addDynamicallyLegalOp<cir::FuncOp>([&typeConverter](cir::FuncOp op) {
1023 bool attrs = llvm::all_of(
1024 op->getAttrs(), [&typeConverter](
const mlir::NamedAttribute &a) {
1025 return isCXXABIAttributeLegal(typeConverter, a.getValue());
1028 return attrs && typeConverter.isLegal(op.getFunctionType());
1030 target.addDynamicallyLegalOp<cir::GlobalOp>(
1031 [&typeConverter](cir::GlobalOp op) {
1032 return typeConverter.isLegal(op.getSymType());
1036 target.addIllegalOp<cir::DeleteArrayOp>();
1037 target.addIllegalOp<cir::DynamicCastOp>();
1038 target.addIllegalOp<cir::VTableGetTypeInfoOp>();
1045void CXXABILoweringPass::runOnOperation() {
1046 auto mod = mlir::cast<mlir::ModuleOp>(getOperation());
1047 mlir::MLIRContext *ctx = mod.getContext();
1052 mod.emitWarning(
"Cannot create a CIR lower module, skipping the ")
1057 mlir::DataLayout dataLayout(mod);
1058 CIRABITypeConverter typeConverter(*ctx, dataLayout, *lowerModule);
1060 mlir::RewritePatternSet patterns(ctx);
1061 patterns.add<CIRGenericCXXABILoweringPattern>(patterns.getContext(),
1064#define GET_ABI_LOWERING_PATTERNS_LIST
1065#include "clang/CIR/Dialect/IR/CIRLowering.inc"
1066#undef GET_ABI_LOWERING_PATTERNS_LIST
1067 >(patterns.getContext(), typeConverter, dataLayout, *lowerModule);
1069 mlir::ConversionTarget target(*ctx);
1072 llvm::SmallVector<mlir::Operation *> ops;
1076 if (failed(mlir::applyPartialConversion(ops, target, std::move(patterns))))
1077 signalPassFailure();
1079 typeConverter.restoreRecordTypeNames();
1083 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 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.
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)