1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
|
//===- TestPatterns.cpp - Test dialect pattern driver ---------------------===//
//
// Copyright 2019 The MLIR Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
#include "TestDialect.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/DialectConversion.h"
using namespace mlir;
// Native function for testing NativeCodeCall
static Value *chooseOperand(Value *input1, Value *input2, BoolAttr choice) {
return choice.getValue() ? input1 : input2;
}
namespace {
#include "TestPatterns.inc"
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// Canonicalizer Driver.
//===----------------------------------------------------------------------===//
namespace {
struct TestPatternDriver : public FunctionPass<TestPatternDriver> {
void runOnFunction() override {
mlir::OwningRewritePatternList patterns;
populateWithGenerated(&getContext(), &patterns);
// Verify named pattern is generated with expected name.
RewriteListBuilder<TestNamedPatternRule>::build(patterns, &getContext());
applyPatternsGreedily(getFunction(), std::move(patterns));
}
};
} // end anonymous namespace
static mlir::PassRegistration<TestPatternDriver>
pass("test-patterns", "Run test dialect patterns");
//===----------------------------------------------------------------------===//
// Legalization Driver.
//===----------------------------------------------------------------------===//
namespace {
/// This pattern is a simple pattern that inlines the first region of a given
/// operation into the parent region.
struct TestRegionRewriteBlockMovement : public ConversionPattern {
TestRegionRewriteBlockMovement(MLIRContext *ctx)
: ConversionPattern("test.region", 1, ctx) {}
PatternMatchResult
matchAndRewrite(Operation *op, ArrayRef<Value *> operands,
ConversionPatternRewriter &rewriter) const final {
// Inline this region into the parent region.
auto &parentRegion = *op->getContainingRegion();
rewriter.inlineRegionBefore(op->getRegion(0), parentRegion,
parentRegion.end());
// Drop this operation.
rewriter.replaceOp(op, llvm::None);
return matchSuccess();
}
};
/// This pattern is a simple pattern that generates a region containing an
/// illegal operation.
struct TestRegionRewriteUndo : public RewritePattern {
TestRegionRewriteUndo(MLIRContext *ctx)
: RewritePattern("test.region_builder", 1, ctx) {}
PatternMatchResult matchAndRewrite(Operation *op,
PatternRewriter &rewriter) const final {
// Create the region operation with an entry block containing arguments.
OperationState newRegion(op->getLoc(), "test.region");
newRegion.addRegion();
auto *regionOp = rewriter.createOperation(newRegion);
auto *entryBlock = rewriter.createBlock(®ionOp->getRegion(0));
entryBlock->addArgument(rewriter.getIntegerType(64));
// Add an explicitly illegal operation to ensure the conversion fails.
rewriter.create<ILLegalOpF>(op->getLoc(), rewriter.getIntegerType(32));
rewriter.create<TestValidOp>(op->getLoc(), ArrayRef<Value *>());
// Drop this operation.
rewriter.replaceOp(op, llvm::None);
return matchSuccess();
}
};
/// This pattern simply erases the given operation.
struct TestDropOp : public ConversionPattern {
TestDropOp(MLIRContext *ctx) : ConversionPattern("test.drop_op", 1, ctx) {}
PatternMatchResult
matchAndRewrite(Operation *op, ArrayRef<Value *> operands,
ConversionPatternRewriter &rewriter) const final {
rewriter.replaceOp(op, llvm::None);
return matchSuccess();
}
};
/// This pattern simply updates the operands of the given operation.
struct TestPassthroughInvalidOp : public ConversionPattern {
TestPassthroughInvalidOp(MLIRContext *ctx)
: ConversionPattern("test.invalid", 1, ctx) {}
PatternMatchResult
matchAndRewrite(Operation *op, ArrayRef<Value *> operands,
ConversionPatternRewriter &rewriter) const final {
rewriter.replaceOpWithNewOp<TestValidOp>(op, llvm::None, operands,
llvm::None);
return matchSuccess();
}
};
/// This pattern handles the case of a split return value.
struct TestSplitReturnType : public ConversionPattern {
TestSplitReturnType(MLIRContext *ctx)
: ConversionPattern("test.return", 1, ctx) {}
PatternMatchResult
matchAndRewrite(Operation *op, ArrayRef<Value *> operands,
ConversionPatternRewriter &rewriter) const final {
// Check for a return of F32.
if (op->getNumOperands() != 1 || !op->getOperand(0)->getType().isF32())
return matchFailure();
// Check if the first operation is a cast operation, if it is we use the
// results directly.
auto *defOp = operands[0]->getDefiningOp();
if (auto packerOp = llvm::dyn_cast_or_null<TestCastOp>(defOp)) {
SmallVector<Value *, 2> returnOperands(packerOp.getOperands());
rewriter.replaceOpWithNewOp<TestReturnOp>(op, returnOperands);
return matchSuccess();
}
// Otherwise, fail to match.
return matchFailure();
}
};
} // namespace
namespace {
struct TestTypeConverter : public TypeConverter {
using TypeConverter::TypeConverter;
LogicalResult convertType(Type t, SmallVectorImpl<Type> &results) override {
// Drop I16 types.
if (t.isInteger(16))
return success();
// Convert I64 to F64.
if (t.isInteger(64)) {
results.push_back(FloatType::getF64(t.getContext()));
return success();
}
// Split F32 into F16,F16.
if (t.isF32()) {
results.assign(2, FloatType::getF16(t.getContext()));
return success();
}
// Otherwise, convert the type directly.
results.push_back(t);
return success();
}
/// Override the hook to materialize a conversion. This is necessary because
/// we generate 1->N type mappings.
Operation *materializeConversion(PatternRewriter &rewriter, Type resultType,
ArrayRef<Value *> inputs,
Location loc) override {
return rewriter.create<TestCastOp>(loc, resultType, inputs);
}
};
struct TestConversionTarget : public ConversionTarget {
TestConversionTarget(MLIRContext &ctx) : ConversionTarget(ctx) {
addLegalOp<LegalOpA, TestValidOp>();
addDynamicallyLegalOp<TestReturnOp>();
addIllegalOp<ILLegalOpF, TestRegionBuilderOp>();
}
bool isDynamicallyLegal(Operation *op) const final {
// Don't allow F32 operands.
return llvm::none_of(op->getOperandTypes(),
[](Type type) { return type.isF32(); });
}
};
struct TestLegalizePatternDriver
: public ModulePass<TestLegalizePatternDriver> {
void runOnModule() override {
mlir::OwningRewritePatternList patterns;
populateWithGenerated(&getContext(), &patterns);
RewriteListBuilder<TestRegionRewriteBlockMovement, TestRegionRewriteUndo,
TestDropOp, TestPassthroughInvalidOp,
TestSplitReturnType>::build(patterns, &getContext());
TestTypeConverter converter;
TestConversionTarget target(getContext());
(void)applyPartialConversion(getModule(), target, std::move(patterns),
&converter);
}
};
} // end anonymous namespace
static mlir::PassRegistration<TestLegalizePatternDriver>
legalizer_pass("test-legalize-patterns",
"Run test dialect legalization patterns");
|