1 //===- Dialect.cpp - Toy IR Dialect registration in MLIR ------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the dialect for the Toy IR: custom type parsing and 10 // operation verification. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "toy/Dialect.h" 15 16 #include "mlir/IR/Builders.h" 17 #include "mlir/IR/DialectImplementation.h" 18 #include "mlir/IR/OpImplementation.h" 19 #include "mlir/IR/StandardTypes.h" 20 #include "mlir/Transforms/InliningUtils.h" 21 22 using namespace mlir; 23 using namespace mlir::toy; 24 25 //===----------------------------------------------------------------------===// 26 // ToyInlinerInterface 27 //===----------------------------------------------------------------------===// 28 29 /// This class defines the interface for handling inlining with Toy 30 /// operations. 31 struct ToyInlinerInterface : public DialectInlinerInterface { 32 using DialectInlinerInterface::DialectInlinerInterface; 33 34 //===--------------------------------------------------------------------===// 35 // Analysis Hooks 36 //===--------------------------------------------------------------------===// 37 38 /// All operations within toy can be inlined. 39 bool isLegalToInline(Operation *, Region *, 40 BlockAndValueMapping &) const final { 41 return true; 42 } 43 44 //===--------------------------------------------------------------------===// 45 // Transformation Hooks 46 //===--------------------------------------------------------------------===// 47 48 /// Handle the given inlined terminator(toy.return) by replacing it with a new 49 /// operation as necessary. 50 void handleTerminator(Operation *op, 51 ArrayRef<Value> valuesToRepl) const final { 52 // Only "toy.return" needs to be handled here. 53 auto returnOp = cast<ReturnOp>(op); 54 55 // Replace the values directly with the return operands. 56 assert(returnOp.getNumOperands() == valuesToRepl.size()); 57 for (const auto &it : llvm::enumerate(returnOp.getOperands())) 58 valuesToRepl[it.index()].replaceAllUsesWith(it.value()); 59 } 60 61 /// Attempts to materialize a conversion for a type mismatch between a call 62 /// from this dialect, and a callable region. This method should generate an 63 /// operation that takes 'input' as the only operand, and produces a single 64 /// result of 'resultType'. If a conversion can not be generated, nullptr 65 /// should be returned. 66 Operation *materializeCallConversion(OpBuilder &builder, Value input, 67 Type resultType, 68 Location conversionLoc) const final { 69 return builder.create<CastOp>(conversionLoc, resultType, input); 70 } 71 }; 72 73 //===----------------------------------------------------------------------===// 74 // ToyDialect 75 //===----------------------------------------------------------------------===// 76 77 /// Dialect creation, the instance will be owned by the context. This is the 78 /// point of registration of custom types and operations for the dialect. 79 ToyDialect::ToyDialect(mlir::MLIRContext *ctx) : mlir::Dialect("toy", ctx) { 80 addOperations< 81 #define GET_OP_LIST 82 #include "toy/Ops.cpp.inc" 83 >(); 84 addInterfaces<ToyInlinerInterface>(); 85 addTypes<StructType>(); 86 } 87 88 mlir::Operation *ToyDialect::materializeConstant(mlir::OpBuilder &builder, 89 mlir::Attribute value, 90 mlir::Type type, 91 mlir::Location loc) { 92 if (type.isa<StructType>()) 93 return builder.create<StructConstantOp>(loc, type, 94 value.cast<mlir::ArrayAttr>()); 95 return builder.create<ConstantOp>(loc, type, 96 value.cast<mlir::DenseElementsAttr>()); 97 } 98 99 //===----------------------------------------------------------------------===// 100 // Toy Operations 101 //===----------------------------------------------------------------------===// 102 103 /// A generalized parser for binary operations. This parses the different forms 104 /// of 'printBinaryOp' below. 105 static mlir::ParseResult parseBinaryOp(mlir::OpAsmParser &parser, 106 mlir::OperationState &result) { 107 SmallVector<mlir::OpAsmParser::OperandType, 2> operands; 108 llvm::SMLoc operandsLoc = parser.getCurrentLocation(); 109 Type type; 110 if (parser.parseOperandList(operands, /*requiredOperandCount=*/2) || 111 parser.parseOptionalAttrDict(result.attributes) || 112 parser.parseColonType(type)) 113 return mlir::failure(); 114 115 // If the type is a function type, it contains the input and result types of 116 // this operation. 117 if (FunctionType funcType = type.dyn_cast<FunctionType>()) { 118 if (parser.resolveOperands(operands, funcType.getInputs(), operandsLoc, 119 result.operands)) 120 return mlir::failure(); 121 result.addTypes(funcType.getResults()); 122 return mlir::success(); 123 } 124 125 // Otherwise, the parsed type is the type of both operands and results. 126 if (parser.resolveOperands(operands, type, result.operands)) 127 return mlir::failure(); 128 result.addTypes(type); 129 return mlir::success(); 130 } 131 132 /// A generalized printer for binary operations. It prints in two different 133 /// forms depending on if all of the types match. 134 static void printBinaryOp(mlir::OpAsmPrinter &printer, mlir::Operation *op) { 135 printer << op->getName() << " " << op->getOperands(); 136 printer.printOptionalAttrDict(op->getAttrs()); 137 printer << " : "; 138 139 // If all of the types are the same, print the type directly. 140 Type resultType = *op->result_type_begin(); 141 if (llvm::all_of(op->getOperandTypes(), 142 [=](Type type) { return type == resultType; })) { 143 printer << resultType; 144 return; 145 } 146 147 // Otherwise, print a functional type. 148 printer.printFunctionalType(op->getOperandTypes(), op->getResultTypes()); 149 } 150 151 //===----------------------------------------------------------------------===// 152 // ConstantOp 153 154 /// Build a constant operation. 155 /// The builder is passed as an argument, so is the state that this method is 156 /// expected to fill in order to build the operation. 157 void ConstantOp::build(mlir::Builder *builder, mlir::OperationState &state, 158 double value) { 159 auto dataType = RankedTensorType::get({}, builder->getF64Type()); 160 auto dataAttribute = DenseElementsAttr::get(dataType, value); 161 ConstantOp::build(builder, state, dataType, dataAttribute); 162 } 163 164 /// The 'OpAsmPrinter' class provides a collection of methods for parsing 165 /// various punctuation, as well as attributes, operands, types, etc. Each of 166 /// these methods returns a `ParseResult`. This class is a wrapper around 167 /// `LogicalResult` that can be converted to a boolean `true` value on failure, 168 /// or `false` on success. This allows for easily chaining together a set of 169 /// parser rules. These rules are used to populate an `mlir::OperationState` 170 /// similarly to the `build` methods described above. 171 static mlir::ParseResult parseConstantOp(mlir::OpAsmParser &parser, 172 mlir::OperationState &result) { 173 mlir::DenseElementsAttr value; 174 if (parser.parseOptionalAttrDict(result.attributes) || 175 parser.parseAttribute(value, "value", result.attributes)) 176 return failure(); 177 178 result.addTypes(value.getType()); 179 return success(); 180 } 181 182 /// The 'OpAsmPrinter' class is a stream that will allows for formatting 183 /// strings, attributes, operands, types, etc. 184 static void print(mlir::OpAsmPrinter &printer, ConstantOp op) { 185 printer << "toy.constant "; 186 printer.printOptionalAttrDict(op.getAttrs(), /*elidedAttrs=*/{"value"}); 187 printer << op.value(); 188 } 189 190 /// Verify that the given attribute value is valid for the given type. 191 static mlir::LogicalResult verifyConstantForType(mlir::Type type, 192 mlir::Attribute opaqueValue, 193 mlir::Operation *op) { 194 if (type.isa<mlir::TensorType>()) { 195 // Check that the value is an elements attribute. 196 auto attrValue = opaqueValue.dyn_cast<mlir::DenseFPElementsAttr>(); 197 if (!attrValue) 198 return op->emitError("constant of TensorType must be initialized by " 199 "a DenseFPElementsAttr, got ") 200 << opaqueValue; 201 202 // If the return type of the constant is not an unranked tensor, the shape 203 // must match the shape of the attribute holding the data. 204 auto resultType = type.dyn_cast<mlir::RankedTensorType>(); 205 if (!resultType) 206 return success(); 207 208 // Check that the rank of the attribute type matches the rank of the 209 // constant result type. 210 auto attrType = attrValue.getType().cast<mlir::TensorType>(); 211 if (attrType.getRank() != resultType.getRank()) { 212 return op->emitOpError("return type must match the one of the attached " 213 "value attribute: ") 214 << attrType.getRank() << " != " << resultType.getRank(); 215 } 216 217 // Check that each of the dimensions match between the two types. 218 for (int dim = 0, dimE = attrType.getRank(); dim < dimE; ++dim) { 219 if (attrType.getShape()[dim] != resultType.getShape()[dim]) { 220 return op->emitOpError( 221 "return type shape mismatches its attribute at dimension ") 222 << dim << ": " << attrType.getShape()[dim] 223 << " != " << resultType.getShape()[dim]; 224 } 225 } 226 return mlir::success(); 227 } 228 auto resultType = type.cast<StructType>(); 229 llvm::ArrayRef<mlir::Type> resultElementTypes = resultType.getElementTypes(); 230 231 // Verify that the initializer is an Array. 232 auto attrValue = opaqueValue.dyn_cast<ArrayAttr>(); 233 if (!attrValue || attrValue.getValue().size() != resultElementTypes.size()) 234 return op->emitError("constant of StructType must be initialized by an " 235 "ArrayAttr with the same number of elements, got ") 236 << opaqueValue; 237 238 // Check that each of the elements are valid. 239 llvm::ArrayRef<mlir::Attribute> attrElementValues = attrValue.getValue(); 240 for (const auto &it : llvm::zip(resultElementTypes, attrElementValues)) 241 if (failed(verifyConstantForType(std::get<0>(it), std::get<1>(it), op))) 242 return mlir::failure(); 243 return mlir::success(); 244 } 245 246 /// Verifier for the constant operation. This corresponds to the `::verify(...)` 247 /// in the op definition. 248 static mlir::LogicalResult verify(ConstantOp op) { 249 return verifyConstantForType(op.getResult().getType(), op.value(), op); 250 } 251 252 static mlir::LogicalResult verify(StructConstantOp op) { 253 return verifyConstantForType(op.getResult().getType(), op.value(), op); 254 } 255 256 /// Infer the output shape of the ConstantOp, this is required by the shape 257 /// inference interface. 258 void ConstantOp::inferShapes() { getResult().setType(value().getType()); } 259 260 //===----------------------------------------------------------------------===// 261 // AddOp 262 263 void AddOp::build(mlir::Builder *builder, mlir::OperationState &state, 264 mlir::Value lhs, mlir::Value rhs) { 265 state.addTypes(UnrankedTensorType::get(builder->getF64Type())); 266 state.addOperands({lhs, rhs}); 267 } 268 269 /// Infer the output shape of the AddOp, this is required by the shape inference 270 /// interface. 271 void AddOp::inferShapes() { getResult().setType(getOperand(0).getType()); } 272 273 //===----------------------------------------------------------------------===// 274 // CastOp 275 276 /// Infer the output shape of the CastOp, this is required by the shape 277 /// inference interface. 278 void CastOp::inferShapes() { getResult().setType(getOperand().getType()); } 279 280 //===----------------------------------------------------------------------===// 281 // GenericCallOp 282 283 void GenericCallOp::build(mlir::Builder *builder, mlir::OperationState &state, 284 StringRef callee, ArrayRef<mlir::Value> arguments) { 285 // Generic call always returns an unranked Tensor initially. 286 state.addTypes(UnrankedTensorType::get(builder->getF64Type())); 287 state.addOperands(arguments); 288 state.addAttribute("callee", builder->getSymbolRefAttr(callee)); 289 } 290 291 /// Return the callee of the generic call operation, this is required by the 292 /// call interface. 293 CallInterfaceCallable GenericCallOp::getCallableForCallee() { 294 return getAttrOfType<SymbolRefAttr>("callee"); 295 } 296 297 /// Get the argument operands to the called function, this is required by the 298 /// call interface. 299 Operation::operand_range GenericCallOp::getArgOperands() { return inputs(); } 300 301 //===----------------------------------------------------------------------===// 302 // MulOp 303 304 void MulOp::build(mlir::Builder *builder, mlir::OperationState &state, 305 mlir::Value lhs, mlir::Value rhs) { 306 state.addTypes(UnrankedTensorType::get(builder->getF64Type())); 307 state.addOperands({lhs, rhs}); 308 } 309 310 /// Infer the output shape of the MulOp, this is required by the shape inference 311 /// interface. 312 void MulOp::inferShapes() { getResult().setType(getOperand(0).getType()); } 313 314 //===----------------------------------------------------------------------===// 315 // ReturnOp 316 317 static mlir::LogicalResult verify(ReturnOp op) { 318 // We know that the parent operation is a function, because of the 'HasParent' 319 // trait attached to the operation definition. 320 auto function = cast<FuncOp>(op.getParentOp()); 321 322 /// ReturnOps can only have a single optional operand. 323 if (op.getNumOperands() > 1) 324 return op.emitOpError() << "expects at most 1 return operand"; 325 326 // The operand number and types must match the function signature. 327 const auto &results = function.getType().getResults(); 328 if (op.getNumOperands() != results.size()) 329 return op.emitOpError() 330 << "does not return the same number of values (" 331 << op.getNumOperands() << ") as the enclosing function (" 332 << results.size() << ")"; 333 334 // If the operation does not have an input, we are done. 335 if (!op.hasOperand()) 336 return mlir::success(); 337 338 auto inputType = *op.operand_type_begin(); 339 auto resultType = results.front(); 340 341 // Check that the result type of the function matches the operand type. 342 if (inputType == resultType || inputType.isa<mlir::UnrankedTensorType>() || 343 resultType.isa<mlir::UnrankedTensorType>()) 344 return mlir::success(); 345 346 return op.emitError() << "type of return operand (" 347 << *op.operand_type_begin() 348 << ") doesn't match function result type (" 349 << results.front() << ")"; 350 } 351 352 //===----------------------------------------------------------------------===// 353 // StructAccessOp 354 355 void StructAccessOp::build(mlir::Builder *b, mlir::OperationState &state, 356 mlir::Value input, size_t index) { 357 // Extract the result type from the input type. 358 StructType structTy = input.getType().cast<StructType>(); 359 assert(index < structTy.getNumElementTypes()); 360 mlir::Type resultType = structTy.getElementTypes()[index]; 361 362 // Call into the auto-generated build method. 363 build(b, state, resultType, input, b->getI64IntegerAttr(index)); 364 } 365 366 static mlir::LogicalResult verify(StructAccessOp op) { 367 StructType structTy = op.input().getType().cast<StructType>(); 368 size_t index = op.index().getZExtValue(); 369 if (index >= structTy.getNumElementTypes()) 370 return op.emitOpError() 371 << "index should be within the range of the input struct type"; 372 mlir::Type resultType = op.getResult().getType(); 373 if (resultType != structTy.getElementTypes()[index]) 374 return op.emitOpError() << "must have the same result type as the struct " 375 "element referred to by the index"; 376 return mlir::success(); 377 } 378 379 //===----------------------------------------------------------------------===// 380 // TransposeOp 381 382 void TransposeOp::build(mlir::Builder *builder, mlir::OperationState &state, 383 mlir::Value value) { 384 state.addTypes(UnrankedTensorType::get(builder->getF64Type())); 385 state.addOperands(value); 386 } 387 388 void TransposeOp::inferShapes() { 389 auto arrayTy = getOperand().getType().cast<RankedTensorType>(); 390 SmallVector<int64_t, 2> dims(llvm::reverse(arrayTy.getShape())); 391 getResult().setType(RankedTensorType::get(dims, arrayTy.getElementType())); 392 } 393 394 static mlir::LogicalResult verify(TransposeOp op) { 395 auto inputType = op.getOperand().getType().dyn_cast<RankedTensorType>(); 396 auto resultType = op.getType().dyn_cast<RankedTensorType>(); 397 if (!inputType || !resultType) 398 return mlir::success(); 399 400 auto inputShape = inputType.getShape(); 401 if (!std::equal(inputShape.begin(), inputShape.end(), 402 resultType.getShape().rbegin())) { 403 return op.emitError() 404 << "expected result shape to be a transpose of the input"; 405 } 406 return mlir::success(); 407 } 408 409 //===----------------------------------------------------------------------===// 410 // Toy Types 411 //===----------------------------------------------------------------------===// 412 413 namespace mlir { 414 namespace toy { 415 namespace detail { 416 /// This class represents the internal storage of the Toy `StructType`. 417 struct StructTypeStorage : public mlir::TypeStorage { 418 /// The `KeyTy` is a required type that provides an interface for the storage 419 /// instance. This type will be used when uniquing an instance of the type 420 /// storage. For our struct type, we will unique each instance structurally on 421 /// the elements that it contains. 422 using KeyTy = llvm::ArrayRef<mlir::Type>; 423 424 /// A constructor for the type storage instance. 425 StructTypeStorage(llvm::ArrayRef<mlir::Type> elementTypes) 426 : elementTypes(elementTypes) {} 427 428 /// Define the comparison function for the key type with the current storage 429 /// instance. This is used when constructing a new instance to ensure that we 430 /// haven't already uniqued an instance of the given key. 431 bool operator==(const KeyTy &key) const { return key == elementTypes; } 432 433 /// Define a hash function for the key type. This is used when uniquing 434 /// instances of the storage, see the `StructType::get` method. 435 /// Note: This method isn't necessary as both llvm::ArrayRef and mlir::Type 436 /// have hash functions available, so we could just omit this entirely. 437 static llvm::hash_code hashKey(const KeyTy &key) { 438 return llvm::hash_value(key); 439 } 440 441 /// Define a construction function for the key type from a set of parameters. 442 /// These parameters will be provided when constructing the storage instance 443 /// itself. 444 /// Note: This method isn't necessary because KeyTy can be directly 445 /// constructed with the given parameters. 446 static KeyTy getKey(llvm::ArrayRef<mlir::Type> elementTypes) { 447 return KeyTy(elementTypes); 448 } 449 450 /// Define a construction method for creating a new instance of this storage. 451 /// This method takes an instance of a storage allocator, and an instance of a 452 /// `KeyTy`. The given allocator must be used for *all* necessary dynamic 453 /// allocations used to create the type storage and its internal. 454 static StructTypeStorage *construct(mlir::TypeStorageAllocator &allocator, 455 const KeyTy &key) { 456 // Copy the elements from the provided `KeyTy` into the allocator. 457 llvm::ArrayRef<mlir::Type> elementTypes = allocator.copyInto(key); 458 459 // Allocate the storage instance and construct it. 460 return new (allocator.allocate<StructTypeStorage>()) 461 StructTypeStorage(elementTypes); 462 } 463 464 /// The following field contains the element types of the struct. 465 llvm::ArrayRef<mlir::Type> elementTypes; 466 }; 467 } // end namespace detail 468 } // end namespace toy 469 } // end namespace mlir 470 471 /// Create an instance of a `StructType` with the given element types. There 472 /// *must* be at least one element type. 473 StructType StructType::get(llvm::ArrayRef<mlir::Type> elementTypes) { 474 assert(!elementTypes.empty() && "expected at least 1 element type"); 475 476 // Call into a helper 'get' method in 'TypeBase' to get a uniqued instance 477 // of this type. The first two parameters are the context to unique in and the 478 // kind of the type. The parameters after the type kind are forwarded to the 479 // storage instance. 480 mlir::MLIRContext *ctx = elementTypes.front().getContext(); 481 return Base::get(ctx, ToyTypes::Struct, elementTypes); 482 } 483 484 /// Returns the element types of this struct type. 485 llvm::ArrayRef<mlir::Type> StructType::getElementTypes() { 486 // 'getImpl' returns a pointer to the internal storage instance. 487 return getImpl()->elementTypes; 488 } 489 490 /// Parse an instance of a type registered to the toy dialect. 491 mlir::Type ToyDialect::parseType(mlir::DialectAsmParser &parser) const { 492 // Parse a struct type in the following form: 493 // struct-type ::= `struct` `<` type (`,` type)* `>` 494 495 // NOTE: All MLIR parser function return a ParseResult. This is a 496 // specialization of LogicalResult that auto-converts to a `true` boolean 497 // value on failure to allow for chaining, but may be used with explicit 498 // `mlir::failed/mlir::succeeded` as desired. 499 500 // Parse: `struct` `<` 501 if (parser.parseKeyword("struct") || parser.parseLess()) 502 return Type(); 503 504 // Parse the element types of the struct. 505 SmallVector<mlir::Type, 1> elementTypes; 506 do { 507 // Parse the current element type. 508 llvm::SMLoc typeLoc = parser.getCurrentLocation(); 509 mlir::Type elementType; 510 if (parser.parseType(elementType)) 511 return nullptr; 512 513 // Check that the type is either a TensorType or another StructType. 514 if (!elementType.isa<mlir::TensorType>() && 515 !elementType.isa<StructType>()) { 516 parser.emitError(typeLoc, "element type for a struct must either " 517 "be a TensorType or a StructType, got: ") 518 << elementType; 519 return Type(); 520 } 521 elementTypes.push_back(elementType); 522 523 // Parse the optional: `,` 524 } while (succeeded(parser.parseOptionalComma())); 525 526 // Parse: `>` 527 if (parser.parseGreater()) 528 return Type(); 529 return StructType::get(elementTypes); 530 } 531 532 /// Print an instance of a type registered to the toy dialect. 533 void ToyDialect::printType(mlir::Type type, 534 mlir::DialectAsmPrinter &printer) const { 535 // Currently the only toy type is a struct type. 536 StructType structType = type.cast<StructType>(); 537 538 // Print the struct type according to the parser format. 539 printer << "struct<"; 540 mlir::interleaveComma(structType.getElementTypes(), printer); 541 printer << '>'; 542 } 543 544 //===----------------------------------------------------------------------===// 545 // TableGen'd op method definitions 546 //===----------------------------------------------------------------------===// 547 548 #define GET_OP_CLASSES 549 #include "toy/Ops.cpp.inc" 550