MLIR 24.0.0git
MLGOAddReflectionMap.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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
12#include "mlir/IR/Attributes.h"
13#include "mlir/IR/Builders.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/Support/Casting.h"
20#include "llvm/Support/FormatVariadic.h"
21#include "llvm/Support/raw_ostream.h"
22
23using namespace mlir;
24using namespace emitc;
25
26namespace mlir {
27namespace emitc {
28#define GEN_PASS_DEF_MLGOADDREFLECTIONMAPPASS
29#include "mlir/Dialect/EmitC/Transforms/Passes.h.inc"
30
31namespace {
32constexpr const char *mapLibraryHeader = "map";
33constexpr const char *stringLibraryHeader = "string";
34
35struct PatternMatchListener : public RewriterBase::Listener {
36 bool patternApplied = false;
37
38 void notifyOperationInserted(Operation *op,
39 OpBuilder::InsertPoint previous) override {
40 patternApplied = true;
41 }
42};
43
44IncludeOp addHeader(OpBuilder &builder, ModuleOp module, StringRef headerName) {
45 StringAttr includeAttr = builder.getStringAttr(headerName);
46 return IncludeOp::create(builder, module.getLoc(), includeAttr,
47 /*is_standard_include=*/builder.getUnitAttr());
48}
49
50class MLGOAddReflectionMapPass
51 : public impl::MLGOAddReflectionMapPassBase<MLGOAddReflectionMapPass> {
52 using MLGOAddReflectionMapPassBase::MLGOAddReflectionMapPassBase;
53 void runOnOperation() override {
54 mlir::ModuleOp moduleOp = getOperation();
55
56 RewritePatternSet patterns(&getContext());
57 populateMLGOAddReflectionMapPatterns(patterns, includedFieldAttrs);
58
59 PatternMatchListener listener;
60 walkAndApplyPatterns(moduleOp, std::move(patterns), &listener);
61
62 // If nothing was matched, no reflection maps were added, removing the need
63 // to add include headers for map and string
64 if (!listener.patternApplied)
65 return;
66
67 // Check if the map and/or string headers are already present
68 bool hasMapHdr = false;
69 bool hasStringHdr = false;
70 for (auto &op : *moduleOp.getBody()) {
71 IncludeOp includeOp = llvm::dyn_cast<IncludeOp>(op);
72 if (!includeOp)
73 continue;
74
75 if (includeOp.getIsStandardInclude()) {
76 auto include = includeOp.getInclude();
77
78 hasMapHdr |= include == mapLibraryHeader;
79 hasStringHdr |= include == stringLibraryHeader;
80 }
81
82 if (hasMapHdr && hasStringHdr)
83 return;
84 }
85
86 mlir::OpBuilder builder(moduleOp.getBody(), moduleOp.getBody()->begin());
87 if (!hasMapHdr)
88 addHeader(builder, moduleOp, mapLibraryHeader);
89
90 if (!hasStringHdr)
91 addHeader(builder, moduleOp, stringLibraryHeader);
92 }
93};
94
95} // namespace
96} // namespace emitc
97} // namespace mlir
98
99/// Rewrites a `emitc::ClassOp` to generate a reflection map of member fields
100/// and a lookup method.
101///
102/// Fields to be mapped are identified via `includedFieldAttrs` attributes
103/// (e.g., `emitc.field_ref`). Fields that do not have a matching attribute
104/// are omitted from the reflection map.
105///
106/// Before:
107/// ```mlir
108/// emitc.class @foo {
109/// emitc.field @fieldName0 : !emitc.array<1xf32> {emitc.field_ref =
110/// ["another_feature"]}
111/// emitc.func @bar() { return }
112/// }
113/// ```
114///
115/// After:
116/// ```mlir
117/// emitc.class @foo {
118/// emitc.field @fieldName0 : !emitc.array<1xf32> {emitc.field_ref =
119/// ["another_feature"]} emitc.field @reflectionMap : !emitc.opaque<"const
120/// std::map<std::string, std::pair<char*, size_t>>"> =
121/// #emitc.opaque<"{ { \"another_feature\",
122/// { reinterpret_cast<char*>(&fieldName0), sizeof(fieldName0) } } }">
123/// emitc.func @getBufferForName(%name: !emitc.opaque<"std::string">) ->
124/// !emitc.ptr<!emitc.opaque<"char">> {
125/// %map = get_field @reflectionMap : ...
126/// %entry = member_call_opaque %map "at"(%name) : ...
127/// %ptr = member %entry "first" : ...
128/// return %ptr : !emitc.ptr<!emitc.opaque<"char">>
129/// }
130/// emitc.func @bar() { return }
131/// }
132/// ```
137 : OpRewritePattern<ClassOp>(context),
139
140 LogicalResult matchAndRewrite(ClassOp classOp,
141 PatternRewriter &rewriter) const override {
142 MLIRContext *context = rewriter.getContext();
143
144 emitc::OpaqueType entryType =
145 emitc::OpaqueType::get(context, "std::pair<char*, size_t>");
146 emitc::OpaqueType mapType = emitc::OpaqueType::get(
147 context,
148 llvm::formatv("const std::map<std::string, {0}>", entryType.getValue())
149 .str());
150
151 // Collect the names of all FieldOps that have one of the attributes in
152 // includedFieldAttrs to use the first element of the array attribute
153 // as the reflection map key
154 std::vector<std::pair<StringRef, StringRef>> fieldNames;
155 classOp.walk([&](FieldOp fieldOp) {
156 for (const auto &attr : includedFieldAttrs) {
157 auto arrayAttr =
158 dyn_cast_if_present<ArrayAttr>(fieldOp->getDiscardableAttr(attr));
159
160 if (!arrayAttr)
161 continue;
162
163 if (!arrayAttr.empty() && isa<StringAttr>(arrayAttr[0])) {
164 fieldNames.emplace_back(cast<StringAttr>(arrayAttr[0]).getValue(),
165 fieldOp.getName());
166 return;
167 }
168 }
169 });
171 if (fieldNames.empty())
172 return failure();
174 // Create reflection map contents
175 std::string reflectionMapContents;
176 llvm::raw_string_ostream os(reflectionMapContents);
177 os << "{ ";
178 llvm::interleaveComma(fieldNames, os, [&](const auto &field) {
179 os << llvm::formatv(
180 "{ \"{0}\", { reinterpret_cast<char*>(&{1}), sizeof({1}) } }",
181 field.first, field.second);
182 });
183 os << " }";
184
185 // Set insertion point before the first function or after all fields
186 // if there are no functions within the class
187 auto funcs = classOp.getBlock().getOps<FuncOp>();
188 auto it = funcs.begin();
189 if (it != funcs.end())
190 rewriter.setInsertionPoint(*it);
191 else
192 rewriter.setInsertionPointToEnd(&classOp.getBlock());
193
194 // To generate the following C++ code
195 // const std::map<std::string, std::pair<char*, size_t>> reflectionMap = {
196 // { "another_feature",
197 // { reinterpret_cast<char*>(&fieldName0), sizeof(fieldName0) } },
198 // ...
199 // };
200 // This can be used to retrieve a pointer to the field contents and its
201 // byte size given the attribute string identifying the field
202 FieldOp reflectionMapField = FieldOp::create(
203 rewriter, classOp.getLoc(), rewriter.getStringAttr("reflectionMap"),
204 /*sym_visibility=*/nullptr, TypeAttr::get(mapType),
205 emitc::OpaqueAttr::get(context, reflectionMapContents));
206
207 // Create getBufferForName method
208 emitc::OpaqueType nameType =
209 emitc::OpaqueType::get(rewriter.getContext(), "std::string");
210 emitc::OpaqueType charType =
211 emitc::OpaqueType::get(rewriter.getContext(), "char");
212 emitc::PointerType valType =
213 emitc::PointerType::get(rewriter.getContext(), charType);
214 FuncOp getBufferForNameFunc = FuncOp::create(
215 rewriter, reflectionMapField->getLoc(), "getBufferForName",
216 FunctionType::get(rewriter.getContext(), {nameType}, {valType}));
217
218 Block *body =
219 rewriter.createBlock(&getBufferForNameFunc.getBody(), {}, {nameType},
220 {reflectionMapField->getLoc()});
221 rewriter.setInsertionPointToStart(body);
222 GetFieldOp mapField = GetFieldOp::create(
223 rewriter, reflectionMapField->getLoc(), mapType, "reflectionMap");
224 Value nameArg = body->getArgument(0);
225 MemberCallOpaqueOp lookupCall = MemberCallOpaqueOp::create(
226 rewriter, reflectionMapField->getLoc(), entryType, mapField.getResult(),
227 "at", ArrayAttr{}, ArrayAttr{}, ValueRange{nameArg});
228 MemberOp bufferPtr =
229 MemberOp::create(rewriter, reflectionMapField->getLoc(), valType,
230 "first", lookupCall.getResult(0));
231 ReturnOp::create(rewriter, reflectionMapField->getLoc(),
232 bufferPtr.getResult());
233
234 return success();
235 }
236
237private:
238 /// The names of the attributes on FieldOps that contain the field name
239 /// metadata for the reflection map. The pass matches the first attribute
240 /// present in the order they are specified in this list.
241 llvm::SmallVector<std::string> includedFieldAttrs;
242};
243
245 RewritePatternSet &patterns,
246 llvm::ArrayRef<std::string> includedFieldAttrs) {
247 patterns.add<MLGOAddReflectionMapClass>(patterns.getContext(),
248 includedFieldAttrs);
249}
return success()
b getContext())
Rewrites a emitc::ClassOp to generate a reflection map of member fields and a lookup method.
LogicalResult matchAndRewrite(ClassOp classOp, PatternRewriter &rewriter) const override
MLGOAddReflectionMapClass(MLIRContext *context, llvm::ArrayRef< std::string > includedFieldAttrs)
Block represents an ordered list of Operations.
Definition Block.h:34
BlockArgument getArgument(unsigned i)
Definition Block.h:154
UnitAttr getUnitAttr()
Definition Builders.cpp:106
StringAttr getStringAttr(const Twine &bytes)
Definition Builders.cpp:271
MLIRContext * getContext() const
Definition Builders.h:56
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
This class represents a saved insertion point.
Definition Builders.h:330
This class helps build Operations.
Definition Builders.h:210
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes={}, ArrayRef< Location > locs={})
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
Definition Builders.cpp:439
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition Builders.h:434
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
void setInsertionPointToEnd(Block *block)
Sets the insertion point to the end of the specified block.
Definition Builders.h:439
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
MLIRContext * getContext() const
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
::mlir::Pass::ListOption< std::string > includedFieldAttrs
void populateMLGOAddReflectionMapPatterns(RewritePatternSet &patterns, ArrayRef< std::string > includedFieldAttrs)
Include the generated interface declarations.
void walkAndApplyPatterns(Operation *op, const FrozenRewritePatternSet &patterns, RewriterBase::Listener *listener=nullptr)
A fast walk-based pattern rewrite driver.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})