MLIR  22.0.0git
TransformDialect.cpp
Go to the documentation of this file.
1 //===- TransformDialect.cpp - Transform Dialect Definition ----------------===//
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 
16 #include "llvm/ADT/SCCIterator.h"
17 #include "llvm/ADT/TypeSwitch.h"
18 
19 using namespace mlir;
20 
21 #include "mlir/Dialect/Transform/IR/TransformDialect.cpp.inc"
22 
23 #define GET_ATTRDEF_CLASSES
24 #include "mlir/Dialect/Transform/IR/TransformAttrs.cpp.inc"
25 
26 #ifndef NDEBUG
28  StringRef name, MLIRContext *context) {
29  // Since the operation is being inserted into the Transform dialect and the
30  // dialect does not implement the interface fallback, only check for the op
31  // itself having the interface implementation.
33  *RegisteredOperationName::lookup(name, context);
34  assert((opName.hasInterface<TransformOpInterface>() ||
35  opName.hasInterface<PatternDescriptorOpInterface>() ||
36  opName.hasInterface<ConversionPatternDescriptorOpInterface>() ||
37  opName.hasInterface<TypeConverterBuilderOpInterface>() ||
38  opName.hasTrait<OpTrait::IsTerminator>()) &&
39  "non-terminator ops injected into the transform dialect must "
40  "implement TransformOpInterface or PatternDescriptorOpInterface or "
41  "ConversionPatternDescriptorOpInterface");
42  if (!opName.hasInterface<PatternDescriptorOpInterface>() &&
43  !opName.hasInterface<ConversionPatternDescriptorOpInterface>() &&
44  !opName.hasInterface<TypeConverterBuilderOpInterface>()) {
45  assert(opName.hasInterface<MemoryEffectOpInterface>() &&
46  "ops injected into the transform dialect must implement "
47  "MemoryEffectsOpInterface");
48  }
49 }
50 
52  TypeID typeID, MLIRContext *context) {
53  const auto &abstractType = AbstractType::lookup(typeID, context);
54  assert((abstractType.hasInterface(
55  TransformHandleTypeInterface::getInterfaceID()) ||
56  abstractType.hasInterface(
57  TransformParamTypeInterface::getInterfaceID()) ||
58  abstractType.hasInterface(
59  TransformValueHandleTypeInterface::getInterfaceID())) &&
60  "expected Transform dialect type to implement one of the three "
61  "interfaces");
62 }
63 #endif // NDEBUG
64 
65 void transform::TransformDialect::initialize() {
66  // Using the checked versions to enable the same assertions as for the ops
67  // from extensions.
68  addOperationsChecked<
69 #define GET_OP_LIST
70 #include "mlir/Dialect/Transform/IR/TransformOps.cpp.inc"
71  >();
72  initializeTypes();
73  addAttributes<
74 #define GET_ATTRDEF_LIST
75 #include "mlir/Dialect/Transform/IR/TransformAttrs.cpp.inc"
76  >();
77  initializeLibraryModule();
78 }
79 
81  StringRef keyword;
82  SMLoc loc = parser.getCurrentLocation();
83  if (failed(parser.parseKeyword(&keyword)))
84  return nullptr;
85 
86  auto it = typeParsingHooks.find(keyword);
87  if (it == typeParsingHooks.end()) {
88  parser.emitError(loc) << "unknown type mnemonic: " << keyword;
89  return nullptr;
90  }
91 
92  return it->getValue()(parser);
93 }
94 
96  DialectAsmPrinter &printer) const {
97  auto it = typePrintingHooks.find(type.getTypeID());
98  assert(it != typePrintingHooks.end() && "printing unknown type");
99  it->getSecond()(type, printer);
100 }
101 
102 LogicalResult transform::TransformDialect::loadIntoLibraryModule(
104  return detail::mergeSymbolsInto(getLibraryModule(), std::move(library));
105 }
106 
107 void transform::TransformDialect::initializeLibraryModule() {
108  MLIRContext *context = getContext();
109  auto loc =
110  FileLineColLoc::get(context, "<transform-dialect-library-module>", 0, 0);
111  libraryModule = ModuleOp::create(loc, "__transform_library");
112  libraryModule.get()->setAttr(TransformDialect::kWithNamedSequenceAttrName,
113  UnitAttr::get(context));
114 }
115 
116 void transform::TransformDialect::reportDuplicateTypeRegistration(
117  StringRef mnemonic) {
118  std::string buffer;
119  llvm::raw_string_ostream msg(buffer);
120  msg << "extensible dialect type '" << mnemonic
121  << "' is already registered with a different implementation";
122  llvm::report_fatal_error(StringRef(buffer));
123 }
124 
125 void transform::TransformDialect::reportDuplicateOpRegistration(
126  StringRef opName) {
127  std::string buffer;
128  llvm::raw_string_ostream msg(buffer);
129  msg << "extensible dialect operation '" << opName
130  << "' is already registered with a mismatching TypeID";
131  llvm::report_fatal_error(StringRef(buffer));
132 }
133 
134 LogicalResult transform::TransformDialect::verifyOperationAttribute(
135  Operation *op, NamedAttribute attribute) {
136  if (attribute.getName().getValue() == kWithNamedSequenceAttrName) {
137  if (!op->hasTrait<OpTrait::SymbolTable>()) {
138  return emitError(op->getLoc()) << attribute.getName()
139  << " attribute can only be attached to "
140  "operations with symbol tables";
141  }
142 
143  const mlir::CallGraph callgraph(op);
144  for (auto scc = llvm::scc_begin(&callgraph); !scc.isAtEnd(); ++scc) {
145  if (!scc.hasCycle())
146  continue;
147 
148  // Need to check this here additionally because this verification may run
149  // before we check the nested operations.
150  if ((*scc->begin())->isExternal())
151  return op->emitOpError() << "contains a call to an external operation, "
152  "which is not allowed";
153 
154  Operation *first = (*scc->begin())->getCallableRegion()->getParentOp();
156  << "recursion not allowed in named sequences";
157  for (auto it = std::next(scc->begin()); it != scc->end(); ++it) {
158  // Need to check this here additionally because this verification may
159  // run before we check the nested operations.
160  if ((*it)->isExternal()) {
161  return op->emitOpError() << "contains a call to an external "
162  "operation, which is not allowed";
163  }
164 
165  Operation *current = (*it)->getCallableRegion()->getParentOp();
166  diag.attachNote(current->getLoc()) << "operation on recursion stack";
167  }
168  return diag;
169  }
170  return success();
171  }
172  if (attribute.getName().getValue() == kTargetTagAttrName) {
173  if (!llvm::isa<StringAttr>(attribute.getValue())) {
174  return op->emitError()
175  << attribute.getName() << " attribute must be a string";
176  }
177  return success();
178  }
179  if (attribute.getName().getValue() == kArgConsumedAttrName ||
180  attribute.getName().getValue() == kArgReadOnlyAttrName) {
181  if (!llvm::isa<UnitAttr>(attribute.getValue())) {
182  return op->emitError()
183  << attribute.getName() << " must be a unit attribute";
184  }
185  return success();
186  }
187  if (attribute.getName().getValue() ==
188  FindPayloadReplacementOpInterface::kSilenceTrackingFailuresAttrName) {
189  if (!llvm::isa<UnitAttr>(attribute.getValue())) {
190  return op->emitError()
191  << attribute.getName() << " must be a unit attribute";
192  }
193  return success();
194  }
195  return emitError(op->getLoc())
196  << "unknown attribute: " << attribute.getName();
197 }
static MLIRContext * getContext(OpFoldResult val)
static std::string diag(const llvm::Value &value)
static const AbstractType & lookup(TypeID typeID, MLIRContext *context)
Look up the specified abstract type in the MLIRContext and return a reference to it.
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
The DialectAsmParser has methods for interacting with the asm parser when parsing attributes and type...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
static FileLineColLoc get(StringAttr filename, unsigned line, unsigned column)
Definition: Location.cpp:157
This class represents a diagnostic that is inflight and set to be reported.
Definition: Diagnostics.h:314
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:63
NamedAttribute represents a combination of a name and an Attribute value.
Definition: Attributes.h:164
StringAttr getName() const
Return the name of the attribute.
Definition: Attributes.cpp:55
Attribute getValue() const
Return the value of the attribute.
Definition: Attributes.h:179
This class provides the API for ops that are known to be terminators.
Definition: OpDefinition.h:773
A trait used to provide symbol table functionalities to a region operation.
Definition: SymbolTable.h:452
bool hasTrait() const
Returns true if the operation was registered with a particular trait, e.g.
bool hasInterface() const
Returns true if this operation has the given interface registered to it.
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition: Operation.h:749
Location getLoc()
The source location the operation was defined or derived from.
Definition: Operation.h:223
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition: Operation.h:234
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
Definition: Operation.cpp:267
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
Definition: Operation.cpp:672
This class acts as an owning reference to an op, and will automatically destroy the held op on destru...
Definition: OwningOpRef.h:29
This is a "type erased" representation of a registered operation.
static std::optional< RegisteredOperationName > lookup(StringRef name, MLIRContext *ctx)
Lookup the registered operation information for the given operation.
This class provides an efficient unique identifier for a specific C++ type.
Definition: TypeID.h:107
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:74
TypeID getTypeID()
Return a unique identifier for the concrete type.
Definition: Types.h:101
void printType(Type type, AsmPrinter &printer)
Prints an LLVM Dialect type.
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition: Remarks.h:491
InFlightDiagnostic mergeSymbolsInto(Operation *target, OwningOpRef< Operation * > other)
Merge all symbols from other into target.
Definition: Utils.cpp:80
void checkImplementsTransformHandleTypeInterface(TypeID typeID, MLIRContext *context)
Asserts that the type provided as template argument implements the TransformHandleTypeInterface.
void checkImplementsTransformOpInterface(StringRef name, MLIRContext *context)
Asserts that the operations provided as template arguments implement the TransformOpInterface and Mem...
Include the generated interface declarations.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
Type parseType(llvm::StringRef typeStr, MLIRContext *context, size_t *numRead=nullptr, bool isKnownNullTerminated=false)
This parses a single MLIR type to an MLIR context if it was valid.