MLIR  21.0.0git
SCFToEmitC.cpp
Go to the documentation of this file.
1 //===- SCFToEmitC.cpp - SCF to EmitC conversion ---------------------------===//
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 a pass to convert scf.if ops into emitc ops.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 
19 #include "mlir/IR/Builders.h"
20 #include "mlir/IR/MLIRContext.h"
21 #include "mlir/IR/PatternMatch.h"
23 #include "mlir/Transforms/Passes.h"
24 
25 namespace mlir {
26 #define GEN_PASS_DEF_SCFTOEMITC
27 #include "mlir/Conversion/Passes.h.inc"
28 } // namespace mlir
29 
30 using namespace mlir;
31 using namespace mlir::scf;
32 
33 namespace {
34 
35 /// Implement the interface to convert SCF to EmitC.
36 struct SCFToEmitCDialectInterface : public ConvertToEmitCPatternInterface {
38 
39  /// Hook for derived dialect interface to provide conversion patterns
40  /// and mark dialect legal for the conversion target.
41  void populateConvertToEmitCConversionPatterns(
42  ConversionTarget &target, TypeConverter &typeConverter,
43  RewritePatternSet &patterns) const final {
44  populateEmitCSizeTTypeConversions(typeConverter);
46  }
47 };
48 } // namespace
49 
51  registry.addExtension(+[](MLIRContext *ctx, scf::SCFDialect *dialect) {
52  dialect->addInterfaces<SCFToEmitCDialectInterface>();
53  });
54 }
55 
56 namespace {
57 
58 struct SCFToEmitCPass : public impl::SCFToEmitCBase<SCFToEmitCPass> {
59  void runOnOperation() override;
60 };
61 
62 // Lower scf::for to emitc::for, implementing result values using
63 // emitc::variable's updated within the loop body.
64 struct ForLowering : public OpConversionPattern<ForOp> {
66 
67  LogicalResult
68  matchAndRewrite(ForOp forOp, OpAdaptor adaptor,
69  ConversionPatternRewriter &rewriter) const override;
70 };
71 
72 // Create an uninitialized emitc::variable op for each result of the given op.
73 template <typename T>
74 static LogicalResult
75 createVariablesForResults(T op, const TypeConverter *typeConverter,
76  ConversionPatternRewriter &rewriter,
77  SmallVector<Value> &resultVariables) {
78  if (!op.getNumResults())
79  return success();
80 
81  Location loc = op->getLoc();
82  MLIRContext *context = op.getContext();
83 
84  OpBuilder::InsertionGuard guard(rewriter);
85  rewriter.setInsertionPoint(op);
86 
87  for (OpResult result : op.getResults()) {
88  Type resultType = typeConverter->convertType(result.getType());
89  if (!resultType)
90  return rewriter.notifyMatchFailure(op, "result type conversion failed");
91  Type varType = emitc::LValueType::get(resultType);
92  emitc::OpaqueAttr noInit = emitc::OpaqueAttr::get(context, "");
93  emitc::VariableOp var =
94  rewriter.create<emitc::VariableOp>(loc, varType, noInit);
95  resultVariables.push_back(var);
96  }
97 
98  return success();
99 }
100 
101 // Create a series of assign ops assigning given values to given variables at
102 // the current insertion point of given rewriter.
103 static void assignValues(ValueRange values, ValueRange variables,
104  ConversionPatternRewriter &rewriter, Location loc) {
105  for (auto [value, var] : llvm::zip(values, variables))
106  rewriter.create<emitc::AssignOp>(loc, var, value);
107 }
108 
109 SmallVector<Value> loadValues(const SmallVector<Value> &variables,
110  PatternRewriter &rewriter, Location loc) {
111  return llvm::map_to_vector<>(variables, [&](Value var) {
112  Type type = cast<emitc::LValueType>(var.getType()).getValueType();
113  return rewriter.create<emitc::LoadOp>(loc, type, var).getResult();
114  });
115 }
116 
117 static LogicalResult lowerYield(Operation *op, ValueRange resultVariables,
118  ConversionPatternRewriter &rewriter,
119  scf::YieldOp yield) {
120  Location loc = yield.getLoc();
121 
122  OpBuilder::InsertionGuard guard(rewriter);
123  rewriter.setInsertionPoint(yield);
124 
125  SmallVector<Value> yieldOperands;
126  if (failed(rewriter.getRemappedValues(yield.getOperands(), yieldOperands))) {
127  return rewriter.notifyMatchFailure(op, "failed to lower yield operands");
128  }
129 
130  assignValues(yieldOperands, resultVariables, rewriter, loc);
131 
132  rewriter.create<emitc::YieldOp>(loc);
133  rewriter.eraseOp(yield);
134 
135  return success();
136 }
137 
138 // Lower the contents of an scf::if/scf::index_switch regions to an
139 // emitc::if/emitc::switch region. The contents of the lowering region is
140 // moved into the respective lowered region, but the scf::yield is replaced not
141 // only with an emitc::yield, but also with a sequence of emitc::assign ops that
142 // set the yielded values into the result variables.
143 static LogicalResult lowerRegion(Operation *op, ValueRange resultVariables,
144  ConversionPatternRewriter &rewriter,
145  Region &region, Region &loweredRegion) {
146  rewriter.inlineRegionBefore(region, loweredRegion, loweredRegion.end());
147  Operation *terminator = loweredRegion.back().getTerminator();
148  return lowerYield(op, resultVariables, rewriter,
149  cast<scf::YieldOp>(terminator));
150 }
151 
152 LogicalResult
153 ForLowering::matchAndRewrite(ForOp forOp, OpAdaptor adaptor,
154  ConversionPatternRewriter &rewriter) const {
155  Location loc = forOp.getLoc();
156 
157  // Create an emitc::variable op for each result. These variables will be
158  // assigned to by emitc::assign ops within the loop body.
159  SmallVector<Value> resultVariables;
160  if (failed(createVariablesForResults(forOp, getTypeConverter(), rewriter,
161  resultVariables)))
162  return rewriter.notifyMatchFailure(forOp,
163  "create variables for results failed");
164 
165  assignValues(adaptor.getInitArgs(), resultVariables, rewriter, loc);
166 
167  emitc::ForOp loweredFor = rewriter.create<emitc::ForOp>(
168  loc, adaptor.getLowerBound(), adaptor.getUpperBound(), adaptor.getStep());
169 
170  Block *loweredBody = loweredFor.getBody();
171 
172  // Erase the auto-generated terminator for the lowered for op.
173  rewriter.eraseOp(loweredBody->getTerminator());
174 
175  IRRewriter::InsertPoint ip = rewriter.saveInsertionPoint();
176  rewriter.setInsertionPointToEnd(loweredBody);
177 
178  SmallVector<Value> iterArgsValues =
179  loadValues(resultVariables, rewriter, loc);
180 
181  rewriter.restoreInsertionPoint(ip);
182 
183  // Convert the original region types into the new types by adding unrealized
184  // casts in the beginning of the loop. This performs the conversion in place.
185  if (failed(rewriter.convertRegionTypes(&forOp.getRegion(),
186  *getTypeConverter(), nullptr))) {
187  return rewriter.notifyMatchFailure(forOp, "region types conversion failed");
188  }
189 
190  // Register the replacements for the block arguments and inline the body of
191  // the scf.for loop into the body of the emitc::for loop.
192  Block *scfBody = &(forOp.getRegion().front());
193  SmallVector<Value> replacingValues;
194  replacingValues.push_back(loweredFor.getInductionVar());
195  replacingValues.append(iterArgsValues.begin(), iterArgsValues.end());
196  rewriter.mergeBlocks(scfBody, loweredBody, replacingValues);
197 
198  auto result = lowerYield(forOp, resultVariables, rewriter,
199  cast<scf::YieldOp>(loweredBody->getTerminator()));
200 
201  if (failed(result)) {
202  return result;
203  }
204 
205  // Load variables into SSA values after the for loop.
206  SmallVector<Value> resultValues = loadValues(resultVariables, rewriter, loc);
207 
208  rewriter.replaceOp(forOp, resultValues);
209  return success();
210 }
211 
212 // Lower scf::if to emitc::if, implementing result values as emitc::variable's
213 // updated within the then and else regions.
214 struct IfLowering : public OpConversionPattern<IfOp> {
216 
217  LogicalResult
218  matchAndRewrite(IfOp ifOp, OpAdaptor adaptor,
219  ConversionPatternRewriter &rewriter) const override;
220 };
221 
222 } // namespace
223 
224 LogicalResult
225 IfLowering::matchAndRewrite(IfOp ifOp, OpAdaptor adaptor,
226  ConversionPatternRewriter &rewriter) const {
227  Location loc = ifOp.getLoc();
228 
229  // Create an emitc::variable op for each result. These variables will be
230  // assigned to by emitc::assign ops within the then & else regions.
231  SmallVector<Value> resultVariables;
232  if (failed(createVariablesForResults(ifOp, getTypeConverter(), rewriter,
233  resultVariables)))
234  return rewriter.notifyMatchFailure(ifOp,
235  "create variables for results failed");
236 
237  // Utility function to lower the contents of an scf::if region to an emitc::if
238  // region. The contents of the scf::if regions is moved into the respective
239  // emitc::if regions, but the scf::yield is replaced not only with an
240  // emitc::yield, but also with a sequence of emitc::assign ops that set the
241  // yielded values into the result variables.
242  auto lowerRegion = [&resultVariables, &rewriter,
243  &ifOp](Region &region, Region &loweredRegion) {
244  rewriter.inlineRegionBefore(region, loweredRegion, loweredRegion.end());
245  Operation *terminator = loweredRegion.back().getTerminator();
246  auto result = lowerYield(ifOp, resultVariables, rewriter,
247  cast<scf::YieldOp>(terminator));
248  if (failed(result)) {
249  return result;
250  }
251  return success();
252  };
253 
254  Region &thenRegion = adaptor.getThenRegion();
255  Region &elseRegion = adaptor.getElseRegion();
256 
257  bool hasElseBlock = !elseRegion.empty();
258 
259  auto loweredIf =
260  rewriter.create<emitc::IfOp>(loc, adaptor.getCondition(), false, false);
261 
262  Region &loweredThenRegion = loweredIf.getThenRegion();
263  auto result = lowerRegion(thenRegion, loweredThenRegion);
264  if (failed(result)) {
265  return result;
266  }
267 
268  if (hasElseBlock) {
269  Region &loweredElseRegion = loweredIf.getElseRegion();
270  auto result = lowerRegion(elseRegion, loweredElseRegion);
271  if (failed(result)) {
272  return result;
273  }
274  }
275 
276  rewriter.setInsertionPointAfter(ifOp);
277  SmallVector<Value> results = loadValues(resultVariables, rewriter, loc);
278 
279  rewriter.replaceOp(ifOp, results);
280  return success();
281 }
282 
283 // Lower scf::index_switch to emitc::switch, implementing result values as
284 // emitc::variable's updated within the case and default regions.
285 struct IndexSwitchOpLowering : public OpConversionPattern<IndexSwitchOp> {
287 
288  LogicalResult
289  matchAndRewrite(IndexSwitchOp indexSwitchOp, OpAdaptor adaptor,
290  ConversionPatternRewriter &rewriter) const override;
291 };
292 
294  IndexSwitchOp indexSwitchOp, OpAdaptor adaptor,
295  ConversionPatternRewriter &rewriter) const {
296  Location loc = indexSwitchOp.getLoc();
297 
298  // Create an emitc::variable op for each result. These variables will be
299  // assigned to by emitc::assign ops within the case and default regions.
300  SmallVector<Value> resultVariables;
301  if (failed(createVariablesForResults(indexSwitchOp, getTypeConverter(),
302  rewriter, resultVariables))) {
303  return rewriter.notifyMatchFailure(indexSwitchOp,
304  "create variables for results failed");
305  }
306 
307  auto loweredSwitch = rewriter.create<emitc::SwitchOp>(
308  loc, adaptor.getArg(), adaptor.getCases(), indexSwitchOp.getNumCases());
309 
310  // Lowering all case regions.
311  for (auto pair :
312  llvm::zip(adaptor.getCaseRegions(), loweredSwitch.getCaseRegions())) {
313  if (failed(lowerRegion(indexSwitchOp, resultVariables, rewriter,
314  *std::get<0>(pair), std::get<1>(pair)))) {
315  return failure();
316  }
317  }
318 
319  // Lowering default region.
320  if (failed(lowerRegion(indexSwitchOp, resultVariables, rewriter,
321  adaptor.getDefaultRegion(),
322  loweredSwitch.getDefaultRegion()))) {
323  return failure();
324  }
325 
326  rewriter.setInsertionPointAfter(indexSwitchOp);
327  SmallVector<Value> results = loadValues(resultVariables, rewriter, loc);
328 
329  rewriter.replaceOp(indexSwitchOp, results);
330  return success();
331 }
332 
334  TypeConverter &typeConverter) {
335  patterns.add<ForLowering>(typeConverter, patterns.getContext());
336  patterns.add<IfLowering>(typeConverter, patterns.getContext());
337  patterns.add<IndexSwitchOpLowering>(typeConverter, patterns.getContext());
338 }
339 
340 void SCFToEmitCPass::runOnOperation() {
342  TypeConverter typeConverter;
343  // Fallback for other types.
344  typeConverter.addConversion([](Type type) -> std::optional<Type> {
345  if (!emitc::isSupportedEmitCType(type))
346  return {};
347  return type;
348  });
349  populateEmitCSizeTTypeConversions(typeConverter);
351 
352  // Configure conversion to lower out SCF operations.
353  ConversionTarget target(getContext());
354  target.addIllegalOp<scf::ForOp, scf::IfOp, scf::IndexSwitchOp>();
355  target.markUnknownOpDynamicallyLegal([](Operation *) { return true; });
356  if (failed(
357  applyPartialConversion(getOperation(), target, std::move(patterns))))
358  signalPassFailure();
359 }
static MLIRContext * getContext(OpFoldResult val)
Block represents an ordered list of Operations.
Definition: Block.h:33
Operation * getTerminator()
Get the terminator operation of this block.
Definition: Block.cpp:244
This class implements a pattern rewriter for use with ConversionPatterns.
void replaceOp(Operation *op, ValueRange newValues) override
Replace the given operation with the new values.
LogicalResult getRemappedValues(ValueRange keys, SmallVectorImpl< Value > &results)
Return the converted values that replace 'keys' with types defined by the type converter of the curre...
FailureOr< Block * > convertRegionTypes(Region *region, const TypeConverter &converter, TypeConverter::SignatureConversion *entryConversion=nullptr)
Apply a signature conversion to each block in the given region.
void eraseOp(Operation *op) override
PatternRewriter hook for erasing a dead operation.
This class describes a specific conversion target.
ConvertToEmitCPatternInterface(Dialect *dialect)
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
bool addExtension(TypeID extensionID, std::unique_ptr< DialectExtensionBase > extension)
Add the given extension to the registry.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:60
RAII guard to reset the insertion point of the builder when destroyed.
Definition: Builders.h:346
InsertPoint saveInsertionPoint() const
Return a saved insertion point.
Definition: Builders.h:383
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition: Builders.h:396
void setInsertionPointToEnd(Block *block)
Sets the insertion point to the end of the specified block.
Definition: Builders.h:434
void restoreInsertionPoint(InsertPoint ip)
Restore the insert point to a previously saved point.
Definition: Builders.h:388
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition: Builders.cpp:452
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Definition: Builders.h:410
OpConversionPattern is a wrapper around ConversionPattern that allows for matching and rewriting agai...
OpConversionPattern(MLIRContext *context, PatternBenefit benefit=1)
This is a value defined by a result of an operation.
Definition: Value.h:447
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
Definition: PatternMatch.h:748
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition: Region.h:26
bool empty()
Definition: Region.h:60
iterator end()
Definition: Region.h:56
Block & back()
Definition: Region.h:64
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
Definition: PatternMatch.h:681
void mergeBlocks(Block *source, Block *dest, ValueRange argValues={})
Inline the operations of block 'source' into the end of block 'dest'.
void inlineRegionBefore(Region &region, Region &parent, Region::iterator before)
Move the blocks that belong to "region" before the given position in another region "parent".
Type conversion class.
void addConversion(FnT &&callback)
Register a conversion function.
LogicalResult convertType(Type t, SmallVectorImpl< Type > &results) const
Convert the given type.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:74
This class provides an abstraction over the different types of ranges over Values.
Definition: ValueRange.h:387
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:96
Type getType() const
Return the type of this value.
Definition: Value.h:105
bool isSupportedEmitCType(mlir::Type type)
Determines whether type is valid in EmitC.
Definition: EmitC.cpp:62
Include the generated interface declarations.
void populateEmitCSizeTTypeConversions(TypeConverter &converter)
void populateSCFToEmitCConversionPatterns(RewritePatternSet &patterns, TypeConverter &typeConverter)
Collect a set of patterns to convert SCF operations to the EmitC dialect.
Definition: SCFToEmitC.cpp:333
const FrozenRewritePatternSet & patterns
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
LogicalResult applyPartialConversion(ArrayRef< Operation * > ops, const ConversionTarget &target, const FrozenRewritePatternSet &patterns, ConversionConfig config=ConversionConfig())
Below we define several entry points for operation conversion.
void registerConvertSCFToEmitCInterface(DialectRegistry &registry)
Definition: SCFToEmitC.cpp:50
LogicalResult matchAndRewrite(IndexSwitchOp indexSwitchOp, OpAdaptor adaptor, ConversionPatternRewriter &rewriter) const override
Methods that operate on the SourceOp type.
Definition: SCFToEmitC.cpp:293