17#include "mlir/IR/AttrTypeSubElements.h"
18#include "mlir/IR/PatternMatch.h"
19#include "mlir/Support/LLVM.h"
20#include "mlir/Transforms/DialectConversion.h"
31#define GEN_PASS_DEF_TARGETLOWERING
32#include "clang/CIR/Dialect/Passes.h.inc"
37struct TargetLoweringPass
38 :
public impl::TargetLoweringBase<TargetLoweringPass> {
39 TargetLoweringPass() =
default;
40 void runOnOperation()
override;
47 TargetLoweringTypeConverter(mlir::MLIRContext &ctx,
48 const cir::TargetLoweringInfo &targetInfo)
49 : RecordRewritingTypeConverter(ctx), targetInfo(targetInfo) {
50 addConversion([
this](cir::PointerType type) -> mlir::Type {
51 mlir::Type pointee = convertType(
type.getPointee());
54 mlir::ptr::MemorySpaceAttrInterface addrSpace =
type.getAddrSpace();
56 mlir::dyn_cast_if_present<cir::LangAddressSpaceAttr>(addrSpace))
57 addrSpace = lowerAddrSpace(
type.getContext(), langAS);
58 return cir::PointerType::get(
type.getContext(), pointee, addrSpace);
62 mlir::ptr::MemorySpaceAttrInterface
63 lowerAddrSpace(mlir::MLIRContext *ctx,
64 cir::LangAddressSpaceAttr langAS)
const {
66 targetInfo.getTargetAddrSpaceFromCIRAddrSpace(langAS.getValue());
69 return cir::TargetAddressSpaceAttr::get(ctx, targetAS);
73 mlir::Attribute convertAttr(mlir::Attribute attr)
const {
74 return attrReplacer.replace(attr);
78 bool typeMayChange(mlir::Type type)
const override {
79 auto ptrTy = mlir::dyn_cast<cir::PointerType>(type);
80 return ptrTy && mlir::isa_and_present<cir::LangAddressSpaceAttr>(
81 ptrTy.getAddrSpace());
85 const cir::TargetLoweringInfo &targetInfo;
86 mutable mlir::AttrTypeReplacer attrReplacer = [
this] {
87 mlir::AttrTypeReplacer replacer;
88 replacer.addReplacement(
89 [
this](mlir::Type type)
90 -> std::optional<std::pair<mlir::Type, mlir::WalkResult>> {
91 mlir::Type converted = convertType(type);
95 return std::make_pair(converted, mlir::WalkResult::skip());
104class CIRGenericTargetLoweringPattern :
public mlir::ConversionPattern {
106 CIRGenericTargetLoweringPattern(
107 mlir::MLIRContext *context,
108 const TargetLoweringTypeConverter &typeConverter)
109 : mlir::ConversionPattern(typeConverter, MatchAnyOpTypeTag(),
113 matchAndRewrite(mlir::Operation *op, llvm::ArrayRef<mlir::Value> operands,
114 mlir::ConversionPatternRewriter &rewriter)
const override {
116 if (llvm::isa<cir::FuncOp, cir::GlobalOp>(op))
117 return mlir::failure();
119 const mlir::TypeConverter *typeConverter = getTypeConverter();
120 assert(typeConverter &&
121 "CIRGenericTargetLoweringPattern requires a type converter");
122 bool operandsAndResultsLegal = typeConverter->isLegal(op);
124 std::all_of(op->getRegions().begin(), op->getRegions().end(),
125 [typeConverter](mlir::Region ®ion) {
126 return typeConverter->isLegal(®ion);
128 if (operandsAndResultsLegal && regionsLegal)
129 return mlir::failure();
131 assert(op->getNumRegions() == 0 &&
"CIRGenericTargetLoweringPattern cannot "
132 "deal with operations with regions");
134 mlir::OperationState loweredOpState(op->getLoc(), op->getName());
135 loweredOpState.addOperands(operands);
138 loweredOpState.propertiesAttr = op->getPropertiesAsAttribute();
139 loweredOpState.addAttributes(op->getDiscardableAttrDictionary().getValue());
141 loweredOpState.addSuccessors(op->getSuccessors());
143 llvm::SmallVector<mlir::Type> loweredResultTypes;
144 loweredResultTypes.reserve(op->getNumResults());
145 for (mlir::Type result : op->getResultTypes())
146 loweredResultTypes.push_back(typeConverter->convertType(result));
147 loweredOpState.addTypes(loweredResultTypes);
150 for (mlir::Region ®ion : op->getRegions()) {
152 rewriter.convertRegionTypes(®ion, *getTypeConverter())))
153 return mlir::failure();
155 for (mlir::Region ®ion : op->getRegions()) {
156 mlir::Region *loweredRegion = loweredOpState.addRegion();
157 rewriter.inlineRegionBefore(region, *loweredRegion, loweredRegion->end());
160 mlir::Operation *loweredOp = rewriter.create(loweredOpState);
163 const auto *tlTypeConverter =
164 static_cast<const TargetLoweringTypeConverter *
>(typeConverter);
165 loweredOp->getName().walkInherentAttrs(
166 loweredOp, [&](llvm::StringRef, mlir::Attribute &attr) {
167 attr = tlTypeConverter->convertAttr(attr);
169 rewriter.replaceOp(op, loweredOp);
170 return mlir::success();
177class CIRGlobalOpTargetLowering
178 :
public mlir::OpConversionPattern<cir::GlobalOp> {
180 CIRGlobalOpTargetLowering(mlir::MLIRContext *context,
181 const TargetLoweringTypeConverter &typeConverter)
182 : mlir::OpConversionPattern<cir::GlobalOp>(typeConverter, context,
186 matchAndRewrite(cir::GlobalOp op, OpAdaptor adaptor,
187 mlir::ConversionPatternRewriter &rewriter)
const override {
188 const auto *typeConverter =
189 static_cast<const TargetLoweringTypeConverter *
>(getTypeConverter());
190 mlir::Type loweredSymTy = typeConverter->convertType(op.getSymType());
192 return mlir::failure();
195 mlir::ptr::MemorySpaceAttrInterface addrSpace = op.getAddrSpaceAttr();
197 mlir::dyn_cast_if_present<cir::LangAddressSpaceAttr>(addrSpace))
198 addrSpace = typeConverter->lowerAddrSpace(op.getContext(), langAS);
201 if (loweredSymTy == op.getSymType() && addrSpace == op.getAddrSpaceAttr())
202 return mlir::failure();
204 auto newOp = mlir::cast<cir::GlobalOp>(rewriter.clone(*op.getOperation()));
205 newOp.setSymType(loweredSymTy);
206 newOp.setAddrSpaceAttr(addrSpace);
207 if (mlir::Attribute init = newOp.getInitialValueAttr())
208 newOp.setInitialValueAttr(typeConverter->convertAttr(init));
209 rewriter.replaceOp(op, newOp);
210 return mlir::success();
215class CIRFuncOpTargetLowering :
public mlir::OpConversionPattern<cir::FuncOp> {
217 using mlir::OpConversionPattern<cir::FuncOp>::OpConversionPattern;
220 matchAndRewrite(cir::FuncOp op, OpAdaptor adaptor,
221 mlir::ConversionPatternRewriter &rewriter)
const override {
222 cir::FuncType opFuncType = op.getFunctionType();
223 mlir::TypeConverter::SignatureConversion signatureConversion(
224 opFuncType.getNumInputs());
226 for (
const auto &[i, argType] : llvm::enumerate(opFuncType.getInputs())) {
227 mlir::Type loweredArgType = getTypeConverter()->convertType(argType);
229 return mlir::failure();
230 signatureConversion.addInputs(i, loweredArgType);
233 mlir::Type loweredReturnType =
234 getTypeConverter()->convertType(opFuncType.getReturnType());
235 if (!loweredReturnType)
236 return mlir::failure();
238 auto loweredFuncType = cir::FuncType::get(
239 signatureConversion.getConvertedTypes(), loweredReturnType,
240 opFuncType.getVarArg());
243 if (loweredFuncType == opFuncType)
244 return mlir::failure();
247 if (mlir::failed(rewriter.convertRegionTypes(
248 &op.getBody(), *getTypeConverter(), &signatureConversion)))
249 return mlir::failure();
251 cir::FuncOp loweredFuncOp = rewriter.cloneWithoutRegions(op);
252 loweredFuncOp.setFunctionType(loweredFuncType);
253 rewriter.inlineRegionBefore(op.getBody(), loweredFuncOp.getBody(),
254 loweredFuncOp.end());
256 rewriter.eraseOp(op);
257 return mlir::success();
266 mlir::cast_if_present<cir::SyncScopeKindAttr>(op->getAttr(
"sync_scope"));
268 cir::SyncScopeKind convertedSyncScope =
270 syncScopeAttr.getValue());
271 op->setAttr(
"sync_scope", cir::SyncScopeKindAttr::get(op->getContext(),
272 convertedSyncScope));
278 const mlir::TypeConverter &tc) {
279 target.addLegalOp<mlir::ModuleOp>();
281 target.addDynamicallyLegalDialect<cir::CIRDialect>(
282 [&tc](mlir::Operation *op) {
286 op->getRegions().begin(), op->getRegions().end(),
287 [&tc](mlir::Region ®ion) { return tc.isLegal(®ion); });
290 target.addDynamicallyLegalOp<cir::FuncOp>(
291 [&tc](cir::FuncOp op) {
return tc.isLegal(op.getFunctionType()); });
293 target.addDynamicallyLegalOp<cir::GlobalOp>([&tc](cir::GlobalOp op) {
294 if (!tc.isLegal(op.getSymType()))
296 return !mlir::isa_and_present<cir::LangAddressSpaceAttr>(
297 op.getAddrSpaceAttr());
301void TargetLoweringPass::runOnOperation() {
302 auto mod = mlir::cast<mlir::ModuleOp>(getOperation());
306 mod.emitWarning(
"Cannot create a CIR lower module, skipping the ")
311 const auto &targetInfo = lowerModule->getTargetLoweringInfo();
313 mod->walk([&](mlir::Operation *op) {
314 if (mlir::isa<cir::LoadOp, cir::StoreOp, cir::AtomicXchgOp,
315 cir::AtomicCmpXchgOp, cir::AtomicFetchOp>(op))
320 TargetLoweringTypeConverter typeConverter(*mod.getContext(), targetInfo);
322 mlir::RewritePatternSet patterns(mod.getContext());
323 patterns.add<CIRGlobalOpTargetLowering>(mod.getContext(), typeConverter);
324 patterns.add<CIRFuncOpTargetLowering>(typeConverter, mod.getContext());
325 patterns.add<CIRGenericTargetLoweringPattern>(mod.getContext(),
328 mlir::ConversionTarget target(*mod.getContext());
331 llvm::SmallVector<mlir::Operation *> ops;
337 mlir::ConversionConfig config;
338 config.allowPatternRollback =
false;
339 if (failed(mlir::applyPartialConversion(ops, target, std::move(patterns),
343 typeConverter.restoreRecordTypeNames();
347 return std::make_unique<TargetLoweringPass>();
static void populateTargetLoweringConversionTarget(mlir::ConversionTarget &target, const mlir::TypeConverter &tc)
static void convertSyncScopeIfPresent(mlir::Operation *op, cir::LowerModule &lowerModule)
const TargetLoweringInfo & getTargetLoweringInfo()
A type converter that converts the types nested in pointers, arrays, functions and records.
virtual cir::SyncScopeKind convertSyncScope(cir::SyncScopeKind syncScope) const
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)
std::unique_ptr< Pass > createTargetLoweringPass()