1//===- TestDecomposeCallGraphTypes.cpp - Test CG type decomposition -------===//
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 "TestOpsInterfaces.h"
10#include "mlir/Dialect/Func/IR/FuncOps.h"
11#include "mlir/Dialect/Func/Transforms/FuncConversions.h"
12#include "mlir/IR/Builders.h"
13#include "mlir/Pass/Pass.h"
14#include "mlir/Transforms/DialectConversion.h"
15
16using namespace mlir;
17
18namespace {
19/// Creates a sequence of `test.get_tuple_element` ops for all elements of a
20/// given tuple value. If some tuple elements are, in turn, tuples, the elements
21/// of those are extracted recursively such that the returned values have the
22/// same types as `resultTypes.getFlattenedTypes()`.
23static SmallVector<Value> buildDecomposeTuple(OpBuilder &builder,
24 TypeRange resultTypes,
25 ValueRange inputs, Location loc) {
26 // Skip materialization if the single input value is not a tuple.
27 if (inputs.size() != 1)
28 return {};
29 Value tuple = inputs.front();
30 auto tupleType = dyn_cast<TupleType>(Val: tuple.getType());
31 if (!tupleType)
32 return {};
33 // Skip materialization if the flattened types do not match the requested
34 // result types.
35 SmallVector<Type> flattenedTypes;
36 tupleType.getFlattenedTypes(types&: flattenedTypes);
37 if (TypeRange(resultTypes) != TypeRange(flattenedTypes))
38 return {};
39 // Recursively decompose the tuple.
40 SmallVector<Value> result;
41 std::function<void(Value)> decompose = [&](Value tuple) {
42 auto tupleType = dyn_cast<TupleType>(Val: tuple.getType());
43 if (!tupleType) {
44 // This is not a tuple.
45 result.push_back(Elt: tuple);
46 return;
47 }
48 for (unsigned i = 0, e = tupleType.size(); i < e; ++i) {
49 Type elementType = tupleType.getType(index: i);
50 Value element = test::GetTupleElementOp::create(
51 builder, loc, elementType, tuple, builder.getI32IntegerAttr(i));
52 decompose(element);
53 }
54 };
55 decompose(tuple);
56 return result;
57}
58
59/// Creates a `test.make_tuple` op out of the given inputs building a tuple of
60/// type `resultType`. If that type is nested, each nested tuple is built
61/// recursively with another `test.make_tuple` op.
62static Value buildMakeTupleOp(OpBuilder &builder, TupleType resultType,
63 ValueRange inputs, Location loc) {
64 // Build one value for each element at this nesting level.
65 SmallVector<Value> elements;
66 elements.reserve(N: resultType.getTypes().size());
67 ValueRange::iterator inputIt = inputs.begin();
68 for (Type elementType : resultType.getTypes()) {
69 if (auto nestedTupleType = dyn_cast<TupleType>(Val&: elementType)) {
70 // Determine how many input values are needed for the nested elements of
71 // the nested TupleType and advance inputIt by that number.
72 // TODO: We only need the *number* of nested types, not the types itself.
73 // Maybe it's worth adding a more efficient overload?
74 SmallVector<Type> nestedFlattenedTypes;
75 nestedTupleType.getFlattenedTypes(types&: nestedFlattenedTypes);
76 size_t numNestedFlattenedTypes = nestedFlattenedTypes.size();
77 ValueRange nestedFlattenedelements(inputIt,
78 inputIt + numNestedFlattenedTypes);
79 inputIt += numNestedFlattenedTypes;
80
81 // Recurse on the values for the nested TupleType.
82 Value res = buildMakeTupleOp(builder, resultType: nestedTupleType,
83 inputs: nestedFlattenedelements, loc);
84 if (!res)
85 return Value();
86
87 // The tuple constructed by the conversion is the element value.
88 elements.push_back(Elt: res);
89 } else {
90 // Base case: take one input as is.
91 elements.push_back(Elt: *inputIt++);
92 }
93 }
94
95 // Assemble the tuple from the elements.
96 return test::MakeTupleOp::create(builder, loc, resultType, elements);
97}
98
99/// A pass for testing call graph type decomposition.
100///
101/// This instantiates the patterns with a TypeConverter that splits tuple types
102/// into their respective element types.
103/// For example, `tuple<T1, T2, T3> --> T1, T2, T3`.
104struct TestDecomposeCallGraphTypes
105 : public PassWrapper<TestDecomposeCallGraphTypes, OperationPass<ModuleOp>> {
106 MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TestDecomposeCallGraphTypes)
107
108 void getDependentDialects(DialectRegistry &registry) const override {
109 registry.insert<test::TestDialect>();
110 }
111 StringRef getArgument() const final {
112 return "test-decompose-call-graph-types";
113 }
114 StringRef getDescription() const final {
115 return "Decomposes types at call graph boundaries.";
116 }
117 void runOnOperation() override {
118 ModuleOp module = getOperation();
119 auto *context = &getContext();
120 TypeConverter typeConverter;
121 ConversionTarget target(*context);
122 RewritePatternSet patterns(context);
123
124 target.addLegalDialect<test::TestDialect>();
125
126 target.addDynamicallyLegalOp<func::ReturnOp>(callback: [&](func::ReturnOp op) {
127 return typeConverter.isLegal(range: op.getOperandTypes());
128 });
129 target.addDynamicallyLegalOp<func::CallOp>(
130 callback: [&](func::CallOp op) { return typeConverter.isLegal(op); });
131 target.addDynamicallyLegalOp<func::FuncOp>(callback: [&](func::FuncOp op) {
132 return typeConverter.isSignatureLegal(ty: op.getFunctionType());
133 });
134
135 typeConverter.addConversion(callback: [](Type type) { return type; });
136 typeConverter.addConversion(
137 callback: [](TupleType tupleType, SmallVectorImpl<Type> &types) {
138 tupleType.getFlattenedTypes(types);
139 return success();
140 });
141 typeConverter.addSourceMaterialization(callback&: buildMakeTupleOp);
142 typeConverter.addTargetMaterialization(callback&: buildDecomposeTuple);
143
144 populateFunctionOpInterfaceTypeConversionPattern<func::FuncOp>(
145 patterns, converter: typeConverter);
146 populateReturnOpTypeConversionPattern(patterns, converter: typeConverter);
147 populateCallOpTypeConversionPattern(patterns, converter: typeConverter);
148
149 if (failed(Result: applyPartialConversion(op: module, target, patterns: std::move(patterns))))
150 return signalPassFailure();
151 }
152};
153
154} // namespace
155
156namespace mlir {
157namespace test {
158void registerTestDecomposeCallGraphTypes() {
159 PassRegistration<TestDecomposeCallGraphTypes>();
160}
161} // namespace test
162} // namespace mlir
163