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(),
489 mlir::dyn_cast_if_present<cir::BlockAddrInfoAttr>(initVal)) {
490 assert(convertedTy == ptrTy &&
"BlockAddrInfo type should not change");
494 auto constPtr = mlir::cast_if_present<cir::ConstPtrAttr>(initVal);
497 return cir::ConstPtrAttr::get(convertedTy, constPtr.getValue());
500 assert(ty == tc.convertType(ty) &&
501 "cir.global or constant operand is not an CXXABI-dependent type");
504 return cast<mlir::TypedAttr>(initVal);
507mlir::LogicalResult CIRConstantOpABILowering::matchAndRewrite(
508 cir::ConstantOp op, OpAdaptor adaptor,
509 mlir::ConversionPatternRewriter &rewriter)
const {
511 mlir::DataLayout layout(op->getParentOfType<mlir::ModuleOp>());
513 lowerModule, layout, *getTypeConverter(), op.getType(), op.getValue());
514 rewriter.replaceOpWithNewOp<ConstantOp>(op, newValue);
515 return mlir::success();
518mlir::LogicalResult CIRCmpOpABILowering::matchAndRewrite(
519 cir::CmpOp op, OpAdaptor adaptor,
520 mlir::ConversionPatternRewriter &rewriter)
const {
521 mlir::Type type = op.getLhs().getType();
523 mlir::Value loweredResult;
524 if (mlir::isa<cir::DataMemberType>(type))
525 loweredResult = lowerModule->getCXXABI().lowerDataMemberCmp(
526 op, adaptor.getLhs(), adaptor.getRhs(), rewriter);
527 else if (mlir::isa<cir::MethodType>(type))
528 loweredResult = lowerModule->getCXXABI().lowerMethodCmp(
529 op, adaptor.getLhs(), adaptor.getRhs(), rewriter);
531 loweredResult = cir::CmpOp::create(
532 rewriter, op.getLoc(), getTypeConverter()->convertType(op.getType()),
533 adaptor.getKind(), adaptor.getLhs(), adaptor.getRhs());
535 rewriter.replaceOp(op, loweredResult);
536 return mlir::success();
539mlir::LogicalResult CIRFuncOpABILowering::matchAndRewrite(
540 cir::FuncOp op, OpAdaptor adaptor,
541 mlir::ConversionPatternRewriter &rewriter)
const {
542 cir::FuncType opFuncType = op.getFunctionType();
543 mlir::TypeConverter::SignatureConversion signatureConversion(
544 opFuncType.getNumInputs());
546 for (
const auto &[i, argType] : llvm::enumerate(opFuncType.getInputs())) {
547 mlir::Type loweredArgType = getTypeConverter()->convertType(argType);
549 return mlir::failure();
550 signatureConversion.addInputs(i, loweredArgType);
553 mlir::Type loweredResultType =
554 getTypeConverter()->convertType(opFuncType.getReturnType());
555 if (!loweredResultType)
556 return mlir::failure();
558 auto loweredFuncType =
559 cir::FuncType::get(signatureConversion.getConvertedTypes(),
560 loweredResultType, opFuncType.isVarArg());
563 cir::FuncOp loweredFuncOp = rewriter.cloneWithoutRegions(op);
564 loweredFuncOp.setFunctionType(loweredFuncType);
567 for (
const mlir::NamedAttribute &na : op->getAttrs())
569 {na.getName(), rewriteAttribute(*getTypeConverter(), op->getContext(),
572 loweredFuncOp->setAttrs(attrs);
574 rewriter.inlineRegionBefore(op.getBody(), loweredFuncOp.getBody(),
575 loweredFuncOp.end());
576 if (mlir::failed(rewriter.convertRegionTypes(
577 &loweredFuncOp.getBody(), *getTypeConverter(), &signatureConversion)))
578 return mlir::failure();
580 rewriter.eraseOp(op);
581 return mlir::success();
584mlir::LogicalResult CIRGlobalOpABILowering::matchAndRewrite(
585 cir::GlobalOp op, OpAdaptor adaptor,
586 mlir::ConversionPatternRewriter &rewriter)
const {
587 mlir::Type ty = op.getSymType();
588 mlir::Type loweredTy = getTypeConverter()->convertType(ty);
590 return mlir::failure();
592 mlir::DataLayout layout(op->getParentOfType<mlir::ModuleOp>());
595 lowerModule, layout, *getTypeConverter(), ty, op.getInitialValueAttr());
597 auto newOp = mlir::cast<cir::GlobalOp>(rewriter.clone(*op.getOperation()));
598 newOp.setInitialValueAttr(loweredInit);
599 newOp.setSymType(loweredTy);
600 rewriter.replaceOp(op, newOp);
601 return mlir::success();
604mlir::LogicalResult CIRBaseDataMemberOpABILowering::matchAndRewrite(
605 cir::BaseDataMemberOp op, OpAdaptor adaptor,
606 mlir::ConversionPatternRewriter &rewriter)
const {
607 mlir::Value loweredResult = lowerModule->getCXXABI().lowerBaseDataMember(
608 op, adaptor.getSrc(), rewriter);
609 rewriter.replaceOp(op, loweredResult);
610 return mlir::success();
613mlir::LogicalResult CIRBaseMethodOpABILowering::matchAndRewrite(
614 cir::BaseMethodOp op, OpAdaptor adaptor,
615 mlir::ConversionPatternRewriter &rewriter)
const {
616 mlir::Value loweredResult =
617 lowerModule->getCXXABI().lowerBaseMethod(op, adaptor.getSrc(), rewriter);
618 rewriter.replaceOp(op, loweredResult);
619 return mlir::success();
622mlir::LogicalResult CIRDeleteArrayOpABILowering::matchAndRewrite(
623 cir::DeleteArrayOp op, OpAdaptor adaptor,
624 mlir::ConversionPatternRewriter &rewriter)
const {
625 mlir::FlatSymbolRefAttr deleteFn = op.getDeleteFnAttr();
626 mlir::Location loc = op->getLoc();
627 mlir::Value loweredAddress = adaptor.getAddress();
629 cir::UsualDeleteParamsAttr deleteParams = op.getDeleteParams();
630 bool cookieRequired = deleteParams.getSize() || op.getElementDtorAttr();
632 if (deleteParams.getTypeAwareDelete() || deleteParams.getDestroyingDelete() ||
633 deleteParams.getAlignment())
634 return rewriter.notifyMatchFailure(
635 op,
"type-aware, destroying, or aligned delete not yet supported");
637 const CIRCXXABI &cxxABI = lowerModule->getCXXABI();
646 mlir::Value deletePtr;
647 mlir::Value numElements;
648 cir::PointerType ptrTy;
650 mlir::DataLayout dl(op->getParentOfType<mlir::ModuleOp>());
653 cir::IntType sizeTy = cirBuilder.getUIntNTy(ptrWidth);
655 if (cookieRequired) {
656 ptrTy = mlir::cast<cir::PointerType>(loweredAddress.getType());
657 cxxABI.
readArrayCookie(loc, loweredAddress, dl, cirBuilder, numElements,
658 deletePtr, cookieSize);
660 deletePtr = cir::CastOp::create(rewriter, loc, cirBuilder.getVoidPtrTy(),
661 cir::CastKind::bitcast, loweredAddress);
671 mlir::FlatSymbolRefAttr dtorFn = op.getElementDtorAttr();
672 cir::CleanupKind cleanupKind =
673 op.getDtorMayThrow() ? cir::CleanupKind::All : cir::CleanupKind::Normal;
674 cir::CleanupScopeOp::create(
675 rewriter, loc, cleanupKind,
677 [&](mlir::OpBuilder &b, mlir::Location l) {
679 auto eltPtrTy = cir::PointerType::get(ptrTy.getPointee());
680 auto arrayDtor = cir::ArrayDtor::create(
681 b, l, loweredAddress, numElements,
682 [&](mlir::OpBuilder &bb, mlir::Location ll) {
684 bb.getInsertionBlock()->addArgument(eltPtrTy, ll);
685 auto dtorCall = cir::CallOp::create(
686 bb, ll, dtorFn, cir::VoidType(), mlir::ValueRange{
arg});
687 if (!op.getDtorMayThrow())
688 dtorCall.setNothrowAttr(bb.getUnitAttr());
689 cir::YieldOp::create(bb, ll);
691 if (op.getDtorMayThrow())
692 arrayDtor.setDtorMayThrow(
true);
694 cir::YieldOp::create(b, l);
697 [&](mlir::OpBuilder &b, mlir::Location l) {
700 if (deleteParams.getSize()) {
701 uint64_t eltSizeBytes = dl.getTypeSizeInBits(ptrTy.getPointee()) / 8;
702 auto eltSizeVal = cir::ConstantOp::create(
703 b, l, cir::IntAttr::get(sizeTy, eltSizeBytes));
704 mlir::Value allocSize =
705 cir::MulOp::create(b, l, sizeTy, eltSizeVal, numElements);
706 auto cookieSizeVal = cir::ConstantOp::create(
707 b, l, cir::IntAttr::get(sizeTy, cookieSize.
getQuantity()));
709 cir::AddOp::create(b, l, sizeTy, allocSize, cookieSizeVal);
713 cir::CallOp::create(b, l, deleteFn, cir::VoidType(), callArgs);
716 deleteCall.setNothrowAttr(b.getUnitAttr());
717 cir::YieldOp::create(b, l);
720 rewriter.eraseOp(op);
721 return mlir::success();
724mlir::LogicalResult CIRDerivedDataMemberOpABILowering::matchAndRewrite(
725 cir::DerivedDataMemberOp op, OpAdaptor adaptor,
726 mlir::ConversionPatternRewriter &rewriter)
const {
727 mlir::Value loweredResult = lowerModule->getCXXABI().lowerDerivedDataMember(
728 op, adaptor.getSrc(), rewriter);
729 rewriter.replaceOp(op, loweredResult);
730 return mlir::success();
733mlir::LogicalResult CIRDerivedMethodOpABILowering::matchAndRewrite(
734 cir::DerivedMethodOp op, OpAdaptor adaptor,
735 mlir::ConversionPatternRewriter &rewriter)
const {
736 mlir::Value loweredResult = lowerModule->getCXXABI().lowerDerivedMethod(
737 op, adaptor.getSrc(), rewriter);
738 rewriter.replaceOp(op, loweredResult);
739 return mlir::success();
742mlir::LogicalResult CIRDynamicCastOpABILowering::matchAndRewrite(
743 cir::DynamicCastOp op, OpAdaptor adaptor,
744 mlir::ConversionPatternRewriter &rewriter)
const {
745 mlir::Value loweredResult =
746 lowerModule->getCXXABI().lowerDynamicCast(op, rewriter);
747 rewriter.replaceOp(op, loweredResult);
748 return mlir::success();
751mlir::LogicalResult CIRGetMethodOpABILowering::matchAndRewrite(
752 cir::GetMethodOp op, OpAdaptor adaptor,
753 mlir::ConversionPatternRewriter &rewriter)
const {
756 lowerModule->getCXXABI().lowerGetMethod(
757 op, callee, thisArg, adaptor.getMethod(), adaptor.getObject(), rewriter);
758 rewriter.replaceOp(op, {callee, thisArg});
759 return mlir::success();
762mlir::LogicalResult CIRGetRuntimeMemberOpABILowering::matchAndRewrite(
763 cir::GetRuntimeMemberOp op, OpAdaptor adaptor,
764 mlir::ConversionPatternRewriter &rewriter)
const {
765 mlir::Type resTy = getTypeConverter()->convertType(op.getType());
766 mlir::Operation *newOp = lowerModule->getCXXABI().lowerGetRuntimeMember(
767 op, resTy, adaptor.getAddr(), adaptor.getMember(), rewriter);
768 rewriter.replaceOp(op, newOp);
769 return mlir::success();
772mlir::LogicalResult CIRVTableGetTypeInfoOpABILowering::matchAndRewrite(
773 cir::VTableGetTypeInfoOp op, OpAdaptor adaptor,
774 mlir::ConversionPatternRewriter &rewriter)
const {
775 mlir::Value loweredResult =
776 lowerModule->getCXXABI().lowerVTableGetTypeInfo(op, rewriter);
777 rewriter.replaceOp(op, loweredResult);
778 return mlir::success();
786class CIRABITypeConverter :
public mlir::TypeConverter {
788 mlir::MLIRContext &context;
793 DenseMap<uint64_t, std::unique_ptr<SmallVector<cir::RecordType>>>
795 llvm::sys::SmartRWMutex<true> callStackMutex;
800 llvm::SmallVector<cir::RecordType> convertedRecordTypes;
801 llvm::sys::SmartRWMutex<true> recordTypeMutex;
807 SmallVector<cir::RecordType> &getCurrentThreadRecursiveStack() {
810 std::shared_lock<
decltype(callStackMutex)> lock(callStackMutex,
812 if (context.isMultithreadingEnabled())
814 auto recursiveStack = conversionCallStack.find(llvm::get_threadid());
815 if (recursiveStack != conversionCallStack.end())
816 return *recursiveStack->second;
821 std::unique_lock<
decltype(callStackMutex)> lock(callStackMutex);
822 auto recursiveStackInserted = conversionCallStack.insert(
823 std::make_pair(llvm::get_threadid(),
824 std::make_unique<SmallVector<cir::RecordType>>()));
825 return *recursiveStackInserted.first->second;
828 void addConvertedRecordType(cir::RecordType rt) {
829 std::unique_lock<
decltype(recordTypeMutex)> lock(recordTypeMutex);
830 convertedRecordTypes.push_back(rt);
833 llvm::SmallVector<mlir::Type> convertRecordMemberTypes(cir::RecordType type) {
834 llvm::SmallVector<mlir::Type> loweredMemberTypes;
835 loweredMemberTypes.reserve(
type.getNumElements());
837 if (mlir::failed(convertTypes(
type.getMembers(), loweredMemberTypes)))
840 return loweredMemberTypes;
843 cir::RecordType convertRecordType(cir::RecordType type) {
847 if (!
type.getName()) {
848 llvm::SmallVector<mlir::Type> converted = convertRecordMemberTypes(type);
849 if (
auto u = mlir::dyn_cast<cir::UnionType>(type)) {
850 mlir::Type loweredPadding;
851 if (mlir::Type pad = u.getPadding())
852 loweredPadding = convertType(pad);
853 return cir::UnionType::get(
type.getContext(), converted,
854 type.getPacked(), loweredPadding);
856 auto s = mlir::cast<cir::StructType>(type);
857 return cir::StructType::get(
type.getContext(), converted,
862 assert(!
type.isIncomplete() ||
type.getMembers().empty());
867 if (
type.isIncomplete() ||
type.isABIConvertedRecord())
870 SmallVectorImpl<cir::RecordType> &recursiveStack =
871 getCurrentThreadRecursiveStack();
873 cir::RecordType convertedType;
874 if (mlir::isa<cir::UnionType>(type))
876 cir::UnionType::get(
type.getContext(),
type.getABIConvertedName());
879 cir::StructType::get(
type.getContext(),
type.getABIConvertedName(),
880 mlir::cast<cir::StructType>(type).getIsClass());
884 return convertedType;
890 if (llvm::is_contained(recursiveStack, type))
891 return convertedType;
893 recursiveStack.push_back(type);
894 llvm::scope_exit popConvertingType(
895 [&recursiveStack]() { recursiveStack.pop_back(); });
897 SmallVector<mlir::Type> convertedMembers = convertRecordMemberTypes(type);
899 mlir::Type loweredPadding;
900 if (
auto u = mlir::dyn_cast<cir::UnionType>(type))
901 if (mlir::Type pad = u.getPadding())
902 loweredPadding = convertType(pad);
903 convertedType.
complete(convertedMembers,
type.getPacked(),
type.getPadded(),
905 addConvertedRecordType(convertedType);
906 return convertedType;
910 CIRABITypeConverter(mlir::MLIRContext &ctx, mlir::DataLayout &dataLayout,
911 cir::LowerModule &lowerModule)
913 addConversion([&](mlir::Type type) -> mlir::Type {
return type; });
916 addConversion([&](cir::PointerType type) -> mlir::Type {
917 mlir::Type loweredPointeeType = convertType(
type.getPointee());
918 if (!loweredPointeeType)
920 return cir::PointerType::get(
type.getContext(), loweredPointeeType,
921 type.getAddrSpace());
923 addConversion([&](cir::ArrayType type) -> mlir::Type {
924 mlir::Type loweredElementType = convertType(
type.getElementType());
925 if (!loweredElementType)
927 return cir::ArrayType::get(loweredElementType,
type.getSize());
930 addConversion([&](cir::DataMemberType type) -> mlir::Type {
933 return convertType(abiType);
935 addConversion([&](cir::MethodType type) -> mlir::Type {
937 return convertType(abiType);
942 addConversion([&](cir::FuncType type) -> mlir::Type {
943 llvm::SmallVector<mlir::Type> loweredInputTypes;
944 loweredInputTypes.reserve(
type.getNumInputs());
945 if (mlir::failed(convertTypes(
type.getInputs(), loweredInputTypes)))
948 mlir::Type loweredReturnType = convertType(
type.getReturnType());
949 if (!loweredReturnType)
952 return cir::FuncType::get(loweredInputTypes, loweredReturnType,
955 addConversion([&](cir::StructType type) -> mlir::Type {
956 return convertRecordType(type);
958 addConversion([&](cir::UnionType type) -> mlir::Type {
959 return convertRecordType(type);
963 void restoreRecordTypeNames() {
964 std::unique_lock<
decltype(recordTypeMutex)> lock(recordTypeMutex);
966 for (
auto rt : convertedRecordTypes)
974 const mlir::TypeConverter &typeConverter) {
975 target.addLegalOp<mlir::ModuleOp>();
980 target.addDynamicallyLegalDialect<cir::CIRDialect>(
981 [&typeConverter](mlir::Operation *op) {
982 if (!typeConverter.isLegal(op))
985 bool attrs = llvm::all_of(
986 op->getAttrs(), [&typeConverter](
const mlir::NamedAttribute &a) {
987 return isCXXABIAttributeLegal(typeConverter, a.getValue());
991 std::all_of(op->getRegions().begin(), op->getRegions().end(),
992 [&typeConverter](mlir::Region ®ion) {
993 return typeConverter.isLegal(®ion);
997 target.addDynamicallyLegalDialect<mlir::acc::OpenACCDialect>(
998 [&typeConverter](mlir::Operation *op) {
999 if (!typeConverter.isLegal(op))
1002 bool attrs = llvm::all_of(
1003 op->getAttrs(), [&typeConverter](
const mlir::NamedAttribute &a) {
1004 return isCXXABIAttributeLegal(typeConverter, a.getValue());
1008 std::all_of(op->getRegions().begin(), op->getRegions().end(),
1009 [&typeConverter](mlir::Region ®ion) {
1010 return typeConverter.isLegal(®ion);
1015 target.addDynamicallyLegalOp<cir::FuncOp>([&typeConverter](cir::FuncOp op) {
1016 bool attrs = llvm::all_of(
1017 op->getAttrs(), [&typeConverter](
const mlir::NamedAttribute &a) {
1018 return isCXXABIAttributeLegal(typeConverter, a.getValue());
1021 return attrs && typeConverter.isLegal(op.getFunctionType());
1023 target.addDynamicallyLegalOp<cir::GlobalOp>(
1024 [&typeConverter](cir::GlobalOp op) {
1025 return typeConverter.isLegal(op.getSymType());
1029 target.addIllegalOp<cir::DeleteArrayOp>();
1030 target.addIllegalOp<cir::DynamicCastOp>();
1031 target.addIllegalOp<cir::VTableGetTypeInfoOp>();
1038void CXXABILoweringPass::runOnOperation() {
1039 auto mod = mlir::cast<mlir::ModuleOp>(getOperation());
1040 mlir::MLIRContext *ctx = mod.getContext();
1045 mod.emitWarning(
"Cannot create a CIR lower module, skipping the ")
1050 mlir::DataLayout dataLayout(mod);
1051 CIRABITypeConverter typeConverter(*ctx, dataLayout, *lowerModule);
1053 mlir::RewritePatternSet patterns(ctx);
1054 patterns.add<CIRGenericCXXABILoweringPattern>(patterns.getContext(),
1057#define GET_ABI_LOWERING_PATTERNS_LIST
1058#include "clang/CIR/Dialect/IR/CIRLowering.inc"
1059#undef GET_ABI_LOWERING_PATTERNS_LIST
1060 >(patterns.getContext(), typeConverter, dataLayout, *lowerModule);
1062 mlir::ConversionTarget target(*ctx);
1065 llvm::SmallVector<mlir::Operation *> ops;
1069 if (failed(mlir::applyPartialConversion(ops, target, std::move(patterns))))
1070 signalPassFailure();
1072 typeConverter.restoreRecordTypeNames();
1076 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)