MLIR  20.0.0git
SparsificationAndBufferizationPass.cpp
Go to the documentation of this file.
1 //===- SparsificationAndBufferizationPass.cpp - Tensor to Memref Lowering -===//
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 
10 
28 #include "mlir/Pass/PassManager.h"
29 #include "mlir/Transforms/Passes.h"
30 
31 using namespace mlir;
32 
33 namespace mlir {
34 
35 #define GEN_PASS_DEF_SPARSIFICATIONANDBUFFERIZATION
36 #include "mlir/Dialect/SparseTensor/Transforms/Passes.h.inc"
37 
38 namespace sparse_tensor {
39 
40 /// Return `true` if one of the given types is a sparse tensor type.
41 static bool containsSparseTensor(TypeRange types) {
42  for (Type t : types)
43  if (isa<TensorType>(t) && getSparseTensorEncoding(t))
44  return true;
45  return false;
46 }
47 
48 /// A pass that lowers tensor ops to memref ops, regardless of whether they are
49 /// dense or sparse.
50 ///
51 /// One-Shot Analysis is used to detect RaW conflicts and to insert buffer
52 /// copies of the tensor level (`insertTensorCopies`). Afterwards, the lowering
53 /// of tensor ops to memref ops follows a different code path depending on
54 /// whether the op is sparse or dense:
55 ///
56 /// * Sparse tensor ops are lowered through Sparsification and follow-up pass
57 /// that lowers sparse_tensor dialect ops.
58 /// * Dense tensor ops are lowered through BufferizableOpInterface
59 /// implementations.
61  : public impl::SparsificationAndBufferizationBase<
62  SparsificationAndBufferizationPass> {
63 public:
64  // Private pass options only.
66  const bufferization::OneShotBufferizationOptions &bufferizationOptions,
67  const SparsificationOptions &sparsificationOptions,
68  bool createSparseDeallocs, bool enableRuntimeLibrary,
69  bool enableBufferInitialization)
70  : bufferizationOptions(bufferizationOptions),
71  sparsificationOptions(sparsificationOptions),
72  createSparseDeallocs(createSparseDeallocs),
73  enableRuntimeLibrary(enableRuntimeLibrary),
74  enableBufferInitialization(enableBufferInitialization) {}
75  // Private pass options and visible pass options.
77  const bufferization::OneShotBufferizationOptions &bufferizationOptions,
78  const SparsificationOptions &sparsificationOptions,
79  bool createSparseDeallocs, bool enableRuntimeLibrary,
80  bool enableBufferInitialization, unsigned vl, bool vla, bool index32,
81  bool gpu, SparseEmitStrategy emitStrategy)
82  : bufferizationOptions(bufferizationOptions),
83  sparsificationOptions(sparsificationOptions),
84  createSparseDeallocs(createSparseDeallocs),
85  enableRuntimeLibrary(enableRuntimeLibrary),
86  enableBufferInitialization(enableBufferInitialization) {
87  // Set the visible pass options explicitly.
88  vectorLength = vl;
89  enableVLAVectorization = vla;
90  enableSIMDIndex32 = index32;
91  enableGPULibgen = gpu;
92  sparseEmitStrategy = emitStrategy;
93  }
94 
95  /// Bufferize all dense ops. This assumes that no further analysis is needed
96  /// and that all required buffer copies were already inserted by
97  /// `insertTensorCopies` in the form of `bufferization.alloc_tensor` ops.
98  LogicalResult runDenseBufferization() {
100  bufferizationOptions;
101  // Skip all sparse ops.
102  updatedOptions.opFilter.denyOperation([&](Operation *op) {
105  return true;
106  if (auto funcOp = dyn_cast<func::FuncOp>(op)) {
107  FunctionType funcType = funcOp.getFunctionType();
108  if (containsSparseTensor(funcType.getInputs()) ||
109  containsSparseTensor(funcType.getResults()))
110  return true;
111  }
112  return false;
113  });
114 
115  if (failed(bufferization::bufferizeModuleOp(cast<ModuleOp>(getOperation()),
116  updatedOptions)))
117  return failure();
118 
120  return success();
121  }
122 
123  void runOnOperation() override {
124  // Overrides the default emit strategy using user-provided value.
125  this->sparsificationOptions.sparseEmitStrategy = sparseEmitStrategy;
126 
127  // Run enabling transformations.
128  {
129  OpPassManager pm("builtin.module");
131  pm.addNestedPass<func::FuncOp>(
133  if (failed(runPipeline(pm, getOperation())))
134  return signalPassFailure();
135  }
136 
137  // Insert tensor copies. This step runs One-Shot Analysis (which analyzes
138  // SSA use-def chains of tensor IR) and decides where buffer copies are
139  // needed and where buffers can be written to in-place. These decisions are
140  // materialized in the IR in the form of `bufferization.alloc_tensor` ops.
141  //
142  // Note: All following steps in this pass must be careful not to modify the
143  // structure of the IR (i.e., tensor use-def chains), as that could
144  // invalidate the results of the analysis. From now on, only small and
145  // localized rewrites are allowed, such as replacing a tensor op with its
146  // memref equivalent.
147  if (failed(bufferization::insertTensorCopies(getOperation(),
148  bufferizationOptions)))
149  return signalPassFailure();
150 
151  // Option `testAnalysisOnly` is a debug/testing flag. If set, the results of
152  // OneShotAnalysis are added to the IR via attributes. In that case, do not
153  // continue with the remaining pipeline.
154  if (bufferizationOptions.testAnalysisOnly)
155  return;
156 
157  // Bufferize all sparse ops. No further analysis is needed. All required
158  // buffer copies were already inserted by `insertTensorCopies` in the form
159  // of `bufferization.alloc_tensor` ops.
160  {
161  OpPassManager pm("builtin.module");
162  if (enableGPULibgen)
163  pm.addPass(createSparseGPUCodegenPass(0, enableRuntimeLibrary));
165  pm.addPass(createSparsificationPass(sparsificationOptions));
166  if (sparsificationOptions.sparseEmitStrategy ==
168  pm.addNestedPass<func::FuncOp>(createSparseSpaceCollapsePass());
170  }
171 
173  pm.addPass(createLowerSparseOpsToForeachPass(enableRuntimeLibrary,
174  /*enableConvert=*/true));
175  pm.addPass(
177  pm.addNestedPass<func::FuncOp>(createLowerForeachToSCFPass());
179  if (vectorLength > 0) {
181  vectorLength, enableVLAVectorization, enableSIMDIndex32));
182  }
183  if (enableRuntimeLibrary) {
185  } else {
186  pm.addPass(createSparseTensorCodegenPass(createSparseDeallocs,
187  enableBufferInitialization));
188  pm.addPass(createSparseBufferRewritePass(enableBufferInitialization));
189  }
190  if (failed(runPipeline(pm, getOperation())))
191  return signalPassFailure();
192  }
193 
194  // Bufferize all dense ops.
195  if (failed(runDenseBufferization()))
196  signalPassFailure();
197  }
198 
199 private:
200  bufferization::OneShotBufferizationOptions bufferizationOptions;
201  SparsificationOptions sparsificationOptions;
202  bool createSparseDeallocs;
203  bool enableRuntimeLibrary;
204  bool enableBufferInitialization;
205 };
206 
207 } // namespace sparse_tensor
208 } // namespace mlir
209 
212  using namespace mlir::bufferization;
214  options.bufferizeFunctionBoundaries = true;
215  options.setFunctionBoundaryTypeConversion(LayoutMapOption::IdentityLayoutMap);
216  options.unknownTypeConverterFn = [](Value value, Attribute memorySpace,
217  const BufferizationOptions &options) {
219  cast<TensorType>(value.getType()), memorySpace);
220  };
221  if (analysisOnly) {
222  options.testAnalysisOnly = true;
223  options.printConflicts = true;
224  }
225  // Since this mini-pipeline may be used in alternative pipelines (viz.
226  // different from the default "sparsifier" pipeline) where unknown ops
227  // are handled by alternative bufferization methods that are downstream
228  // of this mini-pipeline, we allow unknown ops by default (failure to
229  // bufferize is eventually apparent by failing to convert to LLVM IR).
230  options.allowUnknownOps = true;
231  return options;
232 }
233 
234 std::unique_ptr<mlir::Pass> mlir::createSparsificationAndBufferizationPass() {
235  SparsificationOptions sparseOptions;
236  return std::make_unique<
238  getBufferizationOptionsForSparsification(/*analysisOnly=*/false),
239  sparseOptions,
240  /*createSparseDeallocs=*/false,
241  /*enableRuntimeLibrary=*/false,
242  /*enableBufferInitialization=*/false);
243 }
244 
246  const bufferization::OneShotBufferizationOptions &bufferizationOptions,
247  const SparsificationOptions &sparsificationOptions,
248  bool createSparseDeallocs, bool enableRuntimeLibrary,
249  bool enableBufferInitialization, unsigned vectorLength,
250  bool enableVLAVectorization, bool enableSIMDIndex32, bool enableGPULibgen,
251  SparseEmitStrategy emitStrategy) {
252  return std::make_unique<
254  bufferizationOptions, sparsificationOptions, createSparseDeallocs,
255  enableRuntimeLibrary, enableBufferInitialization, vectorLength,
256  enableVLAVectorization, enableSIMDIndex32, enableGPULibgen, emitStrategy);
257 }
static llvm::ManagedStatic< PassManagerOptions > options
Attributes are known-constant values of operations.
Definition: Attributes.h:25
This class represents a pass manager that runs passes on either a specific operation type,...
Definition: PassManager.h:47
void addPass(std::unique_ptr< Pass > pass)
Add the given pass to this pass manager.
Definition: Pass.cpp:364
void addNestedPass(std::unique_ptr< Pass > pass)
Add the given pass to a nested pass manager for the given operation kind OpT.
Definition: PassManager.h:116
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition: Operation.h:373
result_range getResults()
Definition: Operation.h:410
This class provides an abstraction over the various different ranges of value types.
Definition: TypeRange.h:36
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:74
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:129
void denyOperation()
Deny the given ops.
A pass that lowers tensor ops to memref ops, regardless of whether they are dense or sparse.
SparsificationAndBufferizationPass(const bufferization::OneShotBufferizationOptions &bufferizationOptions, const SparsificationOptions &sparsificationOptions, bool createSparseDeallocs, bool enableRuntimeLibrary, bool enableBufferInitialization, unsigned vl, bool vla, bool index32, bool gpu, SparseEmitStrategy emitStrategy)
SparsificationAndBufferizationPass(const bufferization::OneShotBufferizationOptions &bufferizationOptions, const SparsificationOptions &sparsificationOptions, bool createSparseDeallocs, bool enableRuntimeLibrary, bool enableBufferInitialization)
BaseMemRefType getMemRefTypeWithStaticIdentityLayout(TensorType tensorType, Attribute memorySpace=nullptr)
Return a MemRef type with a static identity layout (i.e., no layout map).
LogicalResult insertTensorCopies(Operation *op, const OneShotBufferizationOptions &options, BufferizationStatistics *statistics=nullptr)
Resolve RaW and other conflicts by inserting bufferization.alloc_tensor ops.
void removeBufferizationAttributesInModule(ModuleOp moduleOp)
Remove bufferization attributes on every FuncOp arguments in the ModuleOp.
std::unique_ptr< Pass > createEmptyTensorToAllocTensorPass()
Create a pass that rewrites tensor.empty to bufferization.alloc_tensor.
llvm::LogicalResult bufferizeModuleOp(ModuleOp moduleOp, const OneShotBufferizationOptions &options, BufferizationStatistics *statistics=nullptr)
Bufferize op and its nested ops that implement BufferizableOpInterface.
static bool containsSparseTensor(TypeRange types)
Return true if one of the given types is a sparse tensor type.
SparseTensorEncodingAttr getSparseTensorEncoding(Type type)
Convenience method to get a sparse encoding attribute from a type.
Include the generated interface declarations.
std::unique_ptr< Pass > createSparseVectorizationPass()
std::unique_ptr< Pass > createLowerSparseOpsToForeachPass()
std::unique_ptr< Pass > createSparseTensorCodegenPass()
std::unique_ptr< Pass > createSparseGPUCodegenPass()
std::unique_ptr< Pass > createSparseSpaceCollapsePass()
std::unique_ptr< Pass > createLoopInvariantCodeMotionPass()
Creates a loop invariant code motion pass that hoists loop invariant instructions out of the loop.
bufferization::OneShotBufferizationOptions getBufferizationOptionsForSparsification(bool analysisOnly)
std::unique_ptr< Pass > createSparseReinterpretMapPass()
std::unique_ptr< Pass > createSparseTensorConversionPass()
std::unique_ptr< Pass > createSparseBufferRewritePass()
std::unique_ptr< Pass > createSparsificationAndBufferizationPass()
SparseEmitStrategy
Defines a scope for reinterpret map pass.
Definition: Passes.h:52
std::unique_ptr< Pass > createPreSparsificationRewritePass()
std::unique_ptr< Pass > createLowerForeachToSCFPass()
std::unique_ptr< Pass > createLowerSparseIterationToSCFPass()
std::unique_ptr< Pass > createStageSparseOperationsPass()
std::unique_ptr< Pass > createSparsificationPass()
Options for the Sparsification pass.
Definition: Passes.h:93
SparseEmitStrategy sparseEmitStrategy
Definition: Passes.h:107
Options for BufferizableOpInterface-based bufferization.
bool testAnalysisOnly
If set to true, does not modify the IR apart from adding attributes (for checking the results of the ...
OpFilter opFilter
A filter that specifies which ops should be bufferized and which ops should be ignored.
Options for analysis-enabled bufferization.