14#include "mlir/Dialect/OpenACC/OpenACCOpsDialect.h.inc"
15#include "mlir/Dialect/OpenMP/OpenMPOpsDialect.h.inc"
16#include "mlir/IR/PatternMatch.h"
17#include "mlir/Interfaces/DataLayoutInterfaces.h"
18#include "mlir/Pass/Pass.h"
19#include "mlir/Transforms/DialectConversion.h"
28#include "llvm/ADT/ScopeExit.h"
29#include "llvm/ADT/TypeSwitch.h"
35#define GEN_PASS_DEF_CXXABILOWERING
36#include "clang/CIR/Dialect/Passes.h.inc"
43bool isCXXABIAttributeLegal(
const mlir::TypeConverter &tc,
44 mlir::Attribute
attr) {
51 if (isa<mlir::acc::OpenACCDialect, mlir::omp::OpenMPDialect>(
57 if (
isa<mlir::DenseArrayAttr, mlir::FloatAttr, mlir::UnitAttr,
58 mlir::StringAttr, mlir::IntegerAttr, mlir::SymbolRefAttr,
59 cir::AnnotationAttr>(
attr))
65#include
"clang/CIR/Dialect/IR/CIRLowering.inc"
71 if (isa<cir::DataMemberAttr, cir::MethodAttr>(
attr))
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 allocaTy = op.getAllocaType();
337 mlir::Type loweredAllocaPtrTy = getTypeConverter()->convertType(allocaPtrTy);
338 mlir::Type loweredAllocaTy = getTypeConverter()->convertType(allocaTy);
340 cir::AllocaOp loweredOp = cir::AllocaOp::create(
341 rewriter, op.getLoc(), loweredAllocaPtrTy, loweredAllocaTy, op.getName(),
342 op.getAlignmentAttr(), adaptor.getDynAllocSize());
343 loweredOp.setInit(op.getInit());
344 loweredOp.setConstant(op.getConstant());
345 loweredOp.setAnnotationsAttr(op.getAnnotationsAttr());
347 rewriter.replaceOp(op, loweredOp);
348 return mlir::success();
351mlir::LogicalResult CIRCastOpABILowering::matchAndRewrite(
352 cir::CastOp op, OpAdaptor adaptor,
353 mlir::ConversionPatternRewriter &rewriter)
const {
354 mlir::Type srcTy = op.getSrc().getType();
356 if (mlir::isa<cir::DataMemberType, cir::MethodType>(srcTy)) {
357 switch (op.getKind()) {
358 case cir::CastKind::bitcast: {
359 mlir::Type destTy = getTypeConverter()->convertType(op.getType());
360 mlir::Value loweredResult;
361 if (mlir::isa<cir::DataMemberType>(srcTy))
362 loweredResult = lowerModule->getCXXABI().lowerDataMemberBitcast(
363 op, destTy, adaptor.getSrc(), rewriter);
365 loweredResult = lowerModule->getCXXABI().lowerMethodBitcast(
366 op, destTy, adaptor.getSrc(), rewriter);
367 rewriter.replaceOp(op, loweredResult);
368 return mlir::success();
370 case cir::CastKind::member_ptr_to_bool: {
371 mlir::Value loweredResult;
372 if (mlir::isa<cir::DataMemberType>(srcTy))
373 loweredResult = lowerModule->getCXXABI().lowerDataMemberToBoolCast(
374 op, adaptor.getSrc(), rewriter);
376 loweredResult = lowerModule->getCXXABI().lowerMethodToBoolCast(
377 op, adaptor.getSrc(), rewriter);
378 rewriter.replaceOp(op, loweredResult);
379 return mlir::success();
386 mlir::Value loweredResult = cir::CastOp::create(
387 rewriter, op.getLoc(), getTypeConverter()->convertType(op.getType()),
388 adaptor.getKind(), adaptor.getSrc());
389 rewriter.replaceOp(op, loweredResult);
390 return mlir::success();
395 const mlir::DataLayout &layout,
396 const mlir::TypeConverter &tc,
398 mlir::Attribute initVal) {
399 if (mlir::isa<cir::DataMemberType>(ty)) {
400 auto dataMemberVal = mlir::cast_if_present<cir::DataMemberAttr>(initVal);
404 if (mlir::isa<cir::MethodType>(ty)) {
405 auto methodVal = mlir::cast_if_present<cir::MethodAttr>(initVal);
409 if (
auto arrTy = mlir::dyn_cast<cir::ArrayType>(ty)) {
410 auto loweredArrTy = mlir::cast<cir::ArrayType>(tc.convertType(arrTy));
415 if (
auto zeroVal = mlir::dyn_cast_if_present<cir::ZeroAttr>(initVal))
416 return cir::ZeroAttr::get(loweredArrTy);
418 auto arrayVal = mlir::cast<cir::ConstArrayAttr>(initVal);
424 if (mlir::isa<mlir::StringAttr>(arrayVal.getElts())) {
425 assert(loweredArrTy == arrTy &&
426 "string-literal array type should not change under CXX ABI");
430 auto arrayElts = mlir::cast<ArrayAttr>(arrayVal.getElts());
432 loweredElements.reserve(arrTy.getSize());
433 for (
const mlir::Attribute &attr : arrayElts) {
434 auto typedAttr = cast<mlir::TypedAttr>(attr);
436 lowerModule, layout, tc, typedAttr.getType(), typedAttr));
439 return cir::ConstArrayAttr::get(
440 loweredArrTy, mlir::ArrayAttr::get(ty.getContext(), loweredElements),
441 arrayVal.getTrailingZerosNum());
444 if (
auto recordTy = mlir::dyn_cast<cir::RecordType>(ty)) {
445 auto convertedTy = mlir::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) {
842 return cir::RecordType::get(
843 type.getContext(), convertRecordMemberTypes(type),
type.getPacked(),
846 assert(!
type.isIncomplete() ||
type.getMembers().empty());
851 if (
type.isIncomplete() ||
type.isABIConvertedRecord())
854 SmallVectorImpl<cir::RecordType> &recursiveStack =
855 getCurrentThreadRecursiveStack();
857 auto convertedType = cir::RecordType::get(
858 type.getContext(),
type.getABIConvertedName(),
type.getKind());
861 if (convertedType.isComplete())
862 return convertedType;
868 if (llvm::is_contained(recursiveStack, type))
869 return convertedType;
871 recursiveStack.push_back(type);
872 llvm::scope_exit popConvertingType(
873 [&recursiveStack]() { recursiveStack.pop_back(); });
875 SmallVector<mlir::Type> convertedMembers = convertRecordMemberTypes(type);
877 convertedType.complete(convertedMembers,
type.getPacked(),
879 addConvertedRecordType(convertedType);
880 return convertedType;
884 CIRABITypeConverter(mlir::MLIRContext &ctx, mlir::DataLayout &dataLayout,
885 cir::LowerModule &lowerModule)
887 addConversion([&](mlir::Type type) -> mlir::Type {
return type; });
890 addConversion([&](cir::PointerType type) -> mlir::Type {
891 mlir::Type loweredPointeeType = convertType(
type.getPointee());
892 if (!loweredPointeeType)
894 return cir::PointerType::get(
type.getContext(), loweredPointeeType,
895 type.getAddrSpace());
897 addConversion([&](cir::ArrayType type) -> mlir::Type {
898 mlir::Type loweredElementType = convertType(
type.getElementType());
899 if (!loweredElementType)
901 return cir::ArrayType::get(loweredElementType,
type.getSize());
904 addConversion([&](cir::DataMemberType type) -> mlir::Type {
907 return convertType(abiType);
909 addConversion([&](cir::MethodType type) -> mlir::Type {
911 return convertType(abiType);
916 addConversion([&](cir::FuncType type) -> mlir::Type {
917 llvm::SmallVector<mlir::Type> loweredInputTypes;
918 loweredInputTypes.reserve(
type.getNumInputs());
919 if (mlir::failed(convertTypes(
type.getInputs(), loweredInputTypes)))
922 mlir::Type loweredReturnType = convertType(
type.getReturnType());
923 if (!loweredReturnType)
926 return cir::FuncType::get(loweredInputTypes, loweredReturnType,
929 addConversion([&](cir::RecordType type) -> mlir::Type {
930 return convertRecordType(type);
934 void restoreRecordTypeNames() {
935 std::unique_lock<
decltype(recordTypeMutex)> lock(recordTypeMutex);
937 for (
auto rt : convertedRecordTypes)
938 rt.removeABIConversionNamePrefix();
945 const mlir::TypeConverter &typeConverter) {
946 target.addLegalOp<mlir::ModuleOp>();
951 target.addDynamicallyLegalDialect<cir::CIRDialect>(
952 [&typeConverter](mlir::Operation *op) {
953 if (!typeConverter.isLegal(op))
956 bool attrs = llvm::all_of(
957 op->getAttrs(), [&typeConverter](
const mlir::NamedAttribute &a) {
958 return isCXXABIAttributeLegal(typeConverter, a.getValue());
962 std::all_of(op->getRegions().begin(), op->getRegions().end(),
963 [&typeConverter](mlir::Region ®ion) {
964 return typeConverter.isLegal(®ion);
968 target.addDynamicallyLegalDialect<mlir::acc::OpenACCDialect>(
969 [&typeConverter](mlir::Operation *op) {
970 if (!typeConverter.isLegal(op))
973 bool attrs = llvm::all_of(
974 op->getAttrs(), [&typeConverter](
const mlir::NamedAttribute &a) {
975 return isCXXABIAttributeLegal(typeConverter, a.getValue());
979 std::all_of(op->getRegions().begin(), op->getRegions().end(),
980 [&typeConverter](mlir::Region ®ion) {
981 return typeConverter.isLegal(®ion);
986 target.addDynamicallyLegalOp<cir::FuncOp>([&typeConverter](cir::FuncOp op) {
987 bool attrs = llvm::all_of(
988 op->getAttrs(), [&typeConverter](
const mlir::NamedAttribute &a) {
989 return isCXXABIAttributeLegal(typeConverter, a.getValue());
992 return attrs && typeConverter.isLegal(op.getFunctionType());
994 target.addDynamicallyLegalOp<cir::GlobalOp>(
995 [&typeConverter](cir::GlobalOp op) {
996 return typeConverter.isLegal(op.getSymType());
1000 target.addIllegalOp<cir::DeleteArrayOp>();
1001 target.addIllegalOp<cir::DynamicCastOp>();
1002 target.addIllegalOp<cir::VTableGetTypeInfoOp>();
1044 parent->walk([&](mlir::Block *blk) {
1045 if (blk->hasNoPredecessors() && !blk->isEntryBlock())
1046 unreachableBlocks.push_back(blk);
1049 std::set<mlir::Block *> visited;
1050 for (mlir::Block *root : unreachableBlocks) {
1053 std::deque<mlir::Block *> workList;
1054 workList.push_back(root);
1056 while (!workList.empty()) {
1057 mlir::Block *blk = workList.back();
1058 workList.pop_back();
1059 if (visited.count(blk))
1061 visited.emplace(blk);
1063 for (mlir::Operation &op : *blk)
1066 for (mlir::Block *succ : blk->getSuccessors())
1067 workList.push_back(succ);
1072void CXXABILoweringPass::runOnOperation() {
1073 auto mod = mlir::cast<mlir::ModuleOp>(getOperation());
1074 mlir::MLIRContext *ctx = mod.getContext();
1079 mod.emitWarning(
"Cannot create a CIR lower module, skipping the ")
1084 mlir::DataLayout dataLayout(mod);
1085 CIRABITypeConverter typeConverter(*ctx, dataLayout, *lowerModule);
1087 mlir::RewritePatternSet patterns(ctx);
1088 patterns.add<CIRGenericCXXABILoweringPattern>(patterns.getContext(),
1091#define GET_ABI_LOWERING_PATTERNS_LIST
1092#include "clang/CIR/Dialect/IR/CIRLowering.inc"
1093#undef GET_ABI_LOWERING_PATTERNS_LIST
1094 >(patterns.getContext(), typeConverter, dataLayout, *lowerModule);
1096 mlir::ConversionTarget target(*ctx);
1099 llvm::SmallVector<mlir::Operation *> ops;
1103 if (failed(mlir::applyPartialConversion(ops, target, std::move(patterns))))
1104 signalPassFailure();
1106 typeConverter.restoreRecordTypeNames();
1110 return std::make_unique<CXXABILoweringPass>();
#define CXX_ABI_ALWAYS_LEGAL_ATTRS
static void collectUnreachable(mlir::Operation *parent, llvm::SmallVector< mlir::Operation * > &ops)
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
CharUnits - This is an opaque type for sizes expressed in character units.
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
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)
std::unique_ptr< Pass > createCXXABILoweringPass()
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)