llvm-project/mlir/lib/Dialect/Bufferization/TransformOps/BufferizationTransformOps.cpp
Nikhil Kalra 84cc1865ef
[mlir] Support DialectRegistry extension comparison (#101119)
`PassManager::run` loads the dependent dialects for each pass into the
current context prior to invoking the individual passes. If the
dependent dialect is already loaded into the context, this should be a
no-op. However, if there are extensions registered in the
`DialectRegistry`, the dependent dialects are unconditionally registered
into the context.

This poses a problem for dynamic pass pipelines, however, because they
will likely be executing while the context is in an immutable state
(because of the parent pass pipeline being run).

To solve this, we'll update the extension registration API on
`DialectRegistry` to require a type ID for each extension that is
registered. Then, instead of unconditionally registered dialects into a
context if extensions are present, we'll check against the extension
type IDs already present in the context's internal `DialectRegistry`.
The context will only be marked as dirty if there are net-new extension
types present in the `DialectRegistry` populated by
`PassManager::getDependentDialects`.

Note: this PR removes the `addExtension` overload that utilizes
`std::function` as the parameter. This is because `std::function` is
copyable and potentially allocates memory for the contained function so
we can't use the function pointer as the unique type ID for the
extension.

Downstream changes required:
- Existing `DialectExtension` subclasses will need a type ID to be
registered for each subclass. More details on how to register a type ID
can be found here:
8b68e06731/mlir/include/mlir/Support/TypeID.h (L30)
- Existing uses of the `std::function` overload of `addExtension` will
need to be refactored into dedicated `DialectExtension` classes with
associated type IDs. The attached `std::function` can either be inlined
into or called directly from `DialectExtension::apply`.

---------

Co-authored-by: Mehdi Amini <joker.eph@gmail.com>
2024-08-06 01:32:36 +02:00

179 lines
7.2 KiB
C++

//===- BufferizationTransformOps.h - Bufferization transform ops ----------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "mlir/Dialect/Bufferization/TransformOps/BufferizationTransformOps.h"
#include "mlir/Dialect/Bufferization/IR/Bufferization.h"
#include "mlir/Dialect/Bufferization/Transforms/OneShotAnalysis.h"
#include "mlir/Dialect/Bufferization/Transforms/OneShotModuleBufferize.h"
#include "mlir/Dialect/Bufferization/Transforms/Passes.h"
#include "mlir/Dialect/Bufferization/Transforms/Transforms.h"
#include "mlir/Dialect/Linalg/IR/Linalg.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/Tensor/IR/Tensor.h"
#include "mlir/Dialect/Transform/IR/TransformDialect.h"
#include "mlir/Interfaces/FunctionInterfaces.h"
using namespace mlir;
using namespace mlir::bufferization;
using namespace mlir::transform;
//===----------------------------------------------------------------------===//
// BufferLoopHoistingOp
//===----------------------------------------------------------------------===//
DiagnosedSilenceableFailure transform::BufferLoopHoistingOp::applyToOne(
TransformRewriter &rewriter, Operation *target,
ApplyToEachResultList &results, TransformState &state) {
bufferization::hoistBuffersFromLoops(target);
return DiagnosedSilenceableFailure::success();
}
void transform::BufferLoopHoistingOp::getEffects(
SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
onlyReadsHandle(getTargetMutable(), effects);
modifiesPayload(effects);
}
//===----------------------------------------------------------------------===//
// OneShotBufferizeOp
//===----------------------------------------------------------------------===//
LogicalResult transform::OneShotBufferizeOp::verify() {
if (getMemcpyOp() != "memref.copy" && getMemcpyOp() != "linalg.copy")
return emitOpError() << "unsupported memcpy op";
if (getPrintConflicts() && !getTestAnalysisOnly())
return emitOpError() << "'print_conflicts' requires 'test_analysis_only'";
if (getDumpAliasSets() && !getTestAnalysisOnly())
return emitOpError() << "'dump_alias_sets' requires 'test_analysis_only'";
return success();
}
DiagnosedSilenceableFailure
transform::OneShotBufferizeOp::apply(transform::TransformRewriter &rewriter,
TransformResults &transformResults,
TransformState &state) {
OneShotBufferizationOptions options;
options.allowReturnAllocsFromLoops = getAllowReturnAllocsFromLoops();
options.allowUnknownOps = getAllowUnknownOps();
options.bufferizeFunctionBoundaries = getBufferizeFunctionBoundaries();
options.dumpAliasSets = getDumpAliasSets();
options.testAnalysisOnly = getTestAnalysisOnly();
options.printConflicts = getPrintConflicts();
if (getFunctionBoundaryTypeConversion().has_value())
options.setFunctionBoundaryTypeConversion(
*getFunctionBoundaryTypeConversion());
if (getMemcpyOp() == "memref.copy") {
options.memCpyFn = [](OpBuilder &b, Location loc, Value from, Value to) {
b.create<memref::CopyOp>(loc, from, to);
return success();
};
} else if (getMemcpyOp() == "linalg.copy") {
options.memCpyFn = [](OpBuilder &b, Location loc, Value from, Value to) {
b.create<linalg::CopyOp>(loc, from, to);
return success();
};
} else {
llvm_unreachable("invalid copy op");
}
auto payloadOps = state.getPayloadOps(getTarget());
for (Operation *target : payloadOps) {
if (!isa<ModuleOp, FunctionOpInterface>(target))
return emitSilenceableError() << "expected module or function target";
auto moduleOp = dyn_cast<ModuleOp>(target);
if (options.bufferizeFunctionBoundaries) {
if (!moduleOp)
return emitSilenceableError() << "expected module target";
if (failed(bufferization::runOneShotModuleBufferize(moduleOp, options)))
return emitSilenceableError() << "bufferization failed";
} else {
if (failed(bufferization::runOneShotBufferize(target, options)))
return emitSilenceableError() << "bufferization failed";
}
}
// This transform op is currently restricted to ModuleOps and function ops.
// Such ops are modified in-place.
transformResults.set(cast<OpResult>(getTransformed()), payloadOps);
return DiagnosedSilenceableFailure::success();
}
//===----------------------------------------------------------------------===//
// EliminateEmptyTensorsOp
//===----------------------------------------------------------------------===//
void transform::EliminateEmptyTensorsOp::getEffects(
SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
onlyReadsHandle(getTargetMutable(), effects);
modifiesPayload(effects);
}
DiagnosedSilenceableFailure transform::EliminateEmptyTensorsOp::apply(
transform::TransformRewriter &rewriter, TransformResults &transformResults,
TransformState &state) {
for (Operation *target : state.getPayloadOps(getTarget())) {
if (failed(bufferization::eliminateEmptyTensors(rewriter, target)))
return mlir::emitSilenceableFailure(target->getLoc())
<< "empty tensor elimination failed";
}
return DiagnosedSilenceableFailure::success();
}
//===----------------------------------------------------------------------===//
// EmptyTensorToAllocTensorOp
//===----------------------------------------------------------------------===//
DiagnosedSilenceableFailure EmptyTensorToAllocTensorOp::applyToOne(
transform::TransformRewriter &rewriter, tensor::EmptyOp target,
ApplyToEachResultList &results, transform::TransformState &state) {
rewriter.setInsertionPoint(target);
auto alloc = rewriter.replaceOpWithNewOp<bufferization::AllocTensorOp>(
target, target.getType(), target.getDynamicSizes());
results.push_back(alloc);
return DiagnosedSilenceableFailure::success();
}
//===----------------------------------------------------------------------===//
// Transform op registration
//===----------------------------------------------------------------------===//
namespace {
/// Registers new ops and declares PDL as dependent dialect since the additional
/// ops are using PDL types for operands and results.
class BufferizationTransformDialectExtension
: public transform::TransformDialectExtension<
BufferizationTransformDialectExtension> {
public:
MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(
BufferizationTransformDialectExtension)
using Base::Base;
void init() {
declareGeneratedDialect<bufferization::BufferizationDialect>();
declareGeneratedDialect<memref::MemRefDialect>();
registerTransformOps<
#define GET_OP_LIST
#include "mlir/Dialect/Bufferization/TransformOps/BufferizationTransformOps.cpp.inc"
>();
}
};
} // namespace
#define GET_OP_CLASSES
#include "mlir/Dialect/Bufferization/TransformOps/BufferizationTransformOps.cpp.inc"
#include "mlir/Dialect/Bufferization/IR/BufferizationEnums.cpp.inc"
void mlir::bufferization::registerTransformDialectExtension(
DialectRegistry &registry) {
registry.addExtensions<BufferizationTransformDialectExtension>();
}