13#include "mlir/Dialect/OpenACC/OpenACCOpsDialect.h.inc"
14#include "mlir/Dialect/OpenMP/OpenMPOpsDialect.h.inc"
15#include "mlir/IR/PatternMatch.h"
16#include "mlir/Interfaces/DataLayoutInterfaces.h"
17#include "mlir/Pass/Pass.h"
18#include "mlir/Transforms/DialectConversion.h"
28#include "llvm/ADT/TypeSwitch.h"
34#define GEN_PASS_DEF_CXXABILOWERING
35#include "clang/CIR/Dialect/Passes.h.inc"
42bool isCXXABIAttributeLegal(
const mlir::TypeConverter &tc,
43 mlir::Attribute
attr) {
50 if (isa<mlir::acc::OpenACCDialect, mlir::omp::OpenMPDialect>(
56 if (
isa<mlir::DenseArrayAttr, mlir::FloatAttr, mlir::UnitAttr,
57 mlir::StringAttr, mlir::IntegerAttr, mlir::SymbolRefAttr,
58 cir::AnnotationAttr>(
attr))
64#include
"clang/CIR/Dialect/IR/CIRLowering.inc"
71 if (isa<mlir::DistinctAttr>(
attr))
75 if (isa<cir::DataMemberAttr, cir::DataMemberOffsetAttr, cir::MethodAttr>(
79 return llvm::TypeSwitch<mlir::Attribute, bool>(
attr)
82 [&tc](cir::ZeroAttr za) {
return tc.isLegal(za.getType()); })
83 .Case<cir::PoisonAttr>(
84 [&tc](cir::PoisonAttr pa) {
return tc.isLegal(pa.getType()); })
85 .Case<cir::UndefAttr>(
86 [&tc](cir::UndefAttr uda) {
return tc.isLegal(uda.getType()); })
87 .Case<mlir::TypeAttr>(
88 [&tc](mlir::TypeAttr ta) {
return tc.isLegal(ta.getValue()); })
89 .Case<cir::ConstPtrAttr>(
90 [&tc](cir::ConstPtrAttr cpa) {
return tc.isLegal(cpa.getType()); })
91 .Case<cir::CXXCtorAttr>(
92 [&tc](cir::CXXCtorAttr ca) {
return tc.isLegal(ca.getType()); })
93 .Case<cir::CXXDtorAttr>(
94 [&tc](cir::CXXDtorAttr da) {
return tc.isLegal(da.getType()); })
95 .Case<cir::CXXAssignAttr>(
96 [&tc](cir::CXXAssignAttr aa) {
return tc.isLegal(aa.getType()); })
100 .Case<mlir::ArrayAttr>([&tc](mlir::ArrayAttr array) {
101 return llvm::all_of(array.getValue(), [&tc](mlir::Attribute
attr) {
102 return isCXXABIAttributeLegal(tc, attr);
105 .Case<mlir::DictionaryAttr>([&tc](mlir::DictionaryAttr dict) {
106 return llvm::all_of(dict.getValue(), [&tc](mlir::NamedAttribute na) {
107 return isCXXABIAttributeLegal(tc, na.getValue());
111 .Case<cir::ConstArrayAttr>([&tc](cir::ConstArrayAttr array) {
112 return tc.isLegal(array.getType()) &&
113 isCXXABIAttributeLegal(tc, array.getElts());
115 .Case<cir::GlobalViewAttr>([&tc](cir::GlobalViewAttr gva) {
116 return tc.isLegal(gva.getType()) &&
117 isCXXABIAttributeLegal(tc, gva.getIndices());
119 .Case<cir::GlobalOffsetAttr>([&tc](cir::GlobalOffsetAttr goa) {
120 return tc.isLegal(goa.getType());
122 .Case<cir::VTableAttr>([&tc](cir::VTableAttr vta) {
123 return tc.isLegal(vta.getType()) &&
124 isCXXABIAttributeLegal(tc, vta.getData());
126 .Case<cir::TypeInfoAttr>([&tc](cir::TypeInfoAttr tia) {
127 return tc.isLegal(tia.getType()) &&
128 isCXXABIAttributeLegal(tc, tia.getData());
130 .Case<cir::DynamicCastInfoAttr>([&tc](cir::DynamicCastInfoAttr dcia) {
131 return isCXXABIAttributeLegal(tc, dcia.getSrcRtti()) &&
132 isCXXABIAttributeLegal(tc, dcia.getDestRtti()) &&
133 isCXXABIAttributeLegal(tc, dcia.getRuntimeFunc()) &&
134 isCXXABIAttributeLegal(tc, dcia.getBadCastFunc());
136 .Case<cir::ConstRecordAttr>([&tc](cir::ConstRecordAttr cra) {
137 return tc.isLegal(cra.getType()) &&
138 isCXXABIAttributeLegal(tc, cra.getMembers());
149mlir::Attribute rewriteAttribute(
const mlir::TypeConverter &tc,
150 mlir::MLIRContext *ctx, mlir::Attribute attr) {
153 if (isCXXABIAttributeLegal(tc, attr))
161 return llvm::TypeSwitch<mlir::Attribute, mlir::Attribute>(attr)
163 .Case<cir::ZeroAttr>([&tc](cir::ZeroAttr za) {
164 return cir::ZeroAttr::get(tc.convertType(za.getType()));
166 .Case<cir::PoisonAttr>([&tc](cir::PoisonAttr pa) {
167 return cir::PoisonAttr::get(tc.convertType(pa.getType()));
169 .Case<cir::UndefAttr>([&tc](cir::UndefAttr uda) {
170 return cir::UndefAttr::get(tc.convertType(uda.getType()));
172 .Case<mlir::TypeAttr>([&tc](mlir::TypeAttr ta) {
173 return mlir::TypeAttr::get(tc.convertType(ta.getValue()));
175 .Case<cir::ConstPtrAttr>([&tc](cir::ConstPtrAttr cpa) {
176 return cir::ConstPtrAttr::get(tc.convertType(cpa.getType()),
179 .Case<cir::CXXCtorAttr>([&tc](cir::CXXCtorAttr ca) {
180 return cir::CXXCtorAttr::get(tc.convertType(ca.getType()),
181 ca.getCtorKind(), ca.getIsTrivial());
183 .Case<cir::CXXDtorAttr>([&tc](cir::CXXDtorAttr da) {
184 return cir::CXXDtorAttr::get(tc.convertType(da.getType()),
187 .Case<cir::CXXAssignAttr>([&tc](cir::CXXAssignAttr aa) {
188 return cir::CXXAssignAttr::get(tc.convertType(aa.getType()),
189 aa.getAssignKind(), aa.getIsTrivial());
193 .Case<mlir::ArrayAttr>([&tc, ctx](mlir::ArrayAttr array) {
195 for (mlir::Attribute a : array.getValue())
196 elts.push_back(rewriteAttribute(tc, ctx, a));
197 return mlir::ArrayAttr::get(ctx, elts);
199 .Case<mlir::DictionaryAttr>([&tc, ctx](mlir::DictionaryAttr dict) {
201 for (mlir::NamedAttribute na : dict.getValue())
202 elts.emplace_back(na.getName(),
203 rewriteAttribute(tc, ctx, na.getValue()));
205 return mlir::DictionaryAttr::get(ctx, elts);
208 .Case<cir::ConstArrayAttr>([&tc, ctx](cir::ConstArrayAttr array) {
209 return cir::ConstArrayAttr::get(
210 ctx, tc.convertType(array.getType()),
211 rewriteAttribute(tc, ctx, array.getElts()),
212 array.getTrailingZerosNum());
214 .Case<cir::GlobalViewAttr>([&tc, ctx](cir::GlobalViewAttr gva) {
215 return cir::GlobalViewAttr::get(
216 tc.convertType(gva.getType()), gva.getSymbol(),
217 mlir::cast<mlir::ArrayAttr>(
218 rewriteAttribute(tc, ctx, gva.getIndices())),
219 gva.getAddressPoint());
221 .Case<cir::GlobalOffsetAttr>([&tc](cir::GlobalOffsetAttr goa) {
222 return cir::GlobalOffsetAttr::get(tc.convertType(goa.getType()),
223 goa.getSymbol(), goa.getOffset());
225 .Case<cir::VTableAttr>([&tc, ctx](cir::VTableAttr vta) {
226 return cir::VTableAttr::get(
227 tc.convertType(vta.getType()),
228 mlir::cast<mlir::ArrayAttr>(
229 rewriteAttribute(tc, ctx, vta.getData())),
230 vta.getAddressPoints());
232 .Case<cir::TypeInfoAttr>([&tc, ctx](cir::TypeInfoAttr tia) {
233 return cir::TypeInfoAttr::get(
234 tc.convertType(tia.getType()),
235 mlir::cast<mlir::ArrayAttr>(
236 rewriteAttribute(tc, ctx, tia.getData())));
238 .Case<cir::DynamicCastInfoAttr>([&tc,
239 ctx](cir::DynamicCastInfoAttr dcia) {
240 return cir::DynamicCastInfoAttr::get(
241 mlir::cast<cir::GlobalViewAttr>(
242 rewriteAttribute(tc, ctx, dcia.getSrcRtti())),
243 mlir::cast<cir::GlobalViewAttr>(
244 rewriteAttribute(tc, ctx, dcia.getDestRtti())),
245 dcia.getRuntimeFunc(), dcia.getBadCastFunc(), dcia.getOffsetHint());
247 .Case<cir::ConstRecordAttr>([&tc, ctx](cir::ConstRecordAttr cra) {
248 return cir::ConstRecordAttr::get(
249 ctx, tc.convertType(cra.getType()),
250 mlir::cast<mlir::ArrayAttr>(
251 rewriteAttribute(tc, ctx, cra.getMembers())));
253 .DefaultUnreachable(
"unrewritten illegal attribute kind");
256bool areCXXABIInherentAttrsLegal(mlir::Operation *op,
257 const mlir::TypeConverter &typeConverter) {
259 op->getName().walkInherentAttrs(
260 op, [&](llvm::StringRef, mlir::Attribute &attr) {
261 legal &= isCXXABIAttributeLegal(typeConverter, attr);
266#define GET_ABI_LOWERING_PATTERNS
267#include "clang/CIR/Dialect/IR/CIRLowering.inc"
268#undef GET_ABI_LOWERING_PATTERNS
270struct CXXABILoweringPass
271 :
public impl::CXXABILoweringBase<CXXABILoweringPass> {
272 CXXABILoweringPass() =
default;
273 void runOnOperation()
override;
281class CIRGenericCXXABILoweringPattern :
public mlir::ConversionPattern {
283 CIRGenericCXXABILoweringPattern(mlir::MLIRContext *context,
284 const mlir::TypeConverter &typeConverter)
285 : mlir::ConversionPattern(typeConverter, MatchAnyOpTypeTag(),
289 matchAndRewrite(mlir::Operation *op, llvm::ArrayRef<mlir::Value> operands,
290 mlir::ConversionPatternRewriter &rewriter)
const override {
292 if (llvm::isa<cir::AllocaOp, cir::BaseDataMemberOp, cir::BaseMethodOp,
293 cir::CastOp, cir::CmpOp, cir::ConstantOp, cir::DeleteArrayOp,
294 cir::DerivedDataMemberOp, cir::DerivedMethodOp, cir::FuncOp,
295 cir::GetMethodOp, cir::GetRuntimeMemberOp, cir::GlobalOp>(op))
296 return mlir::failure();
298 const mlir::TypeConverter *typeConverter = getTypeConverter();
299 assert(typeConverter &&
300 "CIRGenericCXXABILoweringPattern requires a type converter");
301 bool operandsAndResultsLegal = typeConverter->isLegal(op);
303 std::all_of(op->getRegions().begin(), op->getRegions().end(),
304 [typeConverter](mlir::Region ®ion) {
305 return typeConverter->isLegal(®ion);
307 bool attrsLegal = areCXXABIInherentAttrsLegal(op, *typeConverter);
309 if (operandsAndResultsLegal && regionsLegal && attrsLegal) {
312 return mlir::failure();
315 mlir::OperationState loweredOpState(op->getLoc(), op->getName());
316 loweredOpState.addOperands(operands);
317 loweredOpState.addSuccessors(op->getSuccessors());
320 loweredOpState.propertiesAttr = op->getPropertiesAsAttribute();
321 loweredOpState.addAttributes(op->getDiscardableAttrDictionary().getValue());
324 llvm::SmallVector<mlir::Type> loweredResultTypes;
325 loweredResultTypes.reserve(op->getNumResults());
326 for (mlir::Type result : op->getResultTypes())
327 loweredResultTypes.push_back(typeConverter->convertType(result));
328 loweredOpState.addTypes(loweredResultTypes);
331 for (mlir::Region ®ion : op->getRegions()) {
333 rewriter.convertRegionTypes(®ion, *getTypeConverter())))
334 return mlir::failure();
336 for (mlir::Region ®ion : op->getRegions()) {
337 mlir::Region *loweredRegion = loweredOpState.addRegion();
338 rewriter.inlineRegionBefore(region, *loweredRegion, loweredRegion->end());
342 mlir::Operation *loweredOp = rewriter.create(loweredOpState);
343 loweredOp->getName().walkInherentAttrs(
344 loweredOp, [&](llvm::StringRef, mlir::Attribute &attr) {
345 attr = rewriteAttribute(*typeConverter, op->getContext(), attr);
348 rewriter.replaceOp(op, loweredOp);
349 return mlir::success();
355mlir::LogicalResult CIRAllocaOpABILowering::matchAndRewrite(
356 cir::AllocaOp op, OpAdaptor adaptor,
357 mlir::ConversionPatternRewriter &rewriter)
const {
358 mlir::Type allocaPtrTy = op.getType();
359 mlir::Type loweredAllocaPtrTy = getTypeConverter()->convertType(allocaPtrTy);
361 cir::AllocaOp loweredOp = cir::AllocaOp::create(
362 rewriter, op.getLoc(), loweredAllocaPtrTy, op.getName(),
363 op.getAlignmentAttr(), adaptor.getDynAllocSize());
364 loweredOp.setInit(op.getInit());
365 loweredOp.setConstant(op.getConstant());
366 loweredOp.setReturnSlot(op.getReturnSlot());
368 rewriter.replaceOp(op, loweredOp);
369 return mlir::success();
372mlir::LogicalResult CIRCastOpABILowering::matchAndRewrite(
373 cir::CastOp op, OpAdaptor adaptor,
374 mlir::ConversionPatternRewriter &rewriter)
const {
375 mlir::Type srcTy = op.getSrc().getType();
377 if (mlir::isa<cir::DataMemberType, cir::MethodType>(srcTy)) {
378 switch (op.getKind()) {
379 case cir::CastKind::bitcast: {
380 mlir::Type destTy = getTypeConverter()->convertType(op.getType());
381 mlir::Value loweredResult;
382 if (mlir::isa<cir::DataMemberType>(srcTy))
383 loweredResult = lowerModule->getCXXABI().lowerDataMemberBitcast(
384 op, destTy, adaptor.getSrc(), rewriter);
386 loweredResult = lowerModule->getCXXABI().lowerMethodBitcast(
387 op, destTy, adaptor.getSrc(), rewriter);
388 rewriter.replaceOp(op, loweredResult);
389 return mlir::success();
391 case cir::CastKind::member_ptr_to_bool: {
392 mlir::Value loweredResult;
393 if (mlir::isa<cir::DataMemberType>(srcTy))
394 loweredResult = lowerModule->getCXXABI().lowerDataMemberToBoolCast(
395 op, adaptor.getSrc(), rewriter);
397 loweredResult = lowerModule->getCXXABI().lowerMethodToBoolCast(
398 op, adaptor.getSrc(), rewriter);
399 rewriter.replaceOp(op, loweredResult);
400 return mlir::success();
407 mlir::Value loweredResult = cir::CastOp::create(
408 rewriter, op.getLoc(), getTypeConverter()->convertType(op.getType()),
409 adaptor.getKind(), adaptor.getSrc());
410 rewriter.replaceOp(op, loweredResult);
411 return mlir::success();
416 const mlir::DataLayout &layout,
417 const mlir::TypeConverter &tc,
419 mlir::Attribute initVal) {
420 if (mlir::isa_and_present<cir::UndefAttr>(initVal))
421 return cir::UndefAttr::get(tc.convertType(ty));
423 if (mlir::isa_and_present<cir::PoisonAttr>(initVal))
424 return cir::PoisonAttr::get(tc.convertType(ty));
426 if (mlir::isa<cir::DataMemberType>(ty)) {
430 mlir::dyn_cast_if_present<cir::DataMemberOffsetAttr>(initVal))
433 auto dataMemberVal = mlir::cast_if_present<cir::DataMemberAttr>(initVal);
437 if (mlir::isa<cir::MethodType>(ty)) {
438 auto methodVal = mlir::cast_if_present<cir::MethodAttr>(initVal);
442 if (
auto arrTy = mlir::dyn_cast<cir::ArrayType>(ty)) {
443 auto loweredArrTy = mlir::cast<cir::ArrayType>(tc.convertType(arrTy));
448 if (
auto zeroVal = mlir::dyn_cast_if_present<cir::ZeroAttr>(initVal))
449 return cir::ZeroAttr::get(loweredArrTy);
451 auto arrayVal = mlir::cast<cir::ConstArrayAttr>(initVal);
457 if (mlir::isa<mlir::StringAttr>(arrayVal.getElts())) {
458 assert(loweredArrTy == arrTy &&
459 "string-literal array type should not change under CXX ABI");
463 auto arrayElts = mlir::cast<ArrayAttr>(arrayVal.getElts());
465 loweredElements.reserve(arrTy.getSize());
466 for (
const mlir::Attribute &attr : arrayElts) {
467 auto typedAttr = cast<mlir::TypedAttr>(attr);
469 lowerModule, layout, tc, typedAttr.getType(), typedAttr));
472 return cir::ConstArrayAttr::get(
473 loweredArrTy, mlir::ArrayAttr::get(ty.getContext(), loweredElements),
474 arrayVal.getTrailingZerosNum());
477 if (
auto recordTy = mlir::dyn_cast<cir::RecordType>(ty)) {
479 mlir::dyn_cast<cir::RecordType>(tc.convertType(recordTy));
483 if (
auto recVal = mlir::dyn_cast_if_present<cir::ZeroAttr>(initVal))
484 return cir::ZeroAttr::get(convertedTy);
487 mlir::dyn_cast_if_present<cir::ConstRecordAttr>(initVal)) {
488 auto recordMembers = mlir::cast<ArrayAttr>(recVal.getMembers());
491 loweredMembers.reserve(recordMembers.size());
493 for (
const mlir::Attribute &attr : recordMembers) {
494 auto typedAttr = cast<mlir::TypedAttr>(attr);
496 lowerModule, layout, tc, typedAttr.getType(), typedAttr));
499 return cir::ConstRecordAttr::get(
500 convertedTy, mlir::ArrayAttr::get(ty.getContext(), loweredMembers));
503 assert(!initVal &&
"Record init val type not handled");
508 if (
auto ptrTy = mlir::dyn_cast<cir::PointerType>(ty)) {
509 auto convertedTy = mlir::cast<cir::PointerType>(tc.convertType(ptrTy));
512 if (
auto gva = mlir::dyn_cast_if_present<cir::GlobalViewAttr>(initVal))
513 return cir::GlobalViewAttr::get(convertedTy, gva.getSymbol(),
514 gva.getIndices(), gva.getAddressPoint());
516 if (
auto goa = mlir::dyn_cast_if_present<cir::GlobalOffsetAttr>(initVal))
517 return cir::GlobalOffsetAttr::get(convertedTy, goa.getSymbol(),
521 mlir::dyn_cast_if_present<cir::BlockAddrInfoAttr>(initVal)) {
522 assert(convertedTy == ptrTy &&
"BlockAddrInfo type should not change");
526 auto constPtr = mlir::cast_if_present<cir::ConstPtrAttr>(initVal);
529 return cir::ConstPtrAttr::get(convertedTy, constPtr.getValue());
532 assert(ty == tc.convertType(ty) &&
533 "cir.global or constant operand is not an CXXABI-dependent type");
536 return cast<mlir::TypedAttr>(initVal);
539mlir::LogicalResult CIRConstantOpABILowering::matchAndRewrite(
540 cir::ConstantOp op, OpAdaptor adaptor,
541 mlir::ConversionPatternRewriter &rewriter)
const {
543 mlir::DataLayout layout(op->getParentOfType<mlir::ModuleOp>());
545 lowerModule, layout, *getTypeConverter(), op.getType(), op.getValue());
546 rewriter.replaceOpWithNewOp<ConstantOp>(op, newValue);
547 return mlir::success();
550mlir::LogicalResult CIRCmpOpABILowering::matchAndRewrite(
551 cir::CmpOp op, OpAdaptor adaptor,
552 mlir::ConversionPatternRewriter &rewriter)
const {
553 mlir::Type type = op.getLhs().getType();
555 mlir::Value loweredResult;
556 if (mlir::isa<cir::DataMemberType>(type))
557 loweredResult = lowerModule->getCXXABI().lowerDataMemberCmp(
558 op, adaptor.getLhs(), adaptor.getRhs(), rewriter);
559 else if (mlir::isa<cir::MethodType>(type))
560 loweredResult = lowerModule->getCXXABI().lowerMethodCmp(
561 op, adaptor.getLhs(), adaptor.getRhs(), rewriter);
563 loweredResult = cir::CmpOp::create(
564 rewriter, op.getLoc(), getTypeConverter()->convertType(op.getType()),
565 adaptor.getKind(), adaptor.getLhs(), adaptor.getRhs());
567 rewriter.replaceOp(op, loweredResult);
568 return mlir::success();
571mlir::LogicalResult CIRFuncOpABILowering::matchAndRewrite(
572 cir::FuncOp op, OpAdaptor adaptor,
573 mlir::ConversionPatternRewriter &rewriter)
const {
574 cir::FuncType opFuncType = op.getFunctionType();
575 mlir::TypeConverter::SignatureConversion signatureConversion(
576 opFuncType.getNumInputs());
578 for (
const auto &[i, argType] : llvm::enumerate(opFuncType.getInputs())) {
579 mlir::Type loweredArgType = getTypeConverter()->convertType(argType);
581 return mlir::failure();
582 signatureConversion.addInputs(i, loweredArgType);
585 mlir::Type loweredResultType =
586 getTypeConverter()->convertType(opFuncType.getReturnType());
587 if (!loweredResultType)
588 return mlir::failure();
590 auto loweredFuncType =
591 cir::FuncType::get(signatureConversion.getConvertedTypes(),
592 loweredResultType, opFuncType.isVarArg());
595 if (mlir::failed(rewriter.convertRegionTypes(
596 &op.getBody(), *getTypeConverter(), &signatureConversion)))
597 return mlir::failure();
600 cir::FuncOp loweredFuncOp = rewriter.cloneWithoutRegions(op);
601 loweredFuncOp.setFunctionType(loweredFuncType);
603 loweredFuncOp->getName().walkInherentAttrs(
604 loweredFuncOp, [&](llvm::StringRef, mlir::Attribute &attr) {
605 attr = rewriteAttribute(*getTypeConverter(), op->getContext(), attr);
607 rewriter.inlineRegionBefore(op.getBody(), loweredFuncOp.getBody(),
608 loweredFuncOp.end());
610 rewriter.eraseOp(op);
611 return mlir::success();
614mlir::LogicalResult CIRGlobalOpABILowering::matchAndRewrite(
615 cir::GlobalOp op, OpAdaptor adaptor,
616 mlir::ConversionPatternRewriter &rewriter)
const {
617 mlir::Type ty = op.getSymType();
618 mlir::Type loweredTy = getTypeConverter()->convertType(ty);
620 return mlir::failure();
622 mlir::DataLayout layout(op->getParentOfType<mlir::ModuleOp>());
625 lowerModule, layout, *getTypeConverter(), ty, op.getInitialValueAttr());
627 cir::GlobalOp newOp = rewriter.cloneWithoutRegions(op);
628 newOp.setInitialValueAttr(loweredInit);
629 newOp.setSymType(loweredTy);
633 rewriter.inlineRegionBefore(op.getCtorRegion(), newOp.getCtorRegion(),
634 newOp.getCtorRegion().end());
635 rewriter.inlineRegionBefore(op.getDtorRegion(), newOp.getDtorRegion(),
636 newOp.getDtorRegion().end());
637 rewriter.replaceOp(op, newOp);
638 return mlir::success();
641mlir::LogicalResult CIRBaseDataMemberOpABILowering::matchAndRewrite(
642 cir::BaseDataMemberOp op, OpAdaptor adaptor,
643 mlir::ConversionPatternRewriter &rewriter)
const {
644 mlir::Value loweredResult = lowerModule->getCXXABI().lowerBaseDataMember(
645 op, adaptor.getSrc(), rewriter);
646 rewriter.replaceOp(op, loweredResult);
647 return mlir::success();
650mlir::LogicalResult CIRBaseMethodOpABILowering::matchAndRewrite(
651 cir::BaseMethodOp op, OpAdaptor adaptor,
652 mlir::ConversionPatternRewriter &rewriter)
const {
653 mlir::Value loweredResult =
654 lowerModule->getCXXABI().lowerBaseMethod(op, adaptor.getSrc(), rewriter);
655 rewriter.replaceOp(op, loweredResult);
656 return mlir::success();
659mlir::LogicalResult CIRDeleteArrayOpABILowering::matchAndRewrite(
660 cir::DeleteArrayOp op, OpAdaptor adaptor,
661 mlir::ConversionPatternRewriter &rewriter)
const {
662 mlir::FlatSymbolRefAttr deleteFn = op.getDeleteFnAttr();
663 mlir::Location loc = op->getLoc();
664 mlir::Value loweredAddress = adaptor.getAddress();
666 cir::UsualDeleteParamsAttr deleteParams = op.getDeleteParamsAttr();
668 deleteParams = cir::UsualDeleteParamsAttr::get(op.getContext(),
false,
669 std::nullopt,
false,
false);
670 bool cookieRequired = deleteParams.getSize() || op.getElementDtorAttr();
672 assert(!deleteParams.getDestroyingDelete() &&
673 "destroying delete not legal on arrays");
674 assert(!deleteParams.getTypeAwareDelete() &&
675 "type-aware delete not legal on arrays");
677 const CIRCXXABI &cxxABI = lowerModule->getCXXABI();
686 mlir::Value deletePtr;
687 mlir::Value numElements;
688 auto ptrTy = mlir::cast<cir::PointerType>(loweredAddress.getType());
690 mlir::DataLayout dl(op->getParentOfType<mlir::ModuleOp>());
693 cir::IntType sizeTy = cirBuilder.getUIntNTy(ptrWidth);
695 if (cookieRequired) {
698 cxxABI.
readArrayCookie(loc, loweredAddress, elementAlign, dl, cirBuilder,
699 numElements, deletePtr, cookieSize);
701 deletePtr = cir::CastOp::create(
702 rewriter, loc, cirBuilder.getVoidPtrTy(ptrTy.getAddrSpace()),
703 cir::CastKind::bitcast, loweredAddress);
713 mlir::FlatSymbolRefAttr dtorFn = op.getElementDtorAttr();
716 auto getCalleeCallingConv = [&](mlir::FlatSymbolRefAttr callee) {
718 mlir::SymbolTable::lookupNearestSymbolFrom<cir::FuncOp>(op, callee))
719 return fn.getCallingConv();
720 return cir::CallingConv::C;
723 cir::CleanupKind cleanupKind =
724 op.getDtorMayThrow() ? cir::CleanupKind::All : cir::CleanupKind::Normal;
725 cir::CleanupScopeOp::create(
726 rewriter, loc, cleanupKind,
728 [&](mlir::OpBuilder &b, mlir::Location l) {
730 auto arrayDtor = cir::ArrayDtor::create(
731 b, l, loweredAddress, numElements,
732 [&](mlir::OpBuilder &bb, mlir::Location ll) {
734 bb.getInsertionBlock()->addArgument(ptrTy, ll);
735 auto dtorCall = cir::CallOp::create(
736 bb, ll, dtorFn, cir::VoidType(), mlir::ValueRange{
arg});
737 dtorCall.setCallingConv(getCalleeCallingConv(dtorFn));
738 if (!op.getDtorMayThrow())
739 dtorCall.setNothrowAttr(bb.getUnitAttr());
740 cir::YieldOp::create(bb, ll);
742 if (op.getDtorMayThrow())
743 arrayDtor.setDtorMayThrow(
true);
745 cir::YieldOp::create(b, l);
748 [&](mlir::OpBuilder &b, mlir::Location l) {
751 if (deleteParams.getSize()) {
752 uint64_t eltSizeBytes = dl.getTypeSizeInBits(ptrTy.getPointee()) / 8;
753 auto eltSizeVal = cir::ConstantOp::create(
754 b, l, cir::IntAttr::get(sizeTy, eltSizeBytes));
755 mlir::Value allocSize =
756 cir::MulOp::create(b, l, sizeTy, eltSizeVal, numElements);
757 auto cookieSizeVal = cir::ConstantOp::create(
758 b, l, cir::IntAttr::get(sizeTy, cookieSize.
getQuantity()));
760 cir::AddOp::create(b, l, sizeTy, allocSize, cookieSizeVal);
763 if (deleteParams.getAlignment()) {
764 auto alignVal = cir::ConstantOp::create(
765 b, l, cir::IntAttr::get(sizeTy, *deleteParams.getAlignment()));
770 cir::CallOp::create(b, l, deleteFn, cir::VoidType(), callArgs);
771 deleteCall.setCallingConv(getCalleeCallingConv(deleteFn));
774 deleteCall.setNothrowAttr(b.getUnitAttr());
775 cir::YieldOp::create(b, l);
778 rewriter.eraseOp(op);
779 return mlir::success();
782mlir::LogicalResult CIRDerivedDataMemberOpABILowering::matchAndRewrite(
783 cir::DerivedDataMemberOp op, OpAdaptor adaptor,
784 mlir::ConversionPatternRewriter &rewriter)
const {
785 mlir::Value loweredResult = lowerModule->getCXXABI().lowerDerivedDataMember(
786 op, adaptor.getSrc(), rewriter);
787 rewriter.replaceOp(op, loweredResult);
788 return mlir::success();
791mlir::LogicalResult CIRDerivedMethodOpABILowering::matchAndRewrite(
792 cir::DerivedMethodOp op, OpAdaptor adaptor,
793 mlir::ConversionPatternRewriter &rewriter)
const {
794 mlir::Value loweredResult = lowerModule->getCXXABI().lowerDerivedMethod(
795 op, adaptor.getSrc(), rewriter);
796 rewriter.replaceOp(op, loweredResult);
797 return mlir::success();
800mlir::LogicalResult CIRDynamicCastOpABILowering::matchAndRewrite(
801 cir::DynamicCastOp op, OpAdaptor adaptor,
802 mlir::ConversionPatternRewriter &rewriter)
const {
803 mlir::Value loweredResult =
804 lowerModule->getCXXABI().lowerDynamicCast(op, rewriter);
805 rewriter.replaceOp(op, loweredResult);
806 return mlir::success();
809mlir::LogicalResult CIRGetMethodOpABILowering::matchAndRewrite(
810 cir::GetMethodOp op, OpAdaptor adaptor,
811 mlir::ConversionPatternRewriter &rewriter)
const {
814 lowerModule->getCXXABI().lowerGetMethod(
815 op, callee, thisArg, adaptor.getMethod(), adaptor.getObject(), rewriter);
816 rewriter.replaceOp(op, {callee, thisArg});
817 return mlir::success();
820mlir::LogicalResult CIRGetRuntimeMemberOpABILowering::matchAndRewrite(
821 cir::GetRuntimeMemberOp op, OpAdaptor adaptor,
822 mlir::ConversionPatternRewriter &rewriter)
const {
823 mlir::Type resTy = getTypeConverter()->convertType(op.getType());
824 mlir::Operation *newOp = lowerModule->getCXXABI().lowerGetRuntimeMember(
825 op, resTy, adaptor.getAddr(), adaptor.getMember(), rewriter);
826 rewriter.replaceOp(op, newOp);
827 return mlir::success();
830mlir::LogicalResult CIRVTableGetTypeInfoOpABILowering::matchAndRewrite(
831 cir::VTableGetTypeInfoOp op, OpAdaptor adaptor,
832 mlir::ConversionPatternRewriter &rewriter)
const {
833 mlir::Value loweredResult =
834 lowerModule->getCXXABI().lowerVTableGetTypeInfo(op, rewriter);
835 rewriter.replaceOp(op, loweredResult);
836 return mlir::success();
845 CIRABITypeConverter(mlir::MLIRContext &ctx, mlir::DataLayout &dataLayout,
846 cir::LowerModule &lowerModule)
847 : RecordRewritingTypeConverter(ctx) {
848 addConversion([&](cir::DataMemberType type) -> mlir::Type {
851 return convertType(abiType);
853 addConversion([&](cir::MethodType type) -> mlir::Type {
855 return convertType(abiType);
862 bool typeMayChange(mlir::Type type)
const override {
863 return mlir::isa<cir::DataMemberType, cir::MethodType>(type);
870 const mlir::TypeConverter &typeConverter) {
871 target.addLegalOp<mlir::ModuleOp>();
876 target.addDynamicallyLegalDialect<cir::CIRDialect>(
877 [&typeConverter](mlir::Operation *op) {
878 if (!typeConverter.isLegal(op))
881 bool attrs = areCXXABIInherentAttrsLegal(op, typeConverter);
884 std::all_of(op->getRegions().begin(), op->getRegions().end(),
885 [&typeConverter](mlir::Region ®ion) {
886 return typeConverter.isLegal(®ion);
890 target.addDynamicallyLegalDialect<mlir::acc::OpenACCDialect>(
891 [&typeConverter](mlir::Operation *op) {
892 if (!typeConverter.isLegal(op))
895 bool attrs = areCXXABIInherentAttrsLegal(op, typeConverter);
898 std::all_of(op->getRegions().begin(), op->getRegions().end(),
899 [&typeConverter](mlir::Region ®ion) {
900 return typeConverter.isLegal(®ion);
906 target.addDynamicallyLegalOp<cir::CastOp>([&typeConverter](cir::CastOp op) {
907 if (op.getSrc().getType() == op.getType()) {
908 switch (op.getKind()) {
909 case cir::CastKind::bitcast:
910 case cir::CastKind::address_space:
911 case cir::CastKind::float_complex:
912 case cir::CastKind::int_complex:
918 if (!typeConverter.isLegal(op.getOperation()))
922 return areCXXABIInherentAttrsLegal(op, typeConverter);
926 target.addDynamicallyLegalOp<cir::FuncOp>([&typeConverter](cir::FuncOp op) {
927 bool attrs = areCXXABIInherentAttrsLegal(op, typeConverter);
929 return attrs && typeConverter.isLegal(op.getFunctionType());
931 target.addDynamicallyLegalOp<cir::GlobalOp>(
932 [&typeConverter](cir::GlobalOp op) {
933 return typeConverter.isLegal(op.getSymType());
937 target.addIllegalOp<cir::DeleteArrayOp>();
938 target.addIllegalOp<cir::DynamicCastOp>();
939 target.addIllegalOp<cir::VTableGetTypeInfoOp>();
946void CXXABILoweringPass::runOnOperation() {
947 auto mod = mlir::cast<mlir::ModuleOp>(getOperation());
948 mlir::MLIRContext *ctx = mod.getContext();
951 assert(lowerModule &&
"LowerModule shouldn't be null");
952 if (!lowerModule->hasTarget()) {
953 mod.emitError() <<
getArgument() <<
" requires a module with a supported '"
954 << cir::CIRDialect::getTripleAttrName() <<
"' attribute";
955 return signalPassFailure();
958 if (!lowerModule->hasCXXABI()) {
959 mod.emitError() <<
"C++ ABI '"
961 lowerModule->getCXXABIKind())
962 <<
"' is not yet supported by CIR";
963 return signalPassFailure();
966 mlir::DataLayout dataLayout(mod);
967 CIRABITypeConverter typeConverter(*ctx, dataLayout, *lowerModule);
969 mlir::RewritePatternSet patterns(ctx);
970 patterns.add<CIRGenericCXXABILoweringPattern>(patterns.getContext(),
973#define GET_ABI_LOWERING_PATTERNS_LIST
974#include "clang/CIR/Dialect/IR/CIRLowering.inc"
975#undef GET_ABI_LOWERING_PATTERNS_LIST
976 >(patterns.getContext(), typeConverter, dataLayout, *lowerModule);
978 mlir::ConversionTarget target(*ctx);
981 llvm::SmallVector<mlir::Operation *> ops;
987 mlir::ConversionConfig config;
988 config.allowPatternRollback =
false;
989 if (failed(mlir::applyPartialConversion(ops, target, std::move(patterns),
993 typeConverter.restoreRecordTypeNames();
997 return std::make_unique<CXXABILoweringPass>();
#define CXX_ABI_ALWAYS_LEGAL_ATTRS
static void populateCXXABIConversionTarget(mlir::ConversionTarget &target, const mlir::TypeConverter &typeConverter)
static mlir::TypedAttr lowerInitialValue(const LowerModule *lowerModule, const mlir::DataLayout &layout, const mlir::TypeConverter &tc, mlir::Type ty, mlir::Attribute initVal)
static const TemplateArgument & getArgument(const TemplateArgument &A)
virtual mlir::Type lowerMethodType(cir::MethodType type, const mlir::TypeConverter &typeConverter) const =0
Lower the given member function pointer type to its ABI type.
virtual mlir::TypedAttr lowerDataMemberConstant(cir::DataMemberAttr attr, const mlir::DataLayout &layout, const mlir::TypeConverter &typeConverter) const =0
Lower the given data member pointer constant to a constant of the ABI type.
virtual mlir::TypedAttr lowerDataMemberOffsetConstant(cir::DataMemberOffsetAttr attr, const mlir::DataLayout &layout, const mlir::TypeConverter &typeConverter) const =0
Lower the given by-offset data member pointer constant (used for members with no CIR field index,...
virtual mlir::TypedAttr lowerMethodConstant(cir::MethodAttr attr, const mlir::DataLayout &layout, const mlir::TypeConverter &typeConverter) const =0
Lower the given member function pointer constant to a constant of the ABI type.
virtual mlir::Type lowerDataMemberType(cir::DataMemberType type, const mlir::TypeConverter &typeConverter) const =0
Lower the given data member pointer type to its ABI type.
void readArrayCookie(mlir::Location loc, mlir::Value elementPtr, clang::CharUnits elementAlign, const mlir::DataLayout &dataLayout, CIRBaseBuilderTy &builder, mlir::Value &numElements, mlir::Value &allocPtr, clang::CharUnits &cookieSize) const
Read the array cookie for a dynamically-allocated array whose first element is at elementPtr.
CIRCXXABI & getCXXABI() const
A type converter that converts the types nested in pointers, arrays, functions and records.
This is an opaque type for sizes expressed in character units.
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
static constexpr CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
static const auto & getSpelling(Kind ABIKind)
void collectUnreachable(mlir::Operation *parent, llvm::SmallVectorImpl< mlir::Operation * > &ops)
Collect ops in blocks that are unreachable from their region's entry, appending them to ops.
std::unique_ptr< LowerModule > createLowerModule(mlir::ModuleOp module)
const internal::VariadicAllOfMatcher< Attr > attr
bool isa(CodeGen::Address addr)
@ Default
Set to the current date and time.
std::unique_ptr< Pass > createCXXABILoweringPass()
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t