xref: /llvm-project/mlir/lib/IR/Dialect.cpp (revision 1a36588ec64ae8576e531e6f0b49eadb90ab0b11)
1 //===- Dialect.cpp - Dialect implementation -------------------------------===//
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 #include "mlir/IR/Dialect.h"
10 #include "mlir/IR/BuiltinDialect.h"
11 #include "mlir/IR/Diagnostics.h"
12 #include "mlir/IR/DialectImplementation.h"
13 #include "mlir/IR/DialectInterface.h"
14 #include "mlir/IR/ExtensibleDialect.h"
15 #include "mlir/IR/MLIRContext.h"
16 #include "mlir/IR/Operation.h"
17 #include "llvm/ADT/MapVector.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/ManagedStatic.h"
21 #include "llvm/Support/Regex.h"
22 
23 #define DEBUG_TYPE "dialect"
24 
25 using namespace mlir;
26 using namespace detail;
27 
28 //===----------------------------------------------------------------------===//
29 // Dialect
30 //===----------------------------------------------------------------------===//
31 
32 Dialect::Dialect(StringRef name, MLIRContext *context, TypeID id)
33     : name(name), dialectID(id), context(context) {
34   assert(isValidNamespace(name) && "invalid dialect namespace");
35 }
36 
37 Dialect::~Dialect() = default;
38 
39 /// Verify an attribute from this dialect on the argument at 'argIndex' for
40 /// the region at 'regionIndex' on the given operation. Returns failure if
41 /// the verification failed, success otherwise. This hook may optionally be
42 /// invoked from any operation containing a region.
43 LogicalResult Dialect::verifyRegionArgAttribute(Operation *, unsigned, unsigned,
44                                                 NamedAttribute) {
45   return success();
46 }
47 
48 /// Verify an attribute from this dialect on the result at 'resultIndex' for
49 /// the region at 'regionIndex' on the given operation. Returns failure if
50 /// the verification failed, success otherwise. This hook may optionally be
51 /// invoked from any operation containing a region.
52 LogicalResult Dialect::verifyRegionResultAttribute(Operation *, unsigned,
53                                                    unsigned, NamedAttribute) {
54   return success();
55 }
56 
57 /// Parse an attribute registered to this dialect.
58 Attribute Dialect::parseAttribute(DialectAsmParser &parser, Type type) const {
59   parser.emitError(parser.getNameLoc())
60       << "dialect '" << getNamespace()
61       << "' provides no attribute parsing hook";
62   return Attribute();
63 }
64 
65 /// Parse a type registered to this dialect.
66 Type Dialect::parseType(DialectAsmParser &parser) const {
67   // If this dialect allows unknown types, then represent this with OpaqueType.
68   if (allowsUnknownTypes()) {
69     StringAttr ns = StringAttr::get(getContext(), getNamespace());
70     return OpaqueType::get(ns, parser.getFullSymbolSpec());
71   }
72 
73   parser.emitError(parser.getNameLoc())
74       << "dialect '" << getNamespace() << "' provides no type parsing hook";
75   return Type();
76 }
77 
78 Optional<Dialect::ParseOpHook>
79 Dialect::getParseOperationHook(StringRef opName) const {
80   return std::nullopt;
81 }
82 
83 llvm::unique_function<void(Operation *, OpAsmPrinter &printer)>
84 Dialect::getOperationPrinter(Operation *op) const {
85   assert(op->getDialect() == this &&
86          "Dialect hook invoked on non-dialect owned operation");
87   return nullptr;
88 }
89 
90 /// Utility function that returns if the given string is a valid dialect
91 /// namespace
92 bool Dialect::isValidNamespace(StringRef str) {
93   llvm::Regex dialectNameRegex("^[a-zA-Z_][a-zA-Z_0-9\\$]*$");
94   return dialectNameRegex.match(str);
95 }
96 
97 /// Register a set of dialect interfaces with this dialect instance.
98 void Dialect::addInterface(std::unique_ptr<DialectInterface> interface) {
99   auto it = registeredInterfaces.try_emplace(interface->getID(),
100                                              std::move(interface));
101   (void)it;
102   LLVM_DEBUG({
103     if (!it.second) {
104       llvm::dbgs() << "[" DEBUG_TYPE
105                       "] repeated interface registration for dialect "
106                    << getNamespace();
107     }
108   });
109 }
110 
111 //===----------------------------------------------------------------------===//
112 // Dialect Interface
113 //===----------------------------------------------------------------------===//
114 
115 DialectInterface::~DialectInterface() = default;
116 
117 MLIRContext *DialectInterface::getContext() const {
118   return dialect->getContext();
119 }
120 
121 DialectInterfaceCollectionBase::DialectInterfaceCollectionBase(
122     MLIRContext *ctx, TypeID interfaceKind) {
123   for (auto *dialect : ctx->getLoadedDialects()) {
124     if (auto *interface = dialect->getRegisteredInterface(interfaceKind)) {
125       interfaces.insert(interface);
126       orderedInterfaces.push_back(interface);
127     }
128   }
129 }
130 
131 DialectInterfaceCollectionBase::~DialectInterfaceCollectionBase() = default;
132 
133 /// Get the interface for the dialect of given operation, or null if one
134 /// is not registered.
135 const DialectInterface *
136 DialectInterfaceCollectionBase::getInterfaceFor(Operation *op) const {
137   return getInterfaceFor(op->getDialect());
138 }
139 
140 //===----------------------------------------------------------------------===//
141 // DialectExtension
142 //===----------------------------------------------------------------------===//
143 
144 DialectExtensionBase::~DialectExtensionBase() = default;
145 
146 //===----------------------------------------------------------------------===//
147 // DialectRegistry
148 //===----------------------------------------------------------------------===//
149 
150 DialectRegistry::DialectRegistry() { insert<BuiltinDialect>(); }
151 
152 DialectAllocatorFunctionRef
153 DialectRegistry::getDialectAllocator(StringRef name) const {
154   auto it = registry.find(name.str());
155   if (it == registry.end())
156     return nullptr;
157   return it->second.second;
158 }
159 
160 void DialectRegistry::insert(TypeID typeID, StringRef name,
161                              const DialectAllocatorFunction &ctor) {
162   auto inserted = registry.insert(
163       std::make_pair(std::string(name), std::make_pair(typeID, ctor)));
164   if (!inserted.second && inserted.first->second.first != typeID) {
165     llvm::report_fatal_error(
166         "Trying to register different dialects for the same namespace: " +
167         name);
168   }
169 }
170 
171 void DialectRegistry::insertDynamic(
172     StringRef name, const DynamicDialectPopulationFunction &ctor) {
173   // This TypeID marks dynamic dialects. We cannot give a TypeID for the
174   // dialect yet, since the TypeID of a dynamic dialect is defined at its
175   // construction.
176   TypeID typeID = TypeID::get<void>();
177 
178   // Create the dialect, and then call ctor, which allocates its components.
179   auto constructor = [nameStr = name.str(), ctor](MLIRContext *ctx) {
180     auto *dynDialect = ctx->getOrLoadDynamicDialect(
181         nameStr, [ctx, ctor](DynamicDialect *dialect) { ctor(ctx, dialect); });
182     assert(dynDialect && "Dynamic dialect creation unexpectedly failed");
183     return dynDialect;
184   };
185 
186   insert(typeID, name, constructor);
187 }
188 
189 void DialectRegistry::applyExtensions(Dialect *dialect) const {
190   MLIRContext *ctx = dialect->getContext();
191   StringRef dialectName = dialect->getNamespace();
192 
193   // Functor used to try to apply the given extension.
194   auto applyExtension = [&](const DialectExtensionBase &extension) {
195     ArrayRef<StringRef> dialectNames = extension.getRequiredDialects();
196 
197     // Handle the simple case of a single dialect name. In this case, the
198     // required dialect should be the current dialect.
199     if (dialectNames.size() == 1) {
200       if (dialectNames.front() == dialectName)
201         extension.apply(ctx, dialect);
202       return;
203     }
204 
205     // Otherwise, check to see if this extension requires this dialect.
206     const StringRef *nameIt = llvm::find(dialectNames, dialectName);
207     if (nameIt == dialectNames.end())
208       return;
209 
210     // If it does, ensure that all of the other required dialects have been
211     // loaded.
212     SmallVector<Dialect *> requiredDialects;
213     requiredDialects.reserve(dialectNames.size());
214     for (auto it = dialectNames.begin(), e = dialectNames.end(); it != e;
215          ++it) {
216       // The current dialect is known to be loaded.
217       if (it == nameIt) {
218         requiredDialects.push_back(dialect);
219         continue;
220       }
221       // Otherwise, check if it is loaded.
222       Dialect *loadedDialect = ctx->getLoadedDialect(*it);
223       if (!loadedDialect)
224         return;
225       requiredDialects.push_back(loadedDialect);
226     }
227     extension.apply(ctx, requiredDialects);
228   };
229 
230   for (const auto &extension : extensions)
231     applyExtension(*extension);
232 }
233 
234 void DialectRegistry::applyExtensions(MLIRContext *ctx) const {
235   // Functor used to try to apply the given extension.
236   auto applyExtension = [&](const DialectExtensionBase &extension) {
237     ArrayRef<StringRef> dialectNames = extension.getRequiredDialects();
238 
239     // Check to see if all of the dialects for this extension are loaded.
240     SmallVector<Dialect *> requiredDialects;
241     requiredDialects.reserve(dialectNames.size());
242     for (StringRef dialectName : dialectNames) {
243       Dialect *loadedDialect = ctx->getLoadedDialect(dialectName);
244       if (!loadedDialect)
245         return;
246       requiredDialects.push_back(loadedDialect);
247     }
248     extension.apply(ctx, requiredDialects);
249   };
250 
251   for (const auto &extension : extensions)
252     applyExtension(*extension);
253 }
254 
255 bool DialectRegistry::isSubsetOf(const DialectRegistry &rhs) const {
256   // Treat any extensions conservatively.
257   if (!extensions.empty())
258     return false;
259   // Check that the current dialects fully overlap with the dialects in 'rhs'.
260   return llvm::all_of(
261       registry, [&](const auto &it) { return rhs.registry.count(it.first); });
262 }
263