clang 24.0.0git
TargetLowering.cpp
Go to the documentation of this file.
1//===- TargetLowering.cpp -------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the cir-target-lowering pass.
10//
11//===----------------------------------------------------------------------===//
12
13#include "RecordTypeConverter.h"
16
17#include "mlir/IR/AttrTypeSubElements.h"
18#include "mlir/IR/PatternMatch.h"
19#include "mlir/Support/LLVM.h"
20#include "mlir/Transforms/DialectConversion.h"
26
27using namespace mlir;
28using namespace cir;
29
30namespace mlir {
31#define GEN_PASS_DEF_TARGETLOWERING
32#include "clang/CIR/Dialect/Passes.h.inc"
33} // namespace mlir
34
35namespace {
36
37struct TargetLoweringPass
38 : public impl::TargetLoweringBase<TargetLoweringPass> {
39 TargetLoweringPass() = default;
40 void runOnOperation() override;
41};
42
43/// Converts LangAddressSpaceAttr → TargetAddressSpaceAttr inside types,
44/// rebuilding only records that reach a language address space.
45class TargetLoweringTypeConverter : public cir::RecordRewritingTypeConverter {
46public:
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());
52 if (!pointee)
53 return {};
54 mlir::ptr::MemorySpaceAttrInterface addrSpace = type.getAddrSpace();
55 if (auto langAS =
56 mlir::dyn_cast_if_present<cir::LangAddressSpaceAttr>(addrSpace))
57 addrSpace = lowerAddrSpace(type.getContext(), langAS);
58 return cir::PointerType::get(type.getContext(), pointee, addrSpace);
59 });
60 }
61
62 mlir::ptr::MemorySpaceAttrInterface
63 lowerAddrSpace(mlir::MLIRContext *ctx,
64 cir::LangAddressSpaceAttr langAS) const {
65 unsigned targetAS =
66 targetInfo.getTargetAddrSpaceFromCIRAddrSpace(langAS.getValue());
67 if (targetAS == 0)
68 return {};
69 return cir::TargetAddressSpaceAttr::get(ctx, targetAS);
70 }
71
72 /// Convert the types nested in \p attr, e.g. the type of a constant.
73 mlir::Attribute convertAttr(mlir::Attribute attr) const {
74 return attrReplacer.replace(attr);
75 }
76
77protected:
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());
82 }
83
84private:
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);
92 if (!converted)
93 return std::nullopt;
94 // Already converted; don't walk into it.
95 return std::make_pair(converted, mlir::WalkResult::skip());
96 });
97 return replacer;
98 }();
99};
100
101/// A generic target lowering pattern that matches any CIR op whose operand or
102/// result types need address space conversion. Clones the op with converted
103/// types.
104class CIRGenericTargetLoweringPattern : public mlir::ConversionPattern {
105public:
106 CIRGenericTargetLoweringPattern(
107 mlir::MLIRContext *context,
108 const TargetLoweringTypeConverter &typeConverter)
109 : mlir::ConversionPattern(typeConverter, MatchAnyOpTypeTag(),
110 /*benefit=*/1, context) {}
111
112 mlir::LogicalResult
113 matchAndRewrite(mlir::Operation *op, llvm::ArrayRef<mlir::Value> operands,
114 mlir::ConversionPatternRewriter &rewriter) const override {
115 // Do not match on operations that have dedicated lowering patterns.
116 if (llvm::isa<cir::FuncOp, cir::GlobalOp>(op))
117 return mlir::failure();
118
119 const mlir::TypeConverter *typeConverter = getTypeConverter();
120 assert(typeConverter &&
121 "CIRGenericTargetLoweringPattern requires a type converter");
122 bool operandsAndResultsLegal = typeConverter->isLegal(op);
123 bool regionsLegal =
124 std::all_of(op->getRegions().begin(), op->getRegions().end(),
125 [typeConverter](mlir::Region &region) {
126 return typeConverter->isLegal(&region);
127 });
128 if (operandsAndResultsLegal && regionsLegal)
129 return mlir::failure();
130
131 assert(op->getNumRegions() == 0 && "CIRGenericTargetLoweringPattern cannot "
132 "deal with operations with regions");
133
134 mlir::OperationState loweredOpState(op->getLoc(), op->getName());
135 loweredOpState.addOperands(operands);
136
137 // Preserve auxiliary metadata verbatim.
138 loweredOpState.propertiesAttr = op->getPropertiesAsAttribute();
139 loweredOpState.addAttributes(op->getDiscardableAttrDictionary().getValue());
140
141 loweredOpState.addSuccessors(op->getSuccessors());
142
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);
148
149 for (mlir::Region &region : op->getRegions()) {
150 mlir::Region *loweredRegion = loweredOpState.addRegion();
151 rewriter.inlineRegionBefore(region, *loweredRegion, loweredRegion->end());
152 if (mlir::failed(
153 rewriter.convertRegionTypes(loweredRegion, *getTypeConverter())))
154 return mlir::failure();
155 }
156
157 mlir::Operation *loweredOp = rewriter.create(loweredOpState);
158 // Keep inherent attributes (e.g. allocaType, constants) in sync with the
159 // converted types.
160 const auto *tlTypeConverter =
161 static_cast<const TargetLoweringTypeConverter *>(typeConverter);
162 loweredOp->getName().walkInherentAttrs(
163 loweredOp, [&](llvm::StringRef, mlir::Attribute &attr) {
164 attr = tlTypeConverter->convertAttr(attr);
165 });
166 rewriter.replaceOp(op, loweredOp);
167 return mlir::success();
168 }
169};
170
171/// Pattern to lower GlobalOp address space attributes. GlobalOp carries
172/// addr_space as a standalone attribute (not inside a type), so the
173/// TypeConverter won't reach it automatically.
174class CIRGlobalOpTargetLowering
175 : public mlir::OpConversionPattern<cir::GlobalOp> {
176public:
177 CIRGlobalOpTargetLowering(mlir::MLIRContext *context,
178 const TargetLoweringTypeConverter &typeConverter)
179 : mlir::OpConversionPattern<cir::GlobalOp>(typeConverter, context,
180 /*benefit=*/1) {}
181
182 mlir::LogicalResult
183 matchAndRewrite(cir::GlobalOp op, OpAdaptor adaptor,
184 mlir::ConversionPatternRewriter &rewriter) const override {
185 const auto *typeConverter =
186 static_cast<const TargetLoweringTypeConverter *>(getTypeConverter());
187 mlir::Type loweredSymTy = typeConverter->convertType(op.getSymType());
188 if (!loweredSymTy)
189 return mlir::failure();
190
191 // Convert the addr_space attribute.
192 mlir::ptr::MemorySpaceAttrInterface addrSpace = op.getAddrSpaceAttr();
193 if (auto langAS =
194 mlir::dyn_cast_if_present<cir::LangAddressSpaceAttr>(addrSpace))
195 addrSpace = typeConverter->lowerAddrSpace(op.getContext(), langAS);
196
197 // Only rewrite if something actually changed.
198 if (loweredSymTy == op.getSymType() && addrSpace == op.getAddrSpaceAttr())
199 return mlir::failure();
200
201 auto newOp = mlir::cast<cir::GlobalOp>(rewriter.clone(*op.getOperation()));
202 newOp.setSymType(loweredSymTy);
203 newOp.setAddrSpaceAttr(addrSpace);
204 if (mlir::Attribute init = newOp.getInitialValueAttr())
205 newOp.setInitialValueAttr(typeConverter->convertAttr(init));
206 rewriter.replaceOp(op, newOp);
207 return mlir::success();
208 }
209};
210
211/// Pattern to lower FuncOp types that contain address spaces.
212class CIRFuncOpTargetLowering : public mlir::OpConversionPattern<cir::FuncOp> {
213public:
214 using mlir::OpConversionPattern<cir::FuncOp>::OpConversionPattern;
215
216 mlir::LogicalResult
217 matchAndRewrite(cir::FuncOp op, OpAdaptor adaptor,
218 mlir::ConversionPatternRewriter &rewriter) const override {
219 cir::FuncType opFuncType = op.getFunctionType();
220 mlir::TypeConverter::SignatureConversion signatureConversion(
221 opFuncType.getNumInputs());
222
223 for (const auto &[i, argType] : llvm::enumerate(opFuncType.getInputs())) {
224 mlir::Type loweredArgType = getTypeConverter()->convertType(argType);
225 if (!loweredArgType)
226 return mlir::failure();
227 signatureConversion.addInputs(i, loweredArgType);
228 }
229
230 mlir::Type loweredReturnType =
231 getTypeConverter()->convertType(opFuncType.getReturnType());
232 if (!loweredReturnType)
233 return mlir::failure();
234
235 auto loweredFuncType = cir::FuncType::get(
236 signatureConversion.getConvertedTypes(), loweredReturnType,
237 /*isVarArg=*/opFuncType.getVarArg());
238
239 // Nothing changed, skip.
240 if (loweredFuncType == opFuncType)
241 return mlir::failure();
242
243 cir::FuncOp loweredFuncOp = rewriter.cloneWithoutRegions(op);
244 loweredFuncOp.setFunctionType(loweredFuncType);
245 rewriter.inlineRegionBefore(op.getBody(), loweredFuncOp.getBody(),
246 loweredFuncOp.end());
247 if (mlir::failed(rewriter.convertRegionTypes(&loweredFuncOp.getBody(),
248 *getTypeConverter(),
249 &signatureConversion)))
250 return mlir::failure();
251
252 rewriter.eraseOp(op);
253 return mlir::success();
254 }
255};
256
257} // namespace
258
259static void convertSyncScopeIfPresent(mlir::Operation *op,
260 cir::LowerModule &lowerModule) {
261 auto syncScopeAttr =
262 mlir::cast_if_present<cir::SyncScopeKindAttr>(op->getAttr("sync_scope"));
263 if (syncScopeAttr) {
264 cir::SyncScopeKind convertedSyncScope =
266 syncScopeAttr.getValue());
267 op->setAttr("sync_scope", cir::SyncScopeKindAttr::get(op->getContext(),
268 convertedSyncScope));
269 }
270}
271
272static void
273populateTargetLoweringConversionTarget(mlir::ConversionTarget &target,
274 const mlir::TypeConverter &tc) {
275 target.addLegalOp<mlir::ModuleOp>();
276
277 target.addDynamicallyLegalDialect<cir::CIRDialect>(
278 [&tc](mlir::Operation *op) {
279 if (!tc.isLegal(op))
280 return false;
281 return std::all_of(
282 op->getRegions().begin(), op->getRegions().end(),
283 [&tc](mlir::Region &region) { return tc.isLegal(&region); });
284 });
285
286 target.addDynamicallyLegalOp<cir::FuncOp>(
287 [&tc](cir::FuncOp op) { return tc.isLegal(op.getFunctionType()); });
288
289 target.addDynamicallyLegalOp<cir::GlobalOp>([&tc](cir::GlobalOp op) {
290 if (!tc.isLegal(op.getSymType()))
291 return false;
292 return !mlir::isa_and_present<cir::LangAddressSpaceAttr>(
293 op.getAddrSpaceAttr());
294 });
295}
296
297void TargetLoweringPass::runOnOperation() {
298 auto mod = mlir::cast<mlir::ModuleOp>(getOperation());
299 std::unique_ptr<cir::LowerModule> lowerModule = cir::createLowerModule(mod);
300 // If lower module is not available, skip the target lowering pass.
301 if (!lowerModule) {
302 mod.emitWarning("Cannot create a CIR lower module, skipping the ")
303 << getName() << " pass";
304 return;
305 }
306
307 const auto &targetInfo = lowerModule->getTargetLoweringInfo();
308
309 mod->walk([&](mlir::Operation *op) {
310 if (mlir::isa<cir::LoadOp, cir::StoreOp, cir::AtomicXchgOp,
311 cir::AtomicCmpXchgOp, cir::AtomicFetchOp>(op))
312 convertSyncScopeIfPresent(op, *lowerModule);
313 });
314
315 // Address space conversion: LangAddressSpaceAttr → TargetAddressSpaceAttr.
316 TargetLoweringTypeConverter typeConverter(*mod.getContext(), targetInfo);
317
318 mlir::RewritePatternSet patterns(mod.getContext());
319 patterns.add<CIRGlobalOpTargetLowering>(mod.getContext(), typeConverter);
320 patterns.add<CIRFuncOpTargetLowering>(typeConverter, mod.getContext());
321 patterns.add<CIRGenericTargetLoweringPattern>(mod.getContext(),
322 typeConverter);
323
324 mlir::ConversionTarget target(*mod.getContext());
325 populateTargetLoweringConversionTarget(target, typeConverter);
326
327 llvm::SmallVector<mlir::Operation *> ops;
328 ops.push_back(mod);
329 cir::collectUnreachable(mod, ops);
330
331 if (failed(mlir::applyPartialConversion(ops, target, std::move(patterns))))
332 signalPassFailure();
333
334 typeConverter.restoreRecordTypeNames();
335}
336
337std::unique_ptr<Pass> mlir::createTargetLoweringPass() {
338 return std::make_unique<TargetLoweringPass>();
339}
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)
Definition HeaderFile.h:38
std::unique_ptr< Pass > createTargetLoweringPass()