Skip to content

Commit 4b13b75

Browse files
committed
[mlir] Add a pass to tile Linalg ops using linalg.tiled_loop.
Differential Revision: https://reviews.llvm.org/D101084
1 parent b845217 commit 4b13b75

8 files changed

Lines changed: 143 additions & 11 deletions

File tree

‎mlir/include/mlir/Dialect/Linalg/Passes.h‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@ createLinalgTilingPass(ArrayRef<int64_t> tileSizes = {});
2929
std::unique_ptr<OperationPass<FuncOp>>
3030
createLinalgTilingToParallelLoopsPass(ArrayRef<int64_t> tileSizes = {});
3131

32+
std::unique_ptr<OperationPass<FuncOp>>
33+
createLinalgTilingToTiledLoopPass(ArrayRef<int64_t> tileSizes = {});
34+
3235
std::unique_ptr<OperationPass<FuncOp>>
3336
createLinalgPromotionPass(bool dynamicBuffers, bool useAlloca);
3437
std::unique_ptr<OperationPass<FuncOp>> createLinalgPromotionPass();

‎mlir/include/mlir/Dialect/Linalg/Passes.td‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -121,8 +121,7 @@ def LinalgTiling : FunctionPass<"linalg-tile"> {
121121
"scf::SCFDialect"
122122
];
123123
let options = [
124-
ListOption<"tileSizes", "linalg-tile-sizes", "int64_t",
125-
"Test generation of dynamic promoted buffers",
124+
ListOption<"tileSizes", "linalg-tile-sizes", "int64_t", "Tile sizes",
126125
"llvm::cl::ZeroOrMore, llvm::cl::MiscFlags::CommaSeparated">
127126
];
128127
}
@@ -132,8 +131,23 @@ def LinalgTilingToParallelLoops
132131
let summary = "Tile operations in the linalg dialect to parallel loops";
133132
let constructor = "mlir::createLinalgTilingToParallelLoopsPass()";
134133
let options = [
135-
ListOption<"tileSizes", "linalg-tile-sizes", "int64_t",
136-
"Test generation of dynamic promoted buffers",
134+
ListOption<"tileSizes", "linalg-tile-sizes", "int64_t", "Tile sizes",
135+
"llvm::cl::ZeroOrMore, llvm::cl::MiscFlags::CommaSeparated">
136+
];
137+
let dependentDialects = [
138+
"AffineDialect",
139+
"linalg::LinalgDialect",
140+
"memref::MemRefDialect",
141+
"scf::SCFDialect"
142+
];
143+
}
144+
145+
def LinalgTilingToTiledLoops
146+
: FunctionPass<"linalg-tile-to-tiled-loop"> {
147+
let summary = "Tile operations in the linalg dialect to linalg.tiled_loop";
148+
let constructor = "mlir::createLinalgTilingToTiledLoopPass()";
149+
let options = [
150+
ListOption<"tileSizes", "linalg-tile-sizes", "int64_t", "Tile sizes",
137151
"llvm::cl::ZeroOrMore, llvm::cl::MiscFlags::CommaSeparated">
138152
];
139153
let dependentDialects = [

‎mlir/include/mlir/Dialect/Linalg/Transforms/Transforms.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,7 @@ enum class LinalgTilingLoopType {
424424
Loops = 0,
425425
AffineLoops = 1,
426426
ParallelLoops = 2,
427+
TiledLoops = 3,
427428
};
428429

429430
using TileSizeComputationFunction =

‎mlir/include/mlir/Dialect/Linalg/Utils/Utils.h‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,7 @@ struct GenerateLoopNest {
253253
edsc::intrinsics::MemRefIndexedValue>::type;
254254

255255
static void
256-
doit(ArrayRef<Range> loopRanges, ValueRange iterArgInitValues,
256+
doit(ArrayRef<Range> loopRanges, LinalgOp linalgOp,
257257
ArrayRef<Attribute> iteratorTypes,
258258
function_ref<scf::ValueVector(ValueRange, ValueRange)> bodyBuilderFn,
259259
Optional<LinalgLoopDistributionOptions> = None);

‎mlir/lib/Dialect/Linalg/Transforms/Loops.cpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -473,7 +473,7 @@ static Optional<LinalgLoops> linalgOpToLoopsImpl(Operation *op,
473473

474474
SmallVector<Value, 4> allIvs;
475475
GenerateLoopNest<LoopTy>::doit(
476-
loopRanges, /*iterInitArgs=*/{}, iteratorTypes,
476+
loopRanges, linalgOp, iteratorTypes,
477477
[&](ValueRange ivs, ValueRange iterArgs) -> scf::ValueVector {
478478
assert(iterArgs.empty() && "unexpected iterArgs");
479479
allIvs.append(ivs.begin(), ivs.end());

‎mlir/lib/Dialect/Linalg/Transforms/Tiling.cpp‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -312,9 +312,8 @@ tileLinalgOpImpl(OpBuilder &b, LinalgOp op, ValueRange tileSizes,
312312
// 2. Create the tiled loops.
313313
LinalgOp res = op;
314314
SmallVector<Value, 4> ivs, tensorResults;
315-
auto outputTensors = op.getOutputTensors();
316315
GenerateLoopNest<LoopTy>::doit(
317-
loopRanges, /*iterArgInitValues*/ outputTensors, iteratorTypes,
316+
loopRanges, op, iteratorTypes,
318317
[&](ValueRange localIvs, ValueRange iterArgs) -> scf::ValueVector {
319318
auto &b = ScopedContext::getBuilderRef();
320319
auto loc = ScopedContext::getLocation();
@@ -439,6 +438,8 @@ mlir::linalg::tileLinalgOp(OpBuilder &b, LinalgOp op,
439438
return tileLinalgOpImpl<scf::ForOp>(b, op, options);
440439
case LinalgTilingLoopType::ParallelLoops:
441440
return tileLinalgOpImpl<scf::ParallelOp>(b, op, options);
441+
case LinalgTilingLoopType::TiledLoops:
442+
return tileLinalgOpImpl<linalg::TiledLoopOp>(b, op, options);
442443
default:;
443444
}
444445
return llvm::None;
@@ -567,6 +568,17 @@ struct LinalgTilingToParallelLoopsPass
567568
}
568569
};
569570

571+
struct LinalgTilingToTiledLoopsPass
572+
: public LinalgTilingToTiledLoopsBase<LinalgTilingToTiledLoopsPass> {
573+
LinalgTilingToTiledLoopsPass() = default;
574+
LinalgTilingToTiledLoopsPass(ArrayRef<int64_t> sizes) { tileSizes = sizes; }
575+
576+
void runOnFunction() override {
577+
applyTilingToLoopPatterns(LinalgTilingLoopType::TiledLoops, getFunction(),
578+
tileSizes);
579+
}
580+
};
581+
570582
} // namespace
571583

572584
std::unique_ptr<OperationPass<FuncOp>>
@@ -578,3 +590,8 @@ std::unique_ptr<OperationPass<FuncOp>>
578590
mlir::createLinalgTilingToParallelLoopsPass(ArrayRef<int64_t> tileSizes) {
579591
return std::make_unique<LinalgTilingToParallelLoopsPass>(tileSizes);
580592
}
593+
594+
std::unique_ptr<OperationPass<FuncOp>>
595+
mlir::createLinalgTilingToTiledLoopPass(ArrayRef<int64_t> tileSizes) {
596+
return std::make_unique<LinalgTilingToTiledLoopsPass>(tileSizes);
597+
}

‎mlir/lib/Dialect/Linalg/Utils/Utils.cpp‎

Lines changed: 45 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,7 @@ bool mlir::linalg::isWindowIteratorType(Attribute attr) {
142142
template struct mlir::linalg::GenerateLoopNest<scf::ForOp>;
143143
template struct mlir::linalg::GenerateLoopNest<scf::ParallelOp>;
144144
template struct mlir::linalg::GenerateLoopNest<AffineForOp>;
145+
template struct mlir::linalg::GenerateLoopNest<TiledLoopOp>;
145146

146147
/// Given a list of subview ranges, extract individual values for lower, upper
147148
/// bounds and steps and put them into the corresponding vectors.
@@ -186,10 +187,11 @@ IntegerAttr getSmallestBoundingIndex(Value size) {
186187
/// Specialization to build an scf "for" nest.
187188
template <>
188189
void GenerateLoopNest<scf::ForOp>::doit(
189-
ArrayRef<Range> loopRanges, ValueRange iterArgInitValues,
190+
ArrayRef<Range> loopRanges, LinalgOp linalgOp,
190191
ArrayRef<Attribute> iteratorTypes,
191192
function_ref<scf::ValueVector(ValueRange, ValueRange)> bodyBuilderFn,
192193
Optional<LinalgLoopDistributionOptions> distributionOptions) {
194+
auto iterArgInitValues = linalgOp.getOutputTensors();
193195
// Create procInfo so it dominates loops, if appropriate.
194196
OpBuilder &builder = edsc::ScopedContext::getBuilderRef();
195197
Location loc = edsc::ScopedContext::getLocation();
@@ -216,10 +218,11 @@ void GenerateLoopNest<scf::ForOp>::doit(
216218
/// Specialization to build affine "for" nest.
217219
template <>
218220
void GenerateLoopNest<AffineForOp>::doit(
219-
ArrayRef<Range> loopRanges, ValueRange iterArgInitValues,
221+
ArrayRef<Range> loopRanges, LinalgOp linalgOp,
220222
ArrayRef<Attribute> iteratorTypes,
221223
function_ref<scf::ValueVector(ValueRange, ValueRange)> bodyBuilderFn,
222224
Optional<LinalgLoopDistributionOptions>) {
225+
auto iterArgInitValues = linalgOp.getOutputTensors();
223226
assert(iterArgInitValues.empty() && "unexpected AffineForOp init values");
224227
SmallVector<Value, 4> lbs, ubs, steps;
225228
unpackRanges(loopRanges, lbs, ubs, steps);
@@ -240,6 +243,44 @@ void GenerateLoopNest<AffineForOp>::doit(
240243
bodyBuilderWithoutIterArgsFn);
241244
}
242245

246+
/// Specialization to build an linalg.tiled_loop
247+
template <>
248+
void GenerateLoopNest<TiledLoopOp>::doit(
249+
ArrayRef<Range> loopRanges, LinalgOp linalgOp,
250+
ArrayRef<Attribute> iteratorTypes,
251+
function_ref<scf::ValueVector(ValueRange, ValueRange)> bodyBuilderFn,
252+
Optional<LinalgLoopDistributionOptions>) {
253+
OpBuilder &builder = edsc::ScopedContext::getBuilderRef();
254+
Location loc = edsc::ScopedContext::getLocation();
255+
SmallVector<ProcInfo, 2> procInfo;
256+
257+
SmallVector<Value, 4> lbs, ubs, steps;
258+
unpackRanges(loopRanges, lbs, ubs, steps);
259+
260+
auto wrappedBuilderFn = [&](OpBuilder &nestedBuilder, Location nestedLoc,
261+
ValueRange ivs, ValueRange inputs,
262+
ValueRange outputs) {
263+
ScopedContext context(nestedBuilder, nestedLoc);
264+
scf::ValueVector results = bodyBuilderFn(ivs, linalgOp.getOutputTensors());
265+
nestedBuilder.create<linalg::YieldOp>(nestedLoc, results);
266+
};
267+
268+
auto tiledLoop = builder.create<TiledLoopOp>(
269+
loc, lbs, ubs, steps, linalgOp.getInputs(), linalgOp.getOutputs(),
270+
builder.getArrayAttr(iteratorTypes), wrappedBuilderFn);
271+
272+
// Replace inputs/outputs with the corresponding region args.
273+
auto isInsideTiledLoop = [&](OpOperand &operand) {
274+
return operand.getOwner()->getBlock() == tiledLoop.getBody();
275+
};
276+
for (auto it :
277+
llvm::zip(linalgOp.getInputs(), tiledLoop.getRegionInputArgs()))
278+
std::get<0>(it).replaceUsesWithIf(std::get<1>(it), isInsideTiledLoop);
279+
for (auto it :
280+
llvm::zip(linalgOp.getOutputs(), tiledLoop.getRegionOutputArgs()))
281+
std::get<0>(it).replaceUsesWithIf(std::get<1>(it), isInsideTiledLoop);
282+
}
283+
243284
/// Update the `lb`, `ub` and `step` to get per processor `lb`, `ub` and `step`.
244285
void updateBoundsForCyclicDistribution(OpBuilder &builder, Location loc,
245286
Value procId, Value nprocs, Value &lb,
@@ -373,10 +414,11 @@ generateParallelLoopNest(ValueRange lbs, ValueRange ubs, ValueRange steps,
373414
/// Specialization for generating a mix of parallel and sequential scf loops.
374415
template <>
375416
void GenerateLoopNest<scf::ParallelOp>::doit(
376-
ArrayRef<Range> loopRanges, ValueRange iterArgInitValues,
417+
ArrayRef<Range> loopRanges, LinalgOp linalgOp,
377418
ArrayRef<Attribute> iteratorTypes,
378419
function_ref<scf::ValueVector(ValueRange, ValueRange)> bodyBuilderFn,
379420
Optional<LinalgLoopDistributionOptions> distributionOptions) {
421+
auto iterArgInitValues = linalgOp.getOutputTensors();
380422
assert(iterArgInitValues.empty() && "unexpected ParallelOp init values");
381423
// This function may be passed more iterator types than ranges.
382424
assert(iteratorTypes.size() >= loopRanges.size() &&

‎mlir/test/Dialect/Linalg/tile-tensors.mlir‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// RUN: mlir-opt %s -linalg-tile="linalg-tile-sizes=2,3,4" -split-input-file | FileCheck %s
2+
// RUN: mlir-opt %s -linalg-tile-to-tiled-loop="linalg-tile-sizes=2,3,4" -split-input-file | FileCheck %s -check-prefix=TLOOP
23

34
// CHECK-LABEL: func @matmul_tensors(
45
// CHECK-SAME: %[[TA:[0-9a-z]+]]: tensor<?x?xf32>
@@ -27,6 +28,38 @@ func @matmul_tensors(
2728
return %0 : tensor<?x?xf32>
2829
}
2930

31+
// TLOOP-LABEL: func @matmul_tensors
32+
// TLOOP-SAME: (%[[ARG_0:.*]]: [[TY:.*]], %[[ARG_1:.*]]: [[TY]],
33+
// TLOOP-SAME: %[[ARG_2:.*]]: [[TY]]) -> [[TY]] {
34+
35+
// TLOOP-DAG: %[[C0:.*]] = constant 0 : index
36+
// TLOOP-DAG: %[[C1:.*]] = constant 1 : index
37+
// TLOOP-DAG: %[[C2:.*]] = constant 2 : index
38+
// TLOOP-DAG: %[[C3:.*]] = constant 3 : index
39+
// TLOOP-DAG: %[[C4:.*]] = constant 4 : index
40+
41+
// TLOOP: %[[ARG_0_X:.*]] = memref.dim %[[ARG_0]], %[[C0]] : [[TY]]
42+
// TLOOP: %[[ARG_0_Y:.*]] = memref.dim %[[ARG_0]], %[[C1]] : [[TY]]
43+
// TLOOP: %[[ARG_1_Y:.*]] = memref.dim %[[ARG_1]], %[[C1]] : [[TY]]
44+
45+
// TLOOP: %{{.*}} = linalg.tiled_loop (%[[I:.*]], %[[J:.*]], %[[K:.*]]) =
46+
// TLOOP-SAME: (%[[C0]], %[[C0]], %[[C0]])
47+
// TLOOP-SAME: to (%[[ARG_0_X]], %[[ARG_1_Y]], %[[ARG_0_Y]])
48+
// TLOOP-SAME: step (%[[C2]], %[[C3]], %[[C4]])
49+
// TLOOP-SAME: ins (%[[A0:.*]] = %[[ARG_0]]: [[TY]], %[[A1:.*]] = %[[ARG_1]]: [[TY]])
50+
// TLOOP-SAME: outs (%[[A2:.*]] = %[[ARG_2]]: [[TY]])
51+
// TLOOP-SAME: iterators["parallel", "parallel", "reduction"] {
52+
53+
// TLOOP: %[[SUB_ARG_0:.*]] = subtensor %[[A0]][%[[I]], %[[K]]]
54+
// TLOOP: %[[SUB_ARG_1:.*]] = subtensor %[[A1]][%[[K]], %[[J]]]
55+
// TLOOP: %[[SUB_ARG_2:.*]] = subtensor %[[A2]][%[[I]], %[[J]]]
56+
57+
// TLOOP: %[[PROD:.*]] = linalg.matmul ins(%[[SUB_ARG_0]], %[[SUB_ARG_1]]
58+
// TLOOP-SE: outs(%[[SUB_ARG_2]] : [[TY]]) -> [[TY]]
59+
60+
// TLOOP: %[[O:.*]] = subtensor_insert %[[PROD]] into %[[A2]][%[[I]], %[[J]]]
61+
// TLOOP: linalg.yield %[[O]] : [[TY]]
62+
3063
// -----
3164

3265
func @generic_op_tensors(
@@ -74,6 +107,28 @@ func @generic_op_tensors(
74107
// CHECK: }
75108
// CHECK: return %[[TD0]]
76109

110+
// TLOOP-LABEL: func @generic_op_tensors(
111+
// TLOOP-SAME: %[[ARG_0:.*]]: [[TY:.*]],
112+
// TLOOP-SAME: %[[ARG_1:.*]]: [[TY]]) -> [[TY]] {
113+
114+
// TLOOP-DAG: %[[C0:.*]] = constant 0 : index
115+
// TLOOP-DAG: %[[C1:.*]] = constant 1 : index
116+
// TLOOP-DAG: %[[C2:.*]] = constant 2 : index
117+
// TLOOP-DAG: %[[C3:.*]] = constant 3 : index
118+
// TLOOP-DAG: %[[C4:.*]] = constant 4 : index
119+
120+
// TLOOP: %[[INIT:.*]] = linalg.init_tensor
121+
// TLOOP: %[[ARG_0_X:.*]] = memref.dim %[[ARG_0]], %[[C0]] : [[TY]]
122+
// TLOOP: %[[ARG_0_Y:.*]] = memref.dim %[[ARG_0]], %[[C1]] : [[TY]]
123+
// TLOOP: %[[ARG_0_Z:.*]] = memref.dim %[[ARG_0]], %[[C2]] : [[TY]]
124+
125+
// TLOOP: %{{.*}} = linalg.tiled_loop (%{{.*}}, %{{.*}}, %{{.*}}) =
126+
// TLOOP-SAME: (%[[C0]], %[[C0]], %[[C0]])
127+
// TLOOP-SAME: to (%[[ARG_0_X]], %[[ARG_0_Y]], %[[ARG_0_Z]])
128+
// TLOOP-SAME: step (%[[C2]], %[[C3]], %[[C4]])
129+
// TLOOP-SAME: ins (%{{.*}} = %[[ARG_0]]: [[TY]], %{{.*}} = %[[ARG_1]]: [[TY]])
130+
// TLOOP-SAME: outs (%{{.*}} = %[[INIT]]: [[TY]])
131+
77132
// -----
78133

79134
func @indexed_generic_op_tensors(

0 commit comments

Comments
 (0)