| 1 | //===- AttrOrTypeDefGen.cpp - MLIR AttrOrType definitions generator -------===// |
| 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 "AttrOrTypeFormatGen.h" |
| 10 | #include "CppGenUtilities.h" |
| 11 | #include "mlir/TableGen/AttrOrTypeDef.h" |
| 12 | #include "mlir/TableGen/Class.h" |
| 13 | #include "mlir/TableGen/Format.h" |
| 14 | #include "mlir/TableGen/GenInfo.h" |
| 15 | #include "mlir/TableGen/Interfaces.h" |
| 16 | #include "llvm/ADT/SmallVectorExtras.h" |
| 17 | #include "llvm/ADT/StringSet.h" |
| 18 | #include "llvm/Support/CommandLine.h" |
| 19 | #include "llvm/TableGen/CodeGenHelpers.h" |
| 20 | #include "llvm/TableGen/Error.h" |
| 21 | #include "llvm/TableGen/TableGenBackend.h" |
| 22 | |
| 23 | #define DEBUG_TYPE "mlir-tblgen-attrortypedefgen" |
| 24 | |
| 25 | using namespace mlir; |
| 26 | using namespace mlir::tblgen; |
| 27 | using llvm::Record; |
| 28 | using llvm::RecordKeeper; |
| 29 | |
| 30 | //===----------------------------------------------------------------------===// |
| 31 | // Utility Functions |
| 32 | //===----------------------------------------------------------------------===// |
| 33 | |
| 34 | /// Find all the AttrOrTypeDef for the specified dialect. If no dialect |
| 35 | /// specified and can only find one dialect's defs, use that. |
| 36 | static void collectAllDefs(StringRef selectedDialect, |
| 37 | ArrayRef<const Record *> records, |
| 38 | SmallVectorImpl<AttrOrTypeDef> &resultDefs) { |
| 39 | // Nothing to do if no defs were found. |
| 40 | if (records.empty()) |
| 41 | return; |
| 42 | |
| 43 | auto defs = llvm::map_range( |
| 44 | C&: records, F: [&](const Record *rec) { return AttrOrTypeDef(rec); }); |
| 45 | if (selectedDialect.empty()) { |
| 46 | // If a dialect was not specified, ensure that all found defs belong to the |
| 47 | // same dialect. |
| 48 | if (!llvm::all_equal(Range: llvm::map_range( |
| 49 | C&: defs, F: [](const auto &def) { return def.getDialect(); }))) { |
| 50 | llvm::PrintFatalError(Msg: "defs belonging to more than one dialect. Must " |
| 51 | "select one via '--(attr|type)defs-dialect'" ); |
| 52 | } |
| 53 | resultDefs.assign(in_start: defs.begin(), in_end: defs.end()); |
| 54 | } else { |
| 55 | // Otherwise, generate the defs that belong to the selected dialect. |
| 56 | auto dialectDefs = llvm::make_filter_range(Range&: defs, Pred: [&](const auto &def) { |
| 57 | return def.getDialect().getName() == selectedDialect; |
| 58 | }); |
| 59 | resultDefs.assign(in_start: dialectDefs.begin(), in_end: dialectDefs.end()); |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | //===----------------------------------------------------------------------===// |
| 64 | // DefGen |
| 65 | //===----------------------------------------------------------------------===// |
| 66 | |
| 67 | namespace { |
| 68 | class DefGen { |
| 69 | public: |
| 70 | /// Create the attribute or type class. |
| 71 | DefGen(const AttrOrTypeDef &def); |
| 72 | |
| 73 | void emitDecl(raw_ostream &os) const { |
| 74 | if (storageCls && def.genStorageClass()) { |
| 75 | llvm::NamespaceEmitter ns(os, def.getStorageNamespace()); |
| 76 | os << "struct " << def.getStorageClassName() << ";\n" ; |
| 77 | } |
| 78 | defCls.writeDeclTo(rawOs&: os); |
| 79 | } |
| 80 | void emitDef(raw_ostream &os) const { |
| 81 | if (storageCls && def.genStorageClass()) { |
| 82 | llvm::NamespaceEmitter ns(os, def.getStorageNamespace()); |
| 83 | storageCls->writeDeclTo(rawOs&: os); // everything is inline |
| 84 | } |
| 85 | defCls.writeDefTo(rawOs&: os); |
| 86 | } |
| 87 | |
| 88 | /// Returns the headers that need to be included for the class to parse. |
| 89 | ArrayRef<StringRef> getRequiredIncludes() const { return requiredIncludes; } |
| 90 | |
| 91 | private: |
| 92 | /// Add traits from the TableGen definition to the class. |
| 93 | void createParentWithTraits(); |
| 94 | /// Emit top-level declarations: using declarations and any extra class |
| 95 | /// declarations. |
| 96 | void emitTopLevelDeclarations(); |
| 97 | /// Emit the function that returns the type or attribute name. |
| 98 | void emitName(); |
| 99 | /// Emit the dialect name as a static member variable. |
| 100 | void emitDialectName(); |
| 101 | /// Emit attribute or type builders. |
| 102 | void emitBuilders(); |
| 103 | /// Emit a verifier declaration for custom verification (impl. provided by |
| 104 | /// the users). |
| 105 | void emitVerifierDecl(); |
| 106 | /// Emit a verifier that checks type constraints. |
| 107 | void emitInvariantsVerifierImpl(); |
| 108 | /// Emit an entry poiunt for verification that calls the invariants and |
| 109 | /// custom verifier. |
| 110 | void emitInvariantsVerifier(bool hasImpl, bool hasCustomVerifier); |
| 111 | /// Emit parsers and printers. |
| 112 | void emitParserPrinter(); |
| 113 | /// Emit parameter accessors, if required. |
| 114 | void emitAccessors(); |
| 115 | /// Emit interface methods. |
| 116 | void emitInterfaceMethods(); |
| 117 | |
| 118 | //===--------------------------------------------------------------------===// |
| 119 | // Builder Emission |
| 120 | |
| 121 | /// Emit the default builder `Attribute::get` |
| 122 | void emitDefaultBuilder(); |
| 123 | /// Emit the checked builder `Attribute::getChecked` |
| 124 | void emitCheckedBuilder(); |
| 125 | /// Emit a custom builder. |
| 126 | void emitCustomBuilder(const AttrOrTypeBuilder &builder); |
| 127 | /// Emit a checked custom builder. |
| 128 | void emitCheckedCustomBuilder(const AttrOrTypeBuilder &builder); |
| 129 | |
| 130 | //===--------------------------------------------------------------------===// |
| 131 | // Interface Method Emission |
| 132 | |
| 133 | /// Emit methods for a trait. |
| 134 | void emitTraitMethods(const InterfaceTrait &trait); |
| 135 | /// Emit a trait method. |
| 136 | void emitTraitMethod(const InterfaceMethod &method); |
| 137 | /// Generate a using declaration for a trait method. |
| 138 | void genTraitMethodUsingDecl(const InterfaceTrait &trait, |
| 139 | const InterfaceMethod &method); |
| 140 | |
| 141 | //===--------------------------------------------------------------------===// |
| 142 | // OpAsm{Type,Attr}Interface Default Method Emission |
| 143 | |
| 144 | /// Emit 'getAlias' method using mnemonic as alias. |
| 145 | void emitMnemonicAliasMethod(); |
| 146 | |
| 147 | //===--------------------------------------------------------------------===// |
| 148 | // Storage Class Emission |
| 149 | void emitStorageClass(); |
| 150 | /// Generate the storage class constructor. |
| 151 | void emitStorageConstructor(); |
| 152 | /// Emit the key type `KeyTy`. |
| 153 | void emitKeyType(); |
| 154 | /// Emit the equality comparison operator. |
| 155 | void emitEquals(); |
| 156 | /// Emit the key hash function. |
| 157 | void emitHashKey(); |
| 158 | /// Emit the function to construct the storage class. |
| 159 | void emitConstruct(); |
| 160 | |
| 161 | //===--------------------------------------------------------------------===// |
| 162 | // Utility Function Declarations |
| 163 | |
| 164 | /// Get the method parameters for a def builder, where the first several |
| 165 | /// parameters may be different. |
| 166 | SmallVector<MethodParameter> |
| 167 | getBuilderParams(std::initializer_list<MethodParameter> prefix) const; |
| 168 | |
| 169 | //===--------------------------------------------------------------------===// |
| 170 | // Class fields |
| 171 | |
| 172 | /// The attribute or type definition. |
| 173 | const AttrOrTypeDef &def; |
| 174 | /// The list of attribute or type parameters. |
| 175 | ArrayRef<AttrOrTypeParameter> params; |
| 176 | /// The attribute or type class. |
| 177 | Class defCls; |
| 178 | /// An optional attribute or type storage class. The storage class will |
| 179 | /// exist if and only if the def has more than zero parameters. |
| 180 | std::optional<Class> storageCls; |
| 181 | |
| 182 | /// The C++ base value of the def, either "Attribute" or "Type". |
| 183 | StringRef valueType; |
| 184 | /// The prefix/suffix of the TableGen def name, either "Attr" or "Type". |
| 185 | StringRef defType; |
| 186 | |
| 187 | /// The set of using declarations for trait methods. |
| 188 | llvm::StringSet<> interfaceUsingNames; |
| 189 | |
| 190 | /// The headers required by the class. |
| 191 | SmallVector<StringRef> requiredIncludes; |
| 192 | }; |
| 193 | } // namespace |
| 194 | |
| 195 | DefGen::DefGen(const AttrOrTypeDef &def) |
| 196 | : def(def), params(def.getParameters()), defCls(def.getCppClassName()), |
| 197 | valueType(isa<AttrDef>(Val: def) ? "Attribute" : "Type" ), |
| 198 | defType(isa<AttrDef>(Val: def) ? "Attr" : "Type" ) { |
| 199 | // Check that all parameters have names and record the headers declaring |
| 200 | // their types. |
| 201 | for (const AttrOrTypeParameter ¶m : def.getParameters()) { |
| 202 | if (param.isAnonymous()) |
| 203 | llvm::PrintFatalError(Msg: "all parameters must have a name" ); |
| 204 | llvm::append_range(C&: requiredIncludes, R: param.getCppIncludes()); |
| 205 | } |
| 206 | |
| 207 | // If a storage class is needed, create one. |
| 208 | if (def.getNumParameters() > 0) |
| 209 | storageCls.emplace(args: def.getStorageClassName(), /*isStruct=*/args: true); |
| 210 | |
| 211 | // Create the parent class with any indicated traits. |
| 212 | createParentWithTraits(); |
| 213 | // Emit top-level declarations. |
| 214 | emitTopLevelDeclarations(); |
| 215 | // Emit builders for defs with parameters |
| 216 | if (storageCls) |
| 217 | emitBuilders(); |
| 218 | // Emit the type name. |
| 219 | emitName(); |
| 220 | // Emit the dialect name. |
| 221 | emitDialectName(); |
| 222 | // Emit verification of type constraints. |
| 223 | bool genVerifyInvariantsImpl = def.genVerifyInvariantsImpl(); |
| 224 | if (storageCls && genVerifyInvariantsImpl) |
| 225 | emitInvariantsVerifierImpl(); |
| 226 | // Emit the custom verifier (written by the user). |
| 227 | bool genVerifyDecl = def.genVerifyDecl(); |
| 228 | if (storageCls && genVerifyDecl) |
| 229 | emitVerifierDecl(); |
| 230 | // Emit the "verifyInvariants" function if there is any verification at all. |
| 231 | if (storageCls) |
| 232 | emitInvariantsVerifier(hasImpl: genVerifyInvariantsImpl, hasCustomVerifier: genVerifyDecl); |
| 233 | // Emit the mnemonic, if there is one, and any associated parser and printer. |
| 234 | if (def.getMnemonic()) |
| 235 | emitParserPrinter(); |
| 236 | // Emit accessors |
| 237 | if (def.genAccessors()) |
| 238 | emitAccessors(); |
| 239 | // Emit trait interface methods |
| 240 | emitInterfaceMethods(); |
| 241 | // Emit OpAsm{Type,Attr}Interface default methods |
| 242 | if (def.genMnemonicAlias()) |
| 243 | emitMnemonicAliasMethod(); |
| 244 | defCls.finalize(); |
| 245 | // Emit a storage class if one is needed |
| 246 | if (storageCls && def.genStorageClass()) |
| 247 | emitStorageClass(); |
| 248 | } |
| 249 | |
| 250 | void DefGen::createParentWithTraits() { |
| 251 | ParentClass defParent(strfmt(fmt: "::mlir::{0}::{1}Base" , parameters&: valueType, parameters&: defType)); |
| 252 | defParent.addTemplateParam(param: def.getCppClassName()); |
| 253 | defParent.addTemplateParam(param: def.getCppBaseClassName()); |
| 254 | defParent.addTemplateParam(param: storageCls |
| 255 | ? strfmt(fmt: "{0}::{1}" , parameters: def.getStorageNamespace(), |
| 256 | parameters: def.getStorageClassName()) |
| 257 | : strfmt(fmt: "::mlir::{0}Storage" , parameters&: valueType)); |
| 258 | SmallVector<std::string> traitNames; |
| 259 | for (auto &trait : def.getTraits()) { |
| 260 | // Skip PredTrait as it doesn't generate a C++ trait class. |
| 261 | if (isa<PredTrait>(Val: &trait)) |
| 262 | continue; |
| 263 | traitNames.push_back( |
| 264 | Elt: isa<NativeTrait>(Val: &trait) |
| 265 | ? cast<NativeTrait>(Val: &trait)->getFullyQualifiedTraitName() |
| 266 | : cast<InterfaceTrait>(Val: &trait)->getFullyQualifiedTraitName()); |
| 267 | llvm::append_range(C&: requiredIncludes, R: trait.getCppIncludes()); |
| 268 | } |
| 269 | for (auto &traitName : traitNames) |
| 270 | defParent.addTemplateParam(param: traitName); |
| 271 | |
| 272 | // Add OpAsmInterface::Trait if we automatically generate mnemonic alias |
| 273 | // method. |
| 274 | std::string opAsmInterfaceTraitName = |
| 275 | strfmt(fmt: "::mlir::OpAsm{0}Interface::Trait" , parameters&: defType); |
| 276 | if (def.genMnemonicAlias() && |
| 277 | !llvm::is_contained(Range&: traitNames, Element: opAsmInterfaceTraitName)) { |
| 278 | defParent.addTemplateParam(param: opAsmInterfaceTraitName); |
| 279 | // `OpAsmAttrInterface` and `OpAsmTypeInterface` are declared in |
| 280 | // `BuiltinAttributeInterfaces.h` and `BuiltinTypeInterfaces.h` |
| 281 | // respectively. |
| 282 | requiredIncludes.push_back(Elt: isa<AttrDef>(Val: def) |
| 283 | ? "mlir/IR/BuiltinAttributeInterfaces.h" |
| 284 | : "mlir/IR/BuiltinTypeInterfaces.h" ); |
| 285 | } |
| 286 | defCls.addParent(parent: std::move(defParent)); |
| 287 | } |
| 288 | |
| 289 | /// Include declarations specified on NativeTrait |
| 290 | static std::string (const AttrOrTypeDef &def) { |
| 291 | SmallVector<StringRef> ; |
| 292 | // Include extra class declarations from NativeTrait |
| 293 | for (const auto &trait : def.getTraits()) { |
| 294 | if (auto *attrOrTypeTrait = dyn_cast<tblgen::NativeTrait>(Val: &trait)) { |
| 295 | StringRef value = attrOrTypeTrait->getExtraConcreteClassDeclaration(); |
| 296 | if (value.empty()) |
| 297 | continue; |
| 298 | extraDeclarations.push_back(Elt: value); |
| 299 | } |
| 300 | } |
| 301 | if (std::optional<StringRef> = def.getExtraDecls()) { |
| 302 | extraDeclarations.push_back(Elt: *extraDecl); |
| 303 | } |
| 304 | return llvm::join(R&: extraDeclarations, Separator: "\n" ); |
| 305 | } |
| 306 | |
| 307 | /// Extra class definitions have a `$cppClass` substitution that is to be |
| 308 | /// replaced by the C++ class name. |
| 309 | static std::string (const AttrOrTypeDef &def) { |
| 310 | SmallVector<StringRef> ; |
| 311 | // Include extra class definitions from NativeTrait |
| 312 | for (const auto &trait : def.getTraits()) { |
| 313 | if (auto *attrOrTypeTrait = dyn_cast<tblgen::NativeTrait>(Val: &trait)) { |
| 314 | StringRef value = attrOrTypeTrait->getExtraConcreteClassDefinition(); |
| 315 | if (value.empty()) |
| 316 | continue; |
| 317 | extraDefinitions.push_back(Elt: value); |
| 318 | } |
| 319 | } |
| 320 | if (std::optional<StringRef> = def.getExtraDefs()) { |
| 321 | extraDefinitions.push_back(Elt: *extraDef); |
| 322 | } |
| 323 | FmtContext ctx = FmtContext().addSubst(placeholder: "cppClass" , subst: def.getCppClassName()); |
| 324 | return tgfmt(fmt: llvm::join(R&: extraDefinitions, Separator: "\n" ), ctx: &ctx).str(); |
| 325 | } |
| 326 | |
| 327 | void DefGen::emitTopLevelDeclarations() { |
| 328 | // Inherit constructors from the attribute or type class. |
| 329 | defCls.declare<VisibilityDeclaration>(args: Visibility::Public); |
| 330 | defCls.declare<UsingDeclaration>(args: "Base::Base" ); |
| 331 | |
| 332 | // Emit the extra declarations first in case there's a definition in there. |
| 333 | std::string = formatExtraDeclarations(def); |
| 334 | std::string = formatExtraDefinitions(def); |
| 335 | defCls.declare<ExtraClassDeclaration>(args: std::move(extraDecl), |
| 336 | args: std::move(extraDef)); |
| 337 | } |
| 338 | |
| 339 | void DefGen::emitName() { |
| 340 | StringRef name; |
| 341 | if (auto *attrDef = dyn_cast<AttrDef>(Val: &def)) { |
| 342 | name = attrDef->getAttrName(); |
| 343 | } else { |
| 344 | auto *typeDef = cast<TypeDef>(Val: &def); |
| 345 | name = typeDef->getTypeName(); |
| 346 | } |
| 347 | std::string nameDecl = |
| 348 | strfmt(fmt: "static constexpr ::llvm::StringLiteral name = \"{0}\";\n" , parameters&: name); |
| 349 | defCls.declare<ExtraClassDeclaration>(args: std::move(nameDecl)); |
| 350 | } |
| 351 | |
| 352 | void DefGen::emitDialectName() { |
| 353 | std::string decl = |
| 354 | strfmt(fmt: "static constexpr ::llvm::StringLiteral dialectName = \"{0}\";\n" , |
| 355 | parameters: def.getDialect().getName()); |
| 356 | defCls.declare<ExtraClassDeclaration>(args: std::move(decl)); |
| 357 | } |
| 358 | |
| 359 | void DefGen::emitBuilders() { |
| 360 | if (!def.skipDefaultBuilders()) { |
| 361 | emitDefaultBuilder(); |
| 362 | if (def.genVerifyDecl() || def.genVerifyInvariantsImpl()) |
| 363 | emitCheckedBuilder(); |
| 364 | } |
| 365 | for (auto &builder : def.getBuilders()) { |
| 366 | emitCustomBuilder(builder); |
| 367 | if (def.genVerifyDecl() || def.genVerifyInvariantsImpl()) |
| 368 | emitCheckedCustomBuilder(builder); |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | void DefGen::emitVerifierDecl() { |
| 373 | defCls.declareStaticMethod( |
| 374 | retType: "::llvm::LogicalResult" , name: "verify" , |
| 375 | args: getBuilderParams(prefix: {{"::llvm::function_ref<::mlir::InFlightDiagnostic()>" , |
| 376 | "emitError" }})); |
| 377 | } |
| 378 | |
| 379 | static const char *const patternParameterVerificationCode = R"( |
| 380 | if (!({0})) { |
| 381 | emitError() << "failed to verify '{1}': {2}"; |
| 382 | return ::mlir::failure(); |
| 383 | } |
| 384 | )" ; |
| 385 | |
| 386 | void DefGen::emitInvariantsVerifierImpl() { |
| 387 | SmallVector<MethodParameter> builderParams = getBuilderParams( |
| 388 | prefix: {{"::llvm::function_ref<::mlir::InFlightDiagnostic()>" , "emitError" }}); |
| 389 | Method *verifier = |
| 390 | defCls.addMethod(retType: "::llvm::LogicalResult" , name: "verifyInvariantsImpl" , |
| 391 | properties: Method::Static, args&: builderParams); |
| 392 | verifier->body().indent(); |
| 393 | |
| 394 | // Generate verification for each parameter that is a type constraint. |
| 395 | for (auto it : llvm::enumerate(First: def.getParameters())) { |
| 396 | const AttrOrTypeParameter ¶m = it.value(); |
| 397 | std::optional<Constraint> constraint = param.getConstraint(); |
| 398 | // No verification needed for parameters that are not type constraints. |
| 399 | if (!constraint.has_value()) |
| 400 | continue; |
| 401 | FmtContext ctx; |
| 402 | // Note: Skip over the first method parameter (`emitError`). |
| 403 | ctx.withSelf(subst: builderParams[it.index() + 1].getName()); |
| 404 | std::string condition = tgfmt(fmt: constraint->getConditionTemplate(), ctx: &ctx); |
| 405 | verifier->body() << formatv(Fmt: patternParameterVerificationCode, Vals&: condition, |
| 406 | Vals: param.getName(), Vals: constraint->getSummary()) |
| 407 | << "\n" ; |
| 408 | } |
| 409 | { |
| 410 | // Generate verification for PredTraits. |
| 411 | FmtContext traitCtx; |
| 412 | for (auto it : llvm::enumerate(First: def.getParameters())) { |
| 413 | // Note: Skip over the first method parameter (`emitError`). |
| 414 | traitCtx.addSubst(placeholder: it.value().getName(), |
| 415 | subst: builderParams[it.index() + 1].getName()); |
| 416 | } |
| 417 | for (const Trait &trait : def.getTraits()) { |
| 418 | if (auto *t = dyn_cast<PredTrait>(Val: &trait)) { |
| 419 | verifier->body() << tgfmt( |
| 420 | fmt: "if (!($0)) {\n" |
| 421 | " emitError() << \"failed to verify that $1\";\n" |
| 422 | " return ::mlir::failure();\n" |
| 423 | "}\n" , |
| 424 | ctx: &traitCtx, vals: tgfmt(fmt: t->getPredTemplate(), ctx: &traitCtx), vals: t->getSummary()); |
| 425 | } |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | verifier->body() << "return ::mlir::success();" ; |
| 430 | } |
| 431 | |
| 432 | void DefGen::emitInvariantsVerifier(bool hasImpl, bool hasCustomVerifier) { |
| 433 | if (!hasImpl && !hasCustomVerifier) |
| 434 | return; |
| 435 | defCls.declare<UsingDeclaration>(args: "Base::getChecked" ); |
| 436 | SmallVector<MethodParameter> builderParams = getBuilderParams( |
| 437 | prefix: {{"::llvm::function_ref<::mlir::InFlightDiagnostic()>" , "emitError" }}); |
| 438 | Method *verifier = |
| 439 | defCls.addMethod(retType: "::llvm::LogicalResult" , name: "verifyInvariants" , |
| 440 | properties: Method::Static, args&: builderParams); |
| 441 | verifier->body().indent(); |
| 442 | |
| 443 | auto emitVerifierCall = [&](StringRef name) { |
| 444 | verifier->body() << strfmt(fmt: "if (::mlir::failed({0}(" , parameters&: name); |
| 445 | llvm::interleaveComma( |
| 446 | c: llvm::map_range(C&: builderParams, |
| 447 | F: [](auto ¶m) { return param.getName(); }), |
| 448 | os&: verifier->body()); |
| 449 | verifier->body() << ")))\n" ; |
| 450 | verifier->body() << " return ::mlir::failure();\n" ; |
| 451 | }; |
| 452 | |
| 453 | if (hasImpl) { |
| 454 | // Call the verifier that checks the type constraints. |
| 455 | emitVerifierCall("verifyInvariantsImpl" ); |
| 456 | } |
| 457 | if (hasCustomVerifier) { |
| 458 | // Call the custom verifier that is provided by the user. |
| 459 | emitVerifierCall("verify" ); |
| 460 | } |
| 461 | verifier->body() << "return ::mlir::success();" ; |
| 462 | } |
| 463 | |
| 464 | void DefGen::emitParserPrinter() { |
| 465 | auto *mnemonic = defCls.addStaticMethod<Method::Constexpr>( |
| 466 | retType: "::llvm::StringLiteral" , name: "getMnemonic" ); |
| 467 | mnemonic->body().indent() << strfmt(fmt: "return {\"{0}\"};" , parameters: *def.getMnemonic()); |
| 468 | |
| 469 | // Declare the parser and printer, if needed. |
| 470 | bool hasAssemblyFormat = def.getAssemblyFormat().has_value(); |
| 471 | if (!def.hasCustomAssemblyFormat() && !hasAssemblyFormat) |
| 472 | return; |
| 473 | |
| 474 | // Declare the parser. |
| 475 | SmallVector<MethodParameter> parserParams; |
| 476 | parserParams.emplace_back(Args: "::mlir::AsmParser &" , Args: "odsParser" ); |
| 477 | if (isa<AttrDef>(Val: &def)) |
| 478 | parserParams.emplace_back(Args: "::mlir::Type" , Args: "odsType" ); |
| 479 | auto *parser = defCls.addMethod(retType: strfmt(fmt: "::mlir::{0}" , parameters&: valueType), name: "parse" , |
| 480 | properties: hasAssemblyFormat ? Method::Static |
| 481 | : Method::StaticDeclaration, |
| 482 | args: std::move(parserParams)); |
| 483 | // Declare the printer. |
| 484 | auto props = hasAssemblyFormat ? Method::Const : Method::ConstDeclaration; |
| 485 | Method *printer = |
| 486 | defCls.addMethod(retType: "void" , name: "print" , properties: props, |
| 487 | args: MethodParameter("::mlir::AsmPrinter &" , "odsPrinter" )); |
| 488 | // Emit the bodies if we are using the declarative format. |
| 489 | if (hasAssemblyFormat) |
| 490 | return generateAttrOrTypeFormat(def, parser&: parser->body(), printer&: printer->body()); |
| 491 | } |
| 492 | |
| 493 | void DefGen::emitAccessors() { |
| 494 | for (auto ¶m : params) { |
| 495 | Method *m = defCls.addMethod( |
| 496 | retType: param.getCppAccessorType(), name: param.getAccessorName(), |
| 497 | properties: def.genStorageClass() ? Method::Const : Method::ConstDeclaration); |
| 498 | // Generate accessor definitions only if we also generate the storage |
| 499 | // class. Otherwise, let the user define the exact accessor definition. |
| 500 | if (!def.genStorageClass()) |
| 501 | continue; |
| 502 | m->body().indent() << "return getImpl()->" << param.getName() << ";" ; |
| 503 | } |
| 504 | } |
| 505 | |
| 506 | void DefGen::emitInterfaceMethods() { |
| 507 | for (auto &traitDef : def.getTraits()) |
| 508 | if (auto *trait = dyn_cast<InterfaceTrait>(Val: &traitDef)) |
| 509 | if (trait->shouldDeclareMethods()) |
| 510 | emitTraitMethods(trait: *trait); |
| 511 | } |
| 512 | |
| 513 | //===----------------------------------------------------------------------===// |
| 514 | // Builder Emission |
| 515 | //===----------------------------------------------------------------------===// |
| 516 | |
| 517 | SmallVector<MethodParameter> |
| 518 | DefGen::getBuilderParams(std::initializer_list<MethodParameter> prefix) const { |
| 519 | SmallVector<MethodParameter> builderParams; |
| 520 | builderParams.append(in_start: prefix.begin(), in_end: prefix.end()); |
| 521 | for (auto ¶m : params) |
| 522 | builderParams.emplace_back(Args: param.getCppType(), Args: param.getName()); |
| 523 | return builderParams; |
| 524 | } |
| 525 | |
| 526 | void DefGen::emitDefaultBuilder() { |
| 527 | Method *m = defCls.addStaticMethod( |
| 528 | retType: def.getCppClassName(), name: "get" , |
| 529 | args: getBuilderParams(prefix: {{"::mlir::MLIRContext *" , "context" }})); |
| 530 | MethodBody &body = m->body().indent(); |
| 531 | auto scope = body.scope(open: "return Base::get(context" , close: ");" ); |
| 532 | for (const auto ¶m : params) |
| 533 | body << ", std::move(" << param.getName() << ")" ; |
| 534 | } |
| 535 | |
| 536 | void DefGen::emitCheckedBuilder() { |
| 537 | Method *m = defCls.addStaticMethod( |
| 538 | retType: def.getCppClassName(), name: "getChecked" , |
| 539 | args: getBuilderParams( |
| 540 | prefix: {{"::llvm::function_ref<::mlir::InFlightDiagnostic()>" , "emitError" }, |
| 541 | {"::mlir::MLIRContext *" , "context" }})); |
| 542 | MethodBody &body = m->body().indent(); |
| 543 | auto scope = body.scope(open: "return Base::getChecked(emitError, context" , close: ");" ); |
| 544 | for (const auto ¶m : params) |
| 545 | body << ", std::move(" << param.getName() << ")" ; |
| 546 | } |
| 547 | |
| 548 | static SmallVector<MethodParameter> |
| 549 | getCustomBuilderParams(std::initializer_list<MethodParameter> prefix, |
| 550 | const AttrOrTypeBuilder &builder) { |
| 551 | auto params = builder.getParameters(); |
| 552 | SmallVector<MethodParameter> builderParams; |
| 553 | builderParams.append(in_start: prefix.begin(), in_end: prefix.end()); |
| 554 | if (!builder.hasInferredContextParameter()) |
| 555 | builderParams.emplace_back(Args: "::mlir::MLIRContext *" , Args: "context" ); |
| 556 | for (auto ¶m : params) { |
| 557 | builderParams.emplace_back(Args: param.getCppType(), Args: *param.getName(), |
| 558 | Args: param.getDefaultValue()); |
| 559 | } |
| 560 | return builderParams; |
| 561 | } |
| 562 | |
| 563 | static std::string getSignature(const Method &m) { |
| 564 | std::string signature; |
| 565 | llvm::raw_string_ostream os(signature); |
| 566 | raw_indented_ostream indentedOs(os); |
| 567 | m.writeDeclTo(os&: indentedOs); |
| 568 | return signature; |
| 569 | } |
| 570 | |
| 571 | static void emitDuplicatedBuilderError(const Method ¤tMethod, |
| 572 | StringRef methodName, |
| 573 | const Class &defCls, |
| 574 | const AttrOrTypeDef &def) { |
| 575 | |
| 576 | // Try to search for method that makes `get` redundant. |
| 577 | auto loc = def.getDef()->getFieldLoc(FieldName: "builders" ); |
| 578 | for (auto &method : defCls.getMethods()) { |
| 579 | if (method->getName() == methodName && |
| 580 | method->makesRedundant(other: currentMethod)) { |
| 581 | PrintError(ErrorLoc: loc, Msg: llvm::Twine("builder `" ) + methodName + |
| 582 | "` conflicts with an existing builder. " ); |
| 583 | PrintFatalNote(Msg: llvm::Twine("A new builder with signature:\n" ) + |
| 584 | getSignature(m: currentMethod) + |
| 585 | "\nis shadowed by an existing builder with signature:\n" + |
| 586 | getSignature(m: *method) + |
| 587 | "\nPlease remove one of the conflicting " |
| 588 | "definitions." ); |
| 589 | } |
| 590 | } |
| 591 | |
| 592 | // This code shouldn't be reached, but leaving this here for potential future |
| 593 | // use. |
| 594 | PrintFatalError(ErrorLoc: loc, Msg: "Failed to generate builder " + methodName); |
| 595 | } |
| 596 | |
| 597 | void DefGen::emitCustomBuilder(const AttrOrTypeBuilder &builder) { |
| 598 | // Don't emit a body if there isn't one. |
| 599 | auto props = builder.getBody() ? Method::Static : Method::StaticDeclaration; |
| 600 | StringRef returnType = def.getCppClassName(); |
| 601 | if (std::optional<StringRef> builderReturnType = builder.getReturnType()) |
| 602 | returnType = *builderReturnType; |
| 603 | |
| 604 | llvm::StringRef methodName = "get" ; |
| 605 | const auto parameters = getCustomBuilderParams(prefix: {}, builder); |
| 606 | Method *m = defCls.addMethod(retType&: returnType, name&: methodName, properties: props, args: parameters); |
| 607 | |
| 608 | // If method is pruned, report error and terminate. |
| 609 | if (!m) { |
| 610 | auto curMethod = Method(returnType, methodName, props, parameters); |
| 611 | emitDuplicatedBuilderError(currentMethod: curMethod, methodName, defCls, def); |
| 612 | } |
| 613 | |
| 614 | if (!builder.getBody()) |
| 615 | return; |
| 616 | |
| 617 | // Format the body and emit it. |
| 618 | FmtContext ctx; |
| 619 | ctx.addSubst(placeholder: "_get" , subst: "Base::get" ); |
| 620 | if (!builder.hasInferredContextParameter()) |
| 621 | ctx.addSubst(placeholder: "_ctxt" , subst: "context" ); |
| 622 | std::string bodyStr = tgfmt(fmt: *builder.getBody(), ctx: &ctx); |
| 623 | m->body().indent().getStream().printReindented(str: bodyStr); |
| 624 | } |
| 625 | |
| 626 | /// Replace all instances of 'from' to 'to' in `str` and return the new string. |
| 627 | static std::string replaceInStr(std::string str, StringRef from, StringRef to) { |
| 628 | size_t pos = 0; |
| 629 | while ((pos = str.find(s: from.data(), pos: pos, n: from.size())) != std::string::npos) |
| 630 | str.replace(pos: pos, n1: from.size(), s: to.data(), n2: to.size()); |
| 631 | return str; |
| 632 | } |
| 633 | |
| 634 | void DefGen::emitCheckedCustomBuilder(const AttrOrTypeBuilder &builder) { |
| 635 | // Don't emit a body if there isn't one. |
| 636 | auto props = builder.getBody() ? Method::Static : Method::StaticDeclaration; |
| 637 | StringRef returnType = def.getCppClassName(); |
| 638 | if (std::optional<StringRef> builderReturnType = builder.getReturnType()) |
| 639 | returnType = *builderReturnType; |
| 640 | |
| 641 | llvm::StringRef methodName = "getChecked" ; |
| 642 | auto parameters = getCustomBuilderParams( |
| 643 | prefix: {{"::llvm::function_ref<::mlir::InFlightDiagnostic()>" , "emitError" }}, |
| 644 | builder); |
| 645 | Method *m = defCls.addMethod(retType&: returnType, name&: methodName, properties: props, args&: parameters); |
| 646 | |
| 647 | // If method is pruned, report error and terminate. |
| 648 | if (!m) { |
| 649 | auto curMethod = Method(returnType, methodName, props, parameters); |
| 650 | emitDuplicatedBuilderError(currentMethod: curMethod, methodName, defCls, def); |
| 651 | } |
| 652 | |
| 653 | if (!builder.getBody()) |
| 654 | return; |
| 655 | |
| 656 | // Format the body and emit it. Replace $_get(...) with |
| 657 | // Base::getChecked(emitError, ...) |
| 658 | FmtContext ctx; |
| 659 | if (!builder.hasInferredContextParameter()) |
| 660 | ctx.addSubst(placeholder: "_ctxt" , subst: "context" ); |
| 661 | std::string bodyStr = replaceInStr(str: builder.getBody()->str(), from: "$_get(" , |
| 662 | to: "Base::getChecked(emitError, " ); |
| 663 | bodyStr = tgfmt(fmt: bodyStr, ctx: &ctx); |
| 664 | m->body().indent().getStream().printReindented(str: bodyStr); |
| 665 | } |
| 666 | |
| 667 | //===----------------------------------------------------------------------===// |
| 668 | // Interface Method Emission |
| 669 | //===----------------------------------------------------------------------===// |
| 670 | |
| 671 | void DefGen::emitTraitMethods(const InterfaceTrait &trait) { |
| 672 | // Get the set of methods that should always be declared. |
| 673 | auto alwaysDeclaredMethods = trait.getAlwaysDeclaredMethods(); |
| 674 | StringSet<> alwaysDeclared; |
| 675 | alwaysDeclared.insert_range(R&: alwaysDeclaredMethods); |
| 676 | |
| 677 | Interface iface = trait.getInterface(); // causes strange bugs if elided |
| 678 | for (auto &method : iface.getMethods()) { |
| 679 | // Don't declare if the method has a body. Or if the method has a default |
| 680 | // implementation and the def didn't request that it always be declared. |
| 681 | if (method.getBody()) |
| 682 | continue; |
| 683 | if (method.getDefaultImplementation() && |
| 684 | !alwaysDeclared.count(Key: method.getName())) { |
| 685 | genTraitMethodUsingDecl(trait, method); |
| 686 | continue; |
| 687 | } |
| 688 | emitTraitMethod(method); |
| 689 | } |
| 690 | } |
| 691 | |
| 692 | void DefGen::emitTraitMethod(const InterfaceMethod &method) { |
| 693 | // All interface methods are declaration-only. |
| 694 | auto props = |
| 695 | method.isStatic() ? Method::StaticDeclaration : Method::ConstDeclaration; |
| 696 | SmallVector<MethodParameter> params; |
| 697 | for (auto ¶m : method.getArguments()) |
| 698 | params.emplace_back(Args: param.type, Args: param.name); |
| 699 | defCls.addMethod(retType: method.getReturnType(), name: method.getName(), properties: props, |
| 700 | args: std::move(params)); |
| 701 | } |
| 702 | |
| 703 | void DefGen::genTraitMethodUsingDecl(const InterfaceTrait &trait, |
| 704 | const InterfaceMethod &method) { |
| 705 | std::string name = (llvm::Twine(trait.getFullyQualifiedTraitName()) + "<" + |
| 706 | def.getCppClassName() + ">::" + method.getName()) |
| 707 | .str(); |
| 708 | if (interfaceUsingNames.insert(key: name).second) |
| 709 | defCls.declare<UsingDeclaration>(args: std::move(name)); |
| 710 | } |
| 711 | |
| 712 | //===----------------------------------------------------------------------===// |
| 713 | // OpAsm{Type,Attr}Interface Default Method Emission |
| 714 | |
| 715 | void DefGen::emitMnemonicAliasMethod() { |
| 716 | // If the mnemonic is not set, there is nothing to do. |
| 717 | if (!def.getMnemonic()) |
| 718 | return; |
| 719 | |
| 720 | // Emit the mnemonic alias method. |
| 721 | SmallVector<MethodParameter> params{{"::llvm::raw_ostream &" , "os" }}; |
| 722 | Method *m = defCls.addMethod<Method::Const>(retType: "::mlir::OpAsmAliasResult" , |
| 723 | name: "getAlias" , args: std::move(params)); |
| 724 | m->body().indent() << strfmt(fmt: "os << \"{0}\";\n" , parameters: *def.getMnemonic()) |
| 725 | << "return ::mlir::OpAsmAliasResult::OverridableAlias;\n" ; |
| 726 | } |
| 727 | |
| 728 | //===----------------------------------------------------------------------===// |
| 729 | // Storage Class Emission |
| 730 | //===----------------------------------------------------------------------===// |
| 731 | |
| 732 | void DefGen::emitStorageConstructor() { |
| 733 | Constructor *ctor = |
| 734 | storageCls->addConstructor<Method::Inline>(args: getBuilderParams(prefix: {})); |
| 735 | for (auto ¶m : params) { |
| 736 | std::string movedValue = ("std::move(" + param.getName() + ")" ).str(); |
| 737 | ctor->addMemberInitializer(name: param.getName(), value&: movedValue); |
| 738 | } |
| 739 | } |
| 740 | |
| 741 | void DefGen::emitKeyType() { |
| 742 | std::string keyType("std::tuple<" ); |
| 743 | llvm::raw_string_ostream os(keyType); |
| 744 | llvm::interleaveComma(c: params, os, |
| 745 | each_fn: [&](auto ¶m) { os << param.getCppType(); }); |
| 746 | os << '>'; |
| 747 | storageCls->declare<UsingDeclaration>(args: "KeyTy" , args: std::move(os.str())); |
| 748 | |
| 749 | // Add a method to construct the key type from the storage. |
| 750 | Method *m = storageCls->addConstMethod<Method::Inline>(retType: "KeyTy" , name: "getAsKey" ); |
| 751 | m->body().indent() << "return KeyTy(" ; |
| 752 | llvm::interleaveComma(c: params, os&: m->body().indent(), |
| 753 | each_fn: [&](auto ¶m) { m->body() << param.getName(); }); |
| 754 | m->body() << ");" ; |
| 755 | } |
| 756 | |
| 757 | void DefGen::emitEquals() { |
| 758 | Method *eq = storageCls->addConstMethod<Method::Inline>( |
| 759 | retType: "bool" , name: "operator==" , args: MethodParameter("const KeyTy &" , "tblgenKey" )); |
| 760 | auto &body = eq->body().indent(); |
| 761 | auto scope = body.scope(open: "return (" , close: ");" ); |
| 762 | const auto eachFn = [&](auto it) { |
| 763 | FmtContext ctx({{"_lhs" , it.value().getName()}, |
| 764 | {"_rhs" , strfmt("std::get<{0}>(tblgenKey)" , it.index())}}); |
| 765 | body << tgfmt(it.value().getComparator(), &ctx); |
| 766 | }; |
| 767 | llvm::interleave(c: llvm::enumerate(First&: params), os&: body, each_fn: eachFn, separator: ") && (" ); |
| 768 | } |
| 769 | |
| 770 | void DefGen::emitHashKey() { |
| 771 | Method *hash = storageCls->addStaticInlineMethod( |
| 772 | retType: "::llvm::hash_code" , name: "hashKey" , |
| 773 | args: MethodParameter("const KeyTy &" , "tblgenKey" )); |
| 774 | auto &body = hash->body().indent(); |
| 775 | auto scope = body.scope(open: "return ::llvm::hash_combine(" , close: ");" ); |
| 776 | llvm::interleaveComma(c: llvm::enumerate(First&: params), os&: body, each_fn: [&](auto it) { |
| 777 | body << llvm::formatv("std::get<{0}>(tblgenKey)" , it.index()); |
| 778 | }); |
| 779 | } |
| 780 | |
| 781 | void DefGen::emitConstruct() { |
| 782 | Method *construct = storageCls->addMethod( |
| 783 | retType: strfmt(fmt: "{0} *" , parameters: def.getStorageClassName()), name: "construct" , |
| 784 | properties: def.hasStorageCustomConstructor() ? Method::StaticDeclaration |
| 785 | : Method::StaticInline, |
| 786 | args: MethodParameter(strfmt(fmt: "::mlir::{0}StorageAllocator &" , parameters&: valueType), |
| 787 | "allocator" ), |
| 788 | args: MethodParameter("KeyTy &&" , "tblgenKey" )); |
| 789 | if (!def.hasStorageCustomConstructor()) { |
| 790 | auto &body = construct->body().indent(); |
| 791 | for (const auto &it : llvm::enumerate(First&: params)) { |
| 792 | body << formatv(Fmt: "auto {0} = std::move(std::get<{1}>(tblgenKey));\n" , |
| 793 | Vals: it.value().getName(), Vals: it.index()); |
| 794 | } |
| 795 | // Use the parameters' custom allocator code, if provided. |
| 796 | FmtContext ctx = FmtContext().addSubst(placeholder: "_allocator" , subst: "allocator" ); |
| 797 | for (auto ¶m : params) { |
| 798 | if (std::optional<StringRef> allocCode = param.getAllocator()) { |
| 799 | ctx.withSelf(subst: param.getName()).addSubst(placeholder: "_dst" , subst: param.getName()); |
| 800 | body << tgfmt(fmt: *allocCode, ctx: &ctx) << '\n'; |
| 801 | } |
| 802 | } |
| 803 | auto scope = |
| 804 | body.scope(open: strfmt(fmt: "return new (allocator.allocate<{0}>()) {0}(" , |
| 805 | parameters: def.getStorageClassName()), |
| 806 | close: ");" ); |
| 807 | llvm::interleaveComma(c: params, os&: body, each_fn: [&](auto ¶m) { |
| 808 | body << "std::move(" << param.getName() << ")" ; |
| 809 | }); |
| 810 | } |
| 811 | } |
| 812 | |
| 813 | void DefGen::emitStorageClass() { |
| 814 | // Add the appropriate parent class. |
| 815 | storageCls->addParent(parent: strfmt(fmt: "::mlir::{0}Storage" , parameters&: valueType)); |
| 816 | // Add the constructor. |
| 817 | emitStorageConstructor(); |
| 818 | // Declare the key type. |
| 819 | emitKeyType(); |
| 820 | // Add the comparison method. |
| 821 | emitEquals(); |
| 822 | // Emit the key hash method. |
| 823 | emitHashKey(); |
| 824 | // Emit the storage constructor. Just declare it if the user wants to define |
| 825 | // it themself. |
| 826 | emitConstruct(); |
| 827 | // Emit the storage class members as public, at the very end of the struct. |
| 828 | storageCls->finalize(); |
| 829 | for (auto ¶m : params) { |
| 830 | if (param.getCppType().contains(Other: "APInt" ) && !param.hasCustomComparator()) { |
| 831 | PrintFatalError( |
| 832 | ErrorLoc: def.getLoc(), |
| 833 | Msg: "Using a raw APInt parameter without a custom comparator is " |
| 834 | "not supported because an assert in the equality operator is " |
| 835 | "triggered when the two APInts have different bit widths. This can " |
| 836 | "lead to unexpected crashes. Use an `APIntParameter` or " |
| 837 | "provide a custom comparator." ); |
| 838 | } |
| 839 | storageCls->declare<Field>(args: param.getCppType(), args: param.getName()); |
| 840 | } |
| 841 | } |
| 842 | |
| 843 | //===----------------------------------------------------------------------===// |
| 844 | // DefGenerator |
| 845 | //===----------------------------------------------------------------------===// |
| 846 | |
| 847 | namespace { |
| 848 | /// This struct is the base generator used when processing tablegen interfaces. |
| 849 | class DefGenerator { |
| 850 | public: |
| 851 | bool emitDecls(StringRef selectedDialect); |
| 852 | bool emitDefs(StringRef selectedDialect); |
| 853 | |
| 854 | protected: |
| 855 | DefGenerator(ArrayRef<const Record *> defs, raw_ostream &os, |
| 856 | StringRef defType, StringRef valueType, bool isAttrGenerator) |
| 857 | : defRecords(defs), os(os), defType(defType), valueType(valueType), |
| 858 | isAttrGenerator(isAttrGenerator) { |
| 859 | // Sort by occurrence in file. |
| 860 | llvm::sort(C&: defRecords, Comp: [](const Record *lhs, const Record *rhs) { |
| 861 | return lhs->getID() < rhs->getID(); |
| 862 | }); |
| 863 | } |
| 864 | |
| 865 | /// Emit the list of def type names. |
| 866 | void emitTypeDefList(ArrayRef<AttrOrTypeDef> defs); |
| 867 | /// Emit the code to dispatch between different defs during parsing/printing. |
| 868 | void emitParsePrintDispatch(ArrayRef<AttrOrTypeDef> defs); |
| 869 | |
| 870 | /// The set of def records to emit. |
| 871 | std::vector<const Record *> defRecords; |
| 872 | /// The attribute or type class to emit. |
| 873 | /// The stream to emit to. |
| 874 | raw_ostream &os; |
| 875 | /// The prefix of the tablegen def name, e.g. Attr or Type. |
| 876 | StringRef defType; |
| 877 | /// The C++ base value type of the def, e.g. Attribute or Type. |
| 878 | StringRef valueType; |
| 879 | /// Flag indicating if this generator is for Attributes. False if the |
| 880 | /// generator is for types. |
| 881 | bool isAttrGenerator; |
| 882 | }; |
| 883 | |
| 884 | /// A specialized generator for AttrDefs. |
| 885 | struct AttrDefGenerator : public DefGenerator { |
| 886 | AttrDefGenerator(const RecordKeeper &records, raw_ostream &os) |
| 887 | : DefGenerator(records.getAllDerivedDefinitionsIfDefined(ClassName: "AttrDef" ), os, |
| 888 | "Attr" , "Attribute" , /*isAttrGenerator=*/true) {} |
| 889 | }; |
| 890 | /// A specialized generator for TypeDefs. |
| 891 | struct TypeDefGenerator : public DefGenerator { |
| 892 | TypeDefGenerator(const RecordKeeper &records, raw_ostream &os) |
| 893 | : DefGenerator(records.getAllDerivedDefinitionsIfDefined(ClassName: "TypeDef" ), os, |
| 894 | "Type" , "Type" , /*isAttrGenerator=*/false) {} |
| 895 | }; |
| 896 | } // namespace |
| 897 | |
| 898 | //===----------------------------------------------------------------------===// |
| 899 | // GEN: Declarations |
| 900 | //===----------------------------------------------------------------------===// |
| 901 | |
| 902 | /// Print this above all the other declarations. Contains type declarations used |
| 903 | /// later on. |
| 904 | static const char *const = R"( |
| 905 | namespace mlir { |
| 906 | class AsmParser; |
| 907 | class AsmPrinter; |
| 908 | } // namespace mlir |
| 909 | )" ; |
| 910 | |
| 911 | bool DefGenerator::emitDecls(StringRef selectedDialect) { |
| 912 | emitSourceFileHeader(Desc: (defType + "Def Declarations" ).str(), OS&: os); |
| 913 | llvm::IfDefEmitter scope(os, "GET_" + defType.upper() + "DEF_CLASSES" ); |
| 914 | |
| 915 | SmallVector<AttrOrTypeDef, 16> defs; |
| 916 | collectAllDefs(selectedDialect, records: defRecords, resultDefs&: defs); |
| 917 | |
| 918 | // The required includes are only known once all declarations were |
| 919 | // generated, so buffer the declarations until the includes are emitted. |
| 920 | SmallVector<StringRef> includes; |
| 921 | std::string declarations; |
| 922 | llvm::raw_string_ostream declOs(declarations); |
| 923 | if (!defs.empty()) { |
| 924 | includes.push_back(Elt: isAttrGenerator ? "mlir/IR/Attributes.h" |
| 925 | : "mlir/IR/Types.h" ); |
| 926 | DialectNamespaceEmitter nsEmitter(declOs, defs.front().getDialect()); |
| 927 | |
| 928 | // Declare all the def classes first (in case they reference each other). |
| 929 | for (const AttrOrTypeDef &def : defs) { |
| 930 | tblgen::emitSummaryAndDescComments(os&: declOs, summary: def.getSummary(), |
| 931 | description: def.getDescription()); |
| 932 | declOs << "class " << def.getCppClassName() << ";\n" ; |
| 933 | } |
| 934 | |
| 935 | // Emit the declarations. |
| 936 | for (const AttrOrTypeDef &def : defs) { |
| 937 | DefGen gen(def); |
| 938 | gen.emitDecl(os&: declOs); |
| 939 | llvm::append_range(C&: includes, R: gen.getRequiredIncludes()); |
| 940 | } |
| 941 | } |
| 942 | tblgen::emitIncludes(os, headers: includes); |
| 943 | |
| 944 | // Output the common "header". |
| 945 | os << typeDefDeclHeader; |
| 946 | os << declarations; |
| 947 | |
| 948 | // Emit the TypeID explicit specializations to have a single definition for |
| 949 | // each of these. |
| 950 | for (const AttrOrTypeDef &def : defs) |
| 951 | if (!def.getDialect().getCppNamespace().empty()) |
| 952 | os << "MLIR_DECLARE_EXPLICIT_TYPE_ID(" |
| 953 | << def.getDialect().getCppNamespace() << "::" << def.getCppClassName() |
| 954 | << ")\n" ; |
| 955 | |
| 956 | return false; |
| 957 | } |
| 958 | |
| 959 | //===----------------------------------------------------------------------===// |
| 960 | // GEN: Def List |
| 961 | //===----------------------------------------------------------------------===// |
| 962 | |
| 963 | void DefGenerator::emitTypeDefList(ArrayRef<AttrOrTypeDef> defs) { |
| 964 | llvm::IfDefEmitter scope(os, "GET_" + defType.upper() + "DEF_LIST" ); |
| 965 | auto interleaveFn = [&](const AttrOrTypeDef &def) { |
| 966 | os << def.getDialect().getCppNamespace() << "::" << def.getCppClassName(); |
| 967 | }; |
| 968 | llvm::interleave(c: defs, os, each_fn: interleaveFn, separator: ",\n" ); |
| 969 | os << "\n" ; |
| 970 | } |
| 971 | |
| 972 | //===----------------------------------------------------------------------===// |
| 973 | // GEN: Definitions |
| 974 | //===----------------------------------------------------------------------===// |
| 975 | |
| 976 | /// The code block for default attribute parser/printer dispatch boilerplate. |
| 977 | /// {0}: the dialect fully qualified class name. |
| 978 | /// {1}: the optional code for the dynamic attribute parser dispatch. |
| 979 | /// {2}: the optional code for the dynamic attribute printer dispatch. |
| 980 | static const char *const dialectDefaultAttrPrinterParserDispatch = R"( |
| 981 | /// Parse an attribute registered to this dialect. |
| 982 | ::mlir::Attribute {0}::parseAttribute(::mlir::DialectAsmParser &parser, |
| 983 | ::mlir::Type type) const {{ |
| 984 | ::llvm::SMLoc typeLoc = parser.getCurrentLocation(); |
| 985 | ::llvm::StringRef attrTag; |
| 986 | {{ |
| 987 | ::mlir::Attribute attr; |
| 988 | auto parseResult = generatedAttributeParser(parser, &attrTag, type, attr); |
| 989 | if (parseResult.has_value()) |
| 990 | return attr; |
| 991 | } |
| 992 | {1} |
| 993 | parser.emitError(typeLoc) << "unknown attribute `" |
| 994 | << attrTag << "` in dialect `" << getNamespace() << "`"; |
| 995 | return {{}; |
| 996 | } |
| 997 | /// Print an attribute registered to this dialect. |
| 998 | void {0}::printAttribute(::mlir::Attribute attr, |
| 999 | ::mlir::DialectAsmPrinter &printer) const {{ |
| 1000 | if (::mlir::succeeded(generatedAttributePrinter(attr, printer))) |
| 1001 | return; |
| 1002 | {2} |
| 1003 | } |
| 1004 | )" ; |
| 1005 | |
| 1006 | /// The code block for dynamic attribute parser dispatch boilerplate. |
| 1007 | static const char *const dialectDynamicAttrParserDispatch = R"( |
| 1008 | { |
| 1009 | ::mlir::Attribute genAttr; |
| 1010 | auto parseResult = parseOptionalDynamicAttr(attrTag, parser, genAttr); |
| 1011 | if (parseResult.has_value()) { |
| 1012 | if (::mlir::succeeded(parseResult.value())) |
| 1013 | return genAttr; |
| 1014 | return Attribute(); |
| 1015 | } |
| 1016 | } |
| 1017 | )" ; |
| 1018 | |
| 1019 | /// The code block for dynamic type printer dispatch boilerplate. |
| 1020 | static const char *const dialectDynamicAttrPrinterDispatch = R"( |
| 1021 | if (::mlir::succeeded(printIfDynamicAttr(attr, printer))) |
| 1022 | return; |
| 1023 | )" ; |
| 1024 | |
| 1025 | /// The code block for default type parser/printer dispatch boilerplate. |
| 1026 | /// {0}: the dialect fully qualified class name. |
| 1027 | /// {1}: the optional code for the dynamic type parser dispatch. |
| 1028 | /// {2}: the optional code for the dynamic type printer dispatch. |
| 1029 | static const char *const dialectDefaultTypePrinterParserDispatch = R"( |
| 1030 | /// Parse a type registered to this dialect. |
| 1031 | ::mlir::Type {0}::parseType(::mlir::DialectAsmParser &parser) const {{ |
| 1032 | ::llvm::SMLoc typeLoc = parser.getCurrentLocation(); |
| 1033 | ::llvm::StringRef mnemonic; |
| 1034 | ::mlir::Type genType; |
| 1035 | auto parseResult = generatedTypeParser(parser, &mnemonic, genType); |
| 1036 | if (parseResult.has_value()) |
| 1037 | return genType; |
| 1038 | {1} |
| 1039 | parser.emitError(typeLoc) << "unknown type `" |
| 1040 | << mnemonic << "` in dialect `" << getNamespace() << "`"; |
| 1041 | return {{}; |
| 1042 | } |
| 1043 | /// Print a type registered to this dialect. |
| 1044 | void {0}::printType(::mlir::Type type, |
| 1045 | ::mlir::DialectAsmPrinter &printer) const {{ |
| 1046 | if (::mlir::succeeded(generatedTypePrinter(type, printer))) |
| 1047 | return; |
| 1048 | {2} |
| 1049 | } |
| 1050 | )" ; |
| 1051 | |
| 1052 | /// The code block for dynamic type parser dispatch boilerplate. |
| 1053 | static const char *const dialectDynamicTypeParserDispatch = R"( |
| 1054 | { |
| 1055 | auto parseResult = parseOptionalDynamicType(mnemonic, parser, genType); |
| 1056 | if (parseResult.has_value()) { |
| 1057 | if (::mlir::succeeded(parseResult.value())) |
| 1058 | return genType; |
| 1059 | return ::mlir::Type(); |
| 1060 | } |
| 1061 | } |
| 1062 | )" ; |
| 1063 | |
| 1064 | /// The code block for dynamic type printer dispatch boilerplate. |
| 1065 | static const char *const dialectDynamicTypePrinterDispatch = R"( |
| 1066 | if (::mlir::succeeded(printIfDynamicType(type, printer))) |
| 1067 | return; |
| 1068 | )" ; |
| 1069 | |
| 1070 | /// Checks whether a declarative assembly format string needs a leading space |
| 1071 | /// between the mnemonic and the format body in the generated printer. |
| 1072 | /// |
| 1073 | /// Returns false for formats starting with punctuation or a space-eraser |
| 1074 | /// directive that should attach directly to the mnemonic (e.g., `<`, `(`, |
| 1075 | /// ``). |
| 1076 | /// |
| 1077 | /// This inspects the raw format string rather than parsing it into a DefFormat. |
| 1078 | /// Parsing would require access to the format element types (which are local to |
| 1079 | /// `AttrOrTypeFormatGen.cpp`) and would re-parse every format string just to |
| 1080 | /// check its first token -- an overkill for a simple spacing heuristic. |
| 1081 | /// The only case this cannot distinguish structurally is an optional group |
| 1082 | /// whose then-branch starts with punctuation, but parsing has the same |
| 1083 | /// limitation since the group's anchor is not known at codegen time. |
| 1084 | static bool needsLeadingSpace(const AttrOrTypeDef &def) { |
| 1085 | StringRef fmtStr = def.getAssemblyFormat()->trim(); |
| 1086 | if (fmtStr.empty()) |
| 1087 | return false; |
| 1088 | |
| 1089 | // '(' starts an optional group. |
| 1090 | if (fmtStr.front() == '(') |
| 1091 | return false; |
| 1092 | |
| 1093 | if (fmtStr.front() != '`' || fmtStr.size() < 2) |
| 1094 | return true; |
| 1095 | |
| 1096 | // Backtick-quoted literals (e.g., `<`, `{`, `[`) or space-eraser (``) -- no |
| 1097 | // leading space. Bare '<', '{', '[' cannot appear at position 0 of a valid |
| 1098 | // format. |
| 1099 | return !llvm::is_contained(Range: "<{([`" , Element: fmtStr[1]); |
| 1100 | } |
| 1101 | |
| 1102 | /// Emit the dialect printer/parser dispatcher. User's code should call these |
| 1103 | /// functions from their dialect's print/parse methods. |
| 1104 | void DefGenerator::emitParsePrintDispatch(ArrayRef<AttrOrTypeDef> defs) { |
| 1105 | if (llvm::none_of(Range&: defs, P: [](const AttrOrTypeDef &def) { |
| 1106 | return def.getMnemonic().has_value(); |
| 1107 | })) { |
| 1108 | return; |
| 1109 | } |
| 1110 | // Declare the parser. |
| 1111 | SmallVector<MethodParameter> params = {{"::mlir::AsmParser &" , "parser" }, |
| 1112 | {"::llvm::StringRef *" , "mnemonic" }}; |
| 1113 | if (isAttrGenerator) |
| 1114 | params.emplace_back(Args: "::mlir::Type" , Args: "type" ); |
| 1115 | params.emplace_back(Args: strfmt(fmt: "::mlir::{0} &" , parameters&: valueType), Args: "value" ); |
| 1116 | Method parse("::mlir::OptionalParseResult" , |
| 1117 | strfmt(fmt: "generated{0}Parser" , parameters&: valueType), Method::StaticInline, |
| 1118 | std::move(params)); |
| 1119 | // Declare the printer. |
| 1120 | Method printer("::llvm::LogicalResult" , |
| 1121 | strfmt(fmt: "generated{0}Printer" , parameters&: valueType), Method::StaticInline, |
| 1122 | {{strfmt(fmt: "::mlir::{0}" , parameters&: valueType), "def" }, |
| 1123 | {"::mlir::AsmPrinter &" , "printer" }}); |
| 1124 | |
| 1125 | // The parser dispatch uses a KeywordSwitch, matching on the mnemonic and |
| 1126 | // calling the def's parse function. The KeywordSwitch only parses the |
| 1127 | // mnemonic if `*mnemonic` is empty, so that callers can continue with a |
| 1128 | // mnemonic they already parsed, e.g. in another dispatch function. |
| 1129 | parse.body() << " return " |
| 1130 | "::mlir::AsmParser::KeywordSwitch<::mlir::" |
| 1131 | "OptionalParseResult>(parser, mnemonic)\n" ; |
| 1132 | const char *const getValueForMnemonic = |
| 1133 | R"( .Case({0}::getMnemonic(), [&](llvm::StringRef, llvm::SMLoc) {{ |
| 1134 | value = {0}::{1}; |
| 1135 | return ::mlir::success(!!value); |
| 1136 | }) |
| 1137 | )" ; |
| 1138 | |
| 1139 | // The printer dispatch uses llvm::TypeSwitch to find and call the correct |
| 1140 | // printer. |
| 1141 | printer.body() << " return ::llvm::TypeSwitch<::mlir::" << valueType |
| 1142 | << ", ::llvm::LogicalResult>(def)" ; |
| 1143 | const char *const printValue = R"( .Case<{0}>([&](auto t) {{ |
| 1144 | printer << {0}::getMnemonic();{1} |
| 1145 | return ::mlir::success(); |
| 1146 | }) |
| 1147 | )" ; |
| 1148 | for (const AttrOrTypeDef &def : defs) { |
| 1149 | if (!def.getMnemonic()) |
| 1150 | continue; |
| 1151 | |
| 1152 | bool hasParserPrinterDecl = |
| 1153 | def.hasCustomAssemblyFormat() || def.getAssemblyFormat(); |
| 1154 | std::string defClass = strfmt( |
| 1155 | fmt: "{0}::{1}" , parameters: def.getDialect().getCppNamespace(), parameters: def.getCppClassName()); |
| 1156 | |
| 1157 | // If the def has no parameters or parser code, invoke a normal `get`. |
| 1158 | std::string parseOrGet = |
| 1159 | hasParserPrinterDecl |
| 1160 | ? strfmt(fmt: "parse(parser{0})" , parameters: isAttrGenerator ? ", type" : "" ) |
| 1161 | : "get(parser.getContext())" ; |
| 1162 | parse.body() << llvm::formatv(Fmt: getValueForMnemonic, Vals&: defClass, Vals&: parseOrGet); |
| 1163 | |
| 1164 | // If the def has no parameters and no printer, just print the mnemonic. |
| 1165 | if (!hasParserPrinterDecl) { |
| 1166 | printer.body() << llvm::formatv(Fmt: printValue, Vals&: defClass, Vals: "" ); |
| 1167 | continue; |
| 1168 | } |
| 1169 | |
| 1170 | // Custom format: `print()` controls its own spacing. |
| 1171 | if (def.hasCustomAssemblyFormat()) { |
| 1172 | printer.body() << llvm::formatv(Fmt: printValue, Vals&: defClass, |
| 1173 | Vals: "\nt.print(printer);" ); |
| 1174 | continue; |
| 1175 | } |
| 1176 | |
| 1177 | // Declarative format: because `print()` doesn't emit a leading space, |
| 1178 | // add one here unless the format starts with punctuation or a |
| 1179 | // space-eraser directive that should attach directly to the mnemonic. |
| 1180 | StringRef printDef = needsLeadingSpace(def) |
| 1181 | ? "\nprinter << ' ';\nt.print(printer);" |
| 1182 | : "\nt.print(printer);" ; |
| 1183 | printer.body() << llvm::formatv(Fmt: printValue, Vals&: defClass, Vals&: printDef); |
| 1184 | } |
| 1185 | parse.body() << " .Default([&](llvm::StringRef keyword, llvm::SMLoc) {\n" |
| 1186 | " *mnemonic = keyword;\n" |
| 1187 | " return std::nullopt;\n" |
| 1188 | " });" ; |
| 1189 | printer.body() << " .Default([](auto) { return ::mlir::failure(); });" ; |
| 1190 | |
| 1191 | raw_indented_ostream indentedOs(os); |
| 1192 | parse.writeDeclTo(os&: indentedOs); |
| 1193 | printer.writeDeclTo(os&: indentedOs); |
| 1194 | } |
| 1195 | |
| 1196 | /// Headers declaring the C++ constructs used by every generated attribute or |
| 1197 | /// type definition, beyond those already included by the declarations. |
| 1198 | static constexpr StringRef attrOrTypeDefIncludes[] = { |
| 1199 | // `::llvm::TypeSwitch`. |
| 1200 | "llvm/ADT/TypeSwitch.h" , |
| 1201 | // `::mlir::Builder`. |
| 1202 | "mlir/IR/Builders.h" , |
| 1203 | // `::mlir::DialectAsmParser`, `::mlir::DialectAsmPrinter`, |
| 1204 | // `::mlir::FieldParser`. |
| 1205 | "mlir/IR/DialectImplementation.h" , |
| 1206 | // `::mlir::AsmParser`, `::mlir::AsmParser::KeywordSwitch`, |
| 1207 | // `::mlir::AsmPrinter`. |
| 1208 | "mlir/IR/OpImplementation.h" , |
| 1209 | }; |
| 1210 | |
| 1211 | bool DefGenerator::emitDefs(StringRef selectedDialect) { |
| 1212 | emitSourceFileHeader(Desc: (defType + "Def Definitions" ).str(), OS&: os); |
| 1213 | |
| 1214 | SmallVector<AttrOrTypeDef, 16> defs; |
| 1215 | collectAllDefs(selectedDialect, records: defRecords, resultDefs&: defs); |
| 1216 | if (defs.empty()) |
| 1217 | return false; |
| 1218 | emitTypeDefList(defs); |
| 1219 | |
| 1220 | llvm::IfDefEmitter scope(os, "GET_" + defType.upper() + "DEF_CLASSES" ); |
| 1221 | tblgen::emitIncludes(os, headers: attrOrTypeDefIncludes); |
| 1222 | emitParsePrintDispatch(defs); |
| 1223 | for (const AttrOrTypeDef &def : defs) { |
| 1224 | { |
| 1225 | DialectNamespaceEmitter ns(os, def.getDialect()); |
| 1226 | DefGen gen(def); |
| 1227 | gen.emitDef(os); |
| 1228 | } |
| 1229 | // Emit the TypeID explicit specializations to have a single symbol def. |
| 1230 | if (!def.getDialect().getCppNamespace().empty()) |
| 1231 | os << "MLIR_DEFINE_EXPLICIT_TYPE_ID(" |
| 1232 | << def.getDialect().getCppNamespace() << "::" << def.getCppClassName() |
| 1233 | << ")\n" ; |
| 1234 | } |
| 1235 | |
| 1236 | Dialect firstDialect = defs.front().getDialect(); |
| 1237 | |
| 1238 | // Emit the default parser/printer for Attributes if the dialect asked for it. |
| 1239 | if (isAttrGenerator && firstDialect.useDefaultAttributePrinterParser()) { |
| 1240 | DialectNamespaceEmitter nsEmitter(os, firstDialect); |
| 1241 | if (firstDialect.isExtensible()) { |
| 1242 | os << llvm::formatv(Fmt: dialectDefaultAttrPrinterParserDispatch, |
| 1243 | Vals: firstDialect.getCppClassName(), |
| 1244 | Vals: dialectDynamicAttrParserDispatch, |
| 1245 | Vals: dialectDynamicAttrPrinterDispatch); |
| 1246 | } else { |
| 1247 | os << llvm::formatv(Fmt: dialectDefaultAttrPrinterParserDispatch, |
| 1248 | Vals: firstDialect.getCppClassName(), Vals: "" , Vals: "" ); |
| 1249 | } |
| 1250 | } |
| 1251 | |
| 1252 | // Emit the default parser/printer for Types if the dialect asked for it. |
| 1253 | if (!isAttrGenerator && firstDialect.useDefaultTypePrinterParser()) { |
| 1254 | DialectNamespaceEmitter nsEmitter(os, firstDialect); |
| 1255 | if (firstDialect.isExtensible()) { |
| 1256 | os << llvm::formatv(Fmt: dialectDefaultTypePrinterParserDispatch, |
| 1257 | Vals: firstDialect.getCppClassName(), |
| 1258 | Vals: dialectDynamicTypeParserDispatch, |
| 1259 | Vals: dialectDynamicTypePrinterDispatch); |
| 1260 | } else { |
| 1261 | os << llvm::formatv(Fmt: dialectDefaultTypePrinterParserDispatch, |
| 1262 | Vals: firstDialect.getCppClassName(), Vals: "" , Vals: "" ); |
| 1263 | } |
| 1264 | } |
| 1265 | |
| 1266 | return false; |
| 1267 | } |
| 1268 | |
| 1269 | //===----------------------------------------------------------------------===// |
| 1270 | // Constraints |
| 1271 | //===----------------------------------------------------------------------===// |
| 1272 | |
| 1273 | /// Find all type constraints for which a C++ function should be generated. |
| 1274 | static std::vector<Constraint> getAllCppConstraints(const RecordKeeper &records, |
| 1275 | StringRef constraintKind) { |
| 1276 | std::vector<Constraint> result; |
| 1277 | for (const Record *def : |
| 1278 | records.getAllDerivedDefinitionsIfDefined(ClassName: constraintKind)) { |
| 1279 | // Ignore constraints defined outside of the top-level file. |
| 1280 | if (llvm::SrcMgr.FindBufferContainingLoc(Loc: def->getLoc()[0]) != |
| 1281 | llvm::SrcMgr.getMainFileID()) |
| 1282 | continue; |
| 1283 | Constraint constr(def); |
| 1284 | // Generate C++ function only if "cppFunctionName" is set. |
| 1285 | if (!constr.getCppFunctionName()) |
| 1286 | continue; |
| 1287 | result.push_back(x: constr); |
| 1288 | } |
| 1289 | return result; |
| 1290 | } |
| 1291 | |
| 1292 | static std::vector<Constraint> |
| 1293 | getAllCppTypeConstraints(const RecordKeeper &records) { |
| 1294 | return getAllCppConstraints(records, constraintKind: "TypeConstraint" ); |
| 1295 | } |
| 1296 | |
| 1297 | static std::vector<Constraint> |
| 1298 | getAllCppAttrConstraints(const RecordKeeper &records) { |
| 1299 | return getAllCppConstraints(records, constraintKind: "AttrConstraint" ); |
| 1300 | } |
| 1301 | |
| 1302 | /// Emit the declarations for the given constraints, of the form: |
| 1303 | /// `bool <constraintCppFunctionName>(<parameterTypeName> <parameterName>);` |
| 1304 | static void emitConstraintDecls(ArrayRef<Constraint> constraints, |
| 1305 | raw_ostream &os, StringRef parameterTypeName, |
| 1306 | StringRef parameterName) { |
| 1307 | static const char *const constraintDecl = "bool {0}({1} {2});\n" ; |
| 1308 | for (Constraint constr : constraints) |
| 1309 | os << strfmt(fmt: constraintDecl, parameters: *constr.getCppFunctionName(), |
| 1310 | parameters&: parameterTypeName, parameters&: parameterName); |
| 1311 | } |
| 1312 | |
| 1313 | static void emitTypeConstraintDecls(const RecordKeeper &records, |
| 1314 | raw_ostream &os) { |
| 1315 | emitConstraintDecls(constraints: getAllCppTypeConstraints(records), os, parameterTypeName: "::mlir::Type" , |
| 1316 | parameterName: "type" ); |
| 1317 | } |
| 1318 | |
| 1319 | static void emitAttrConstraintDecls(const RecordKeeper &records, |
| 1320 | raw_ostream &os) { |
| 1321 | emitConstraintDecls(constraints: getAllCppAttrConstraints(records), os, |
| 1322 | parameterTypeName: "::mlir::Attribute" , parameterName: "attr" ); |
| 1323 | } |
| 1324 | |
| 1325 | /// Emit the definitions for the given constraints, of the form: |
| 1326 | /// `bool <constraintCppFunctionName>(<parameterTypeName> <parameterName>) { |
| 1327 | /// return (<condition>); }` |
| 1328 | /// where `<condition>` is the condition template with the `self` variable |
| 1329 | /// replaced with the `selfName` parameter. |
| 1330 | static void emitConstraintDefs(ArrayRef<Constraint> constraints, |
| 1331 | raw_ostream &os, StringRef parameterTypeName, |
| 1332 | StringRef selfName) { |
| 1333 | static const char *const constraintDef = R"( |
| 1334 | bool {0}({1} {2}) { |
| 1335 | return ({3}); |
| 1336 | } |
| 1337 | )" ; |
| 1338 | |
| 1339 | for (Constraint constr : constraints) { |
| 1340 | FmtContext ctx; |
| 1341 | ctx.withSelf(subst: selfName); |
| 1342 | std::string condition = tgfmt(fmt: constr.getConditionTemplate(), ctx: &ctx); |
| 1343 | os << strfmt(fmt: constraintDef, parameters: *constr.getCppFunctionName(), parameters&: parameterTypeName, |
| 1344 | parameters&: selfName, parameters&: condition); |
| 1345 | } |
| 1346 | } |
| 1347 | |
| 1348 | static void emitTypeConstraintDefs(const RecordKeeper &records, |
| 1349 | raw_ostream &os) { |
| 1350 | emitConstraintDefs(constraints: getAllCppTypeConstraints(records), os, parameterTypeName: "::mlir::Type" , |
| 1351 | selfName: "type" ); |
| 1352 | } |
| 1353 | |
| 1354 | static void emitAttrConstraintDefs(const RecordKeeper &records, |
| 1355 | raw_ostream &os) { |
| 1356 | emitConstraintDefs(constraints: getAllCppAttrConstraints(records), os, parameterTypeName: "::mlir::Attribute" , |
| 1357 | selfName: "attr" ); |
| 1358 | } |
| 1359 | |
| 1360 | //===----------------------------------------------------------------------===// |
| 1361 | // GEN: Registration hooks |
| 1362 | //===----------------------------------------------------------------------===// |
| 1363 | |
| 1364 | //===----------------------------------------------------------------------===// |
| 1365 | // AttrDef |
| 1366 | //===----------------------------------------------------------------------===// |
| 1367 | |
| 1368 | static llvm::cl::OptionCategory attrdefGenCat("Options for -gen-attrdef-*" ); |
| 1369 | static llvm::cl::opt<std::string> |
| 1370 | attrDialect("attrdefs-dialect" , |
| 1371 | llvm::cl::desc("Generate attributes for this dialect" ), |
| 1372 | llvm::cl::cat(attrdefGenCat), llvm::cl::CommaSeparated); |
| 1373 | |
| 1374 | static mlir::GenRegistration |
| 1375 | genAttrDefs("gen-attrdef-defs" , "Generate AttrDef definitions" , |
| 1376 | [](const RecordKeeper &records, raw_ostream &os) { |
| 1377 | AttrDefGenerator generator(records, os); |
| 1378 | return generator.emitDefs(selectedDialect: attrDialect); |
| 1379 | }); |
| 1380 | static mlir::GenRegistration |
| 1381 | genAttrDecls("gen-attrdef-decls" , "Generate AttrDef declarations" , |
| 1382 | [](const RecordKeeper &records, raw_ostream &os) { |
| 1383 | AttrDefGenerator generator(records, os); |
| 1384 | return generator.emitDecls(selectedDialect: attrDialect); |
| 1385 | }); |
| 1386 | |
| 1387 | static mlir::GenRegistration |
| 1388 | genAttrConstrDefs("gen-attr-constraint-defs" , |
| 1389 | "Generate attribute constraint definitions" , |
| 1390 | [](const RecordKeeper &records, raw_ostream &os) { |
| 1391 | emitAttrConstraintDefs(records, os); |
| 1392 | return false; |
| 1393 | }); |
| 1394 | static mlir::GenRegistration |
| 1395 | genAttrConstrDecls("gen-attr-constraint-decls" , |
| 1396 | "Generate attribute constraint declarations" , |
| 1397 | [](const RecordKeeper &records, raw_ostream &os) { |
| 1398 | emitAttrConstraintDecls(records, os); |
| 1399 | return false; |
| 1400 | }); |
| 1401 | |
| 1402 | //===----------------------------------------------------------------------===// |
| 1403 | // TypeDef |
| 1404 | //===----------------------------------------------------------------------===// |
| 1405 | |
| 1406 | static llvm::cl::OptionCategory typedefGenCat("Options for -gen-typedef-*" ); |
| 1407 | static llvm::cl::opt<std::string> |
| 1408 | typeDialect("typedefs-dialect" , |
| 1409 | llvm::cl::desc("Generate types for this dialect" ), |
| 1410 | llvm::cl::cat(typedefGenCat), llvm::cl::CommaSeparated); |
| 1411 | |
| 1412 | static mlir::GenRegistration |
| 1413 | genTypeDefs("gen-typedef-defs" , "Generate TypeDef definitions" , |
| 1414 | [](const RecordKeeper &records, raw_ostream &os) { |
| 1415 | TypeDefGenerator generator(records, os); |
| 1416 | return generator.emitDefs(selectedDialect: typeDialect); |
| 1417 | }); |
| 1418 | static mlir::GenRegistration |
| 1419 | genTypeDecls("gen-typedef-decls" , "Generate TypeDef declarations" , |
| 1420 | [](const RecordKeeper &records, raw_ostream &os) { |
| 1421 | TypeDefGenerator generator(records, os); |
| 1422 | return generator.emitDecls(selectedDialect: typeDialect); |
| 1423 | }); |
| 1424 | |
| 1425 | static mlir::GenRegistration |
| 1426 | genTypeConstrDefs("gen-type-constraint-defs" , |
| 1427 | "Generate type constraint definitions" , |
| 1428 | [](const RecordKeeper &records, raw_ostream &os) { |
| 1429 | emitTypeConstraintDefs(records, os); |
| 1430 | return false; |
| 1431 | }); |
| 1432 | static mlir::GenRegistration |
| 1433 | genTypeConstrDecls("gen-type-constraint-decls" , |
| 1434 | "Generate type constraint declarations" , |
| 1435 | [](const RecordKeeper &records, raw_ostream &os) { |
| 1436 | emitTypeConstraintDecls(records, os); |
| 1437 | return false; |
| 1438 | }); |
| 1439 | |