1 //===- Async.cpp - MLIR Async Operations ----------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "mlir/Dialect/Async/IR/Async.h"
10 
11 #include "mlir/IR/DialectImplementation.h"
12 #include "llvm/ADT/TypeSwitch.h"
13 
14 using namespace mlir;
15 using namespace mlir::async;
16 
17 #include "mlir/Dialect/Async/IR/AsyncOpsDialect.cpp.inc"
18 
19 constexpr StringRef AsyncDialect::kAllowedToBlockAttrName;
20 
21 void AsyncDialect::initialize() {
22   addOperations<
23 #define GET_OP_LIST
24 #include "mlir/Dialect/Async/IR/AsyncOps.cpp.inc"
25       >();
26   addTypes<
27 #define GET_TYPEDEF_LIST
28 #include "mlir/Dialect/Async/IR/AsyncOpsTypes.cpp.inc"
29       >();
30 }
31 
32 //===----------------------------------------------------------------------===//
33 // YieldOp
34 //===----------------------------------------------------------------------===//
35 
36 static LogicalResult verify(YieldOp op) {
37   // Get the underlying value types from async values returned from the
38   // parent `async.execute` operation.
39   auto executeOp = op->getParentOfType<ExecuteOp>();
40   auto types = llvm::map_range(executeOp.results(), [](const OpResult &result) {
41     return result.getType().cast<ValueType>().getValueType();
42   });
43 
44   if (op.getOperandTypes() != types)
45     return op.emitOpError("operand types do not match the types returned from "
46                           "the parent ExecuteOp");
47 
48   return success();
49 }
50 
51 MutableOperandRange
52 YieldOp::getMutableSuccessorOperands(Optional<unsigned> index) {
53   assert(!index.hasValue());
54   return operandsMutable();
55 }
56 
57 //===----------------------------------------------------------------------===//
58 /// ExecuteOp
59 //===----------------------------------------------------------------------===//
60 
61 constexpr char kOperandSegmentSizesAttr[] = "operand_segment_sizes";
62 
63 OperandRange ExecuteOp::getSuccessorEntryOperands(unsigned index) {
64   assert(index == 0 && "invalid region index");
65   return operands();
66 }
67 
68 void ExecuteOp::getSuccessorRegions(Optional<unsigned> index,
69                                     ArrayRef<Attribute>,
70                                     SmallVectorImpl<RegionSuccessor> &regions) {
71   // The `body` region branch back to the parent operation.
72   if (index.hasValue()) {
73     assert(*index == 0 && "invalid region index");
74     regions.push_back(RegionSuccessor(results()));
75     return;
76   }
77 
78   // Otherwise the successor is the body region.
79   regions.push_back(RegionSuccessor(&body(), body().getArguments()));
80 }
81 
82 void ExecuteOp::build(OpBuilder &builder, OperationState &result,
83                       TypeRange resultTypes, ValueRange dependencies,
84                       ValueRange operands, BodyBuilderFn bodyBuilder) {
85 
86   result.addOperands(dependencies);
87   result.addOperands(operands);
88 
89   // Add derived `operand_segment_sizes` attribute based on parsed operands.
90   int32_t numDependencies = dependencies.size();
91   int32_t numOperands = operands.size();
92   auto operandSegmentSizes = DenseIntElementsAttr::get(
93       VectorType::get({2}, builder.getIntegerType(32)),
94       {numDependencies, numOperands});
95   result.addAttribute(kOperandSegmentSizesAttr, operandSegmentSizes);
96 
97   // First result is always a token, and then `resultTypes` wrapped into
98   // `async.value`.
99   result.addTypes({TokenType::get(result.getContext())});
100   for (Type type : resultTypes)
101     result.addTypes(ValueType::get(type));
102 
103   // Add a body region with block arguments as unwrapped async value operands.
104   Region *bodyRegion = result.addRegion();
105   bodyRegion->push_back(new Block);
106   Block &bodyBlock = bodyRegion->front();
107   for (Value operand : operands) {
108     auto valueType = operand.getType().dyn_cast<ValueType>();
109     bodyBlock.addArgument(valueType ? valueType.getValueType()
110                                     : operand.getType());
111   }
112 
113   // Create the default terminator if the builder is not provided and if the
114   // expected result is empty. Otherwise, leave this to the caller
115   // because we don't know which values to return from the execute op.
116   if (resultTypes.empty() && !bodyBuilder) {
117     OpBuilder::InsertionGuard guard(builder);
118     builder.setInsertionPointToStart(&bodyBlock);
119     builder.create<async::YieldOp>(result.location, ValueRange());
120   } else if (bodyBuilder) {
121     OpBuilder::InsertionGuard guard(builder);
122     builder.setInsertionPointToStart(&bodyBlock);
123     bodyBuilder(builder, result.location, bodyBlock.getArguments());
124   }
125 }
126 
127 static void print(OpAsmPrinter &p, ExecuteOp op) {
128   // [%tokens,...]
129   if (!op.dependencies().empty())
130     p << " [" << op.dependencies() << "]";
131 
132   // (%value as %unwrapped: !async.value<!arg.type>, ...)
133   if (!op.operands().empty()) {
134     p << " (";
135     Block *entry = op.body().empty() ? nullptr : &op.body().front();
136     llvm::interleaveComma(op.operands(), p, [&, n = 0](Value operand) mutable {
137       Value argument = entry ? entry->getArgument(n++) : Value();
138       p << operand << " as " << argument << ": " << operand.getType();
139     });
140     p << ")";
141   }
142 
143   // -> (!async.value<!return.type>, ...)
144   p.printOptionalArrowTypeList(llvm::drop_begin(op.getResultTypes()));
145   p.printOptionalAttrDictWithKeyword(op->getAttrs(),
146                                      {kOperandSegmentSizesAttr});
147   p << ' ';
148   p.printRegion(op.body(), /*printEntryBlockArgs=*/false);
149 }
150 
151 static ParseResult parseExecuteOp(OpAsmParser &parser, OperationState &result) {
152   MLIRContext *ctx = result.getContext();
153 
154   // Sizes of parsed variadic operands, will be updated below after parsing.
155   int32_t numDependencies = 0;
156 
157   auto tokenTy = TokenType::get(ctx);
158 
159   // Parse dependency tokens.
160   if (succeeded(parser.parseOptionalLSquare())) {
161     SmallVector<OpAsmParser::OperandType, 4> tokenArgs;
162     if (parser.parseOperandList(tokenArgs) ||
163         parser.resolveOperands(tokenArgs, tokenTy, result.operands) ||
164         parser.parseRSquare())
165       return failure();
166 
167     numDependencies = tokenArgs.size();
168   }
169 
170   // Parse async value operands (%value as %unwrapped : !async.value<!type>).
171   SmallVector<OpAsmParser::OperandType, 4> valueArgs;
172   SmallVector<OpAsmParser::OperandType, 4> unwrappedArgs;
173   SmallVector<Type, 4> valueTypes;
174   SmallVector<Type, 4> unwrappedTypes;
175 
176   // Parse a single instance of `%value as %unwrapped : !async.value<!type>`.
177   auto parseAsyncValueArg = [&]() -> ParseResult {
178     if (parser.parseOperand(valueArgs.emplace_back()) ||
179         parser.parseKeyword("as") ||
180         parser.parseOperand(unwrappedArgs.emplace_back()) ||
181         parser.parseColonType(valueTypes.emplace_back()))
182       return failure();
183 
184     auto valueTy = valueTypes.back().dyn_cast<ValueType>();
185     unwrappedTypes.emplace_back(valueTy ? valueTy.getValueType() : Type());
186 
187     return success();
188   };
189 
190   auto argsLoc = parser.getCurrentLocation();
191   if (parser.parseCommaSeparatedList(OpAsmParser::Delimiter::OptionalParen,
192                                      parseAsyncValueArg) ||
193       parser.resolveOperands(valueArgs, valueTypes, argsLoc, result.operands))
194     return failure();
195 
196   int32_t numOperands = valueArgs.size();
197 
198   // Add derived `operand_segment_sizes` attribute based on parsed operands.
199   auto operandSegmentSizes = DenseIntElementsAttr::get(
200       VectorType::get({2}, parser.getBuilder().getI32Type()),
201       {numDependencies, numOperands});
202   result.addAttribute(kOperandSegmentSizesAttr, operandSegmentSizes);
203 
204   // Parse the types of results returned from the async execute op.
205   SmallVector<Type, 4> resultTypes;
206   if (parser.parseOptionalArrowTypeList(resultTypes))
207     return failure();
208 
209   // Async execute first result is always a completion token.
210   parser.addTypeToList(tokenTy, result.types);
211   parser.addTypesToList(resultTypes, result.types);
212 
213   // Parse operation attributes.
214   NamedAttrList attrs;
215   if (parser.parseOptionalAttrDictWithKeyword(attrs))
216     return failure();
217   result.addAttributes(attrs);
218 
219   // Parse asynchronous region.
220   Region *body = result.addRegion();
221   if (parser.parseRegion(*body, /*arguments=*/{unwrappedArgs},
222                          /*argTypes=*/{unwrappedTypes},
223                          /*enableNameShadowing=*/false))
224     return failure();
225 
226   return success();
227 }
228 
229 static LogicalResult verify(ExecuteOp op) {
230   // Unwrap async.execute value operands types.
231   auto unwrappedTypes = llvm::map_range(op.operands(), [](Value operand) {
232     return operand.getType().cast<ValueType>().getValueType();
233   });
234 
235   // Verify that unwrapped argument types matches the body region arguments.
236   if (op.body().getArgumentTypes() != unwrappedTypes)
237     return op.emitOpError("async body region argument types do not match the "
238                           "execute operation arguments types");
239 
240   return success();
241 }
242 
243 //===----------------------------------------------------------------------===//
244 /// CreateGroupOp
245 //===----------------------------------------------------------------------===//
246 
247 LogicalResult CreateGroupOp::canonicalize(CreateGroupOp op,
248                                           PatternRewriter &rewriter) {
249   // Find all `await_all` users of the group.
250   llvm::SmallVector<AwaitAllOp> awaitAllUsers;
251 
252   auto isAwaitAll = [&](Operation *op) -> bool {
253     if (AwaitAllOp awaitAll = dyn_cast<AwaitAllOp>(op)) {
254       awaitAllUsers.push_back(awaitAll);
255       return true;
256     }
257     return false;
258   };
259 
260   // Check if all users of the group are `await_all` operations.
261   if (!llvm::all_of(op->getUsers(), isAwaitAll))
262     return failure();
263 
264   // If group is only awaited without adding anything to it, we can safely erase
265   // the create operation and all users.
266   for (AwaitAllOp awaitAll : awaitAllUsers)
267     rewriter.eraseOp(awaitAll);
268   rewriter.eraseOp(op);
269 
270   return success();
271 }
272 
273 //===----------------------------------------------------------------------===//
274 /// AwaitOp
275 //===----------------------------------------------------------------------===//
276 
277 void AwaitOp::build(OpBuilder &builder, OperationState &result, Value operand,
278                     ArrayRef<NamedAttribute> attrs) {
279   result.addOperands({operand});
280   result.attributes.append(attrs.begin(), attrs.end());
281 
282   // Add unwrapped async.value type to the returned values types.
283   if (auto valueType = operand.getType().dyn_cast<ValueType>())
284     result.addTypes(valueType.getValueType());
285 }
286 
287 static ParseResult parseAwaitResultType(OpAsmParser &parser, Type &operandType,
288                                         Type &resultType) {
289   if (parser.parseType(operandType))
290     return failure();
291 
292   // Add unwrapped async.value type to the returned values types.
293   if (auto valueType = operandType.dyn_cast<ValueType>())
294     resultType = valueType.getValueType();
295 
296   return success();
297 }
298 
299 static void printAwaitResultType(OpAsmPrinter &p, Operation *op,
300                                  Type operandType, Type resultType) {
301   p << operandType;
302 }
303 
304 static LogicalResult verify(AwaitOp op) {
305   Type argType = op.operand().getType();
306 
307   // Awaiting on a token does not have any results.
308   if (argType.isa<TokenType>() && !op.getResultTypes().empty())
309     return op.emitOpError("awaiting on a token must have empty result");
310 
311   // Awaiting on a value unwraps the async value type.
312   if (auto value = argType.dyn_cast<ValueType>()) {
313     if (*op.getResultType() != value.getValueType())
314       return op.emitOpError()
315              << "result type " << *op.getResultType()
316              << " does not match async value type " << value.getValueType();
317   }
318 
319   return success();
320 }
321 
322 //===----------------------------------------------------------------------===//
323 // TableGen'd op method definitions
324 //===----------------------------------------------------------------------===//
325 
326 #define GET_OP_CLASSES
327 #include "mlir/Dialect/Async/IR/AsyncOps.cpp.inc"
328 
329 //===----------------------------------------------------------------------===//
330 // TableGen'd type method definitions
331 //===----------------------------------------------------------------------===//
332 
333 #define GET_TYPEDEF_CLASSES
334 #include "mlir/Dialect/Async/IR/AsyncOpsTypes.cpp.inc"
335 
336 void ValueType::print(AsmPrinter &printer) const {
337   printer << "<";
338   printer.printType(getValueType());
339   printer << '>';
340 }
341 
342 Type ValueType::parse(mlir::AsmParser &parser) {
343   Type ty;
344   if (parser.parseLess() || parser.parseType(ty) || parser.parseGreater()) {
345     parser.emitError(parser.getNameLoc(), "failed to parse async value type");
346     return Type();
347   }
348   return ValueType::get(ty);
349 }
350