-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathPTOCanonicalizeSubviewForTLoad.cpp
More file actions
326 lines (288 loc) · 9.64 KB
/
PTOCanonicalizeSubviewForTLoad.cpp
File metadata and controls
326 lines (288 loc) · 9.64 KB
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
// Copyright (c) 2026 Huawei Technologies Co., Ltd.
// This program is free software, you can redistribute it and/or modify it under the terms and conditions of
// CANN Open Software License Agreement Version 2.0 (the "License").
// Please refer to the License for details. You may not use this file except in compliance with the License.
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
// See LICENSE in the root of the software repository for the full text of the License.
#include "PTO/IR/PTO.h"
#include "PTO/Transforms/Passes.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Pass/Pass.h"
#include "llvm/ADT/DenseSet.h"
namespace mlir {
namespace pto {
#define GEN_PASS_DEF_PTOCANONICALIZESUBVIEWFORTLOAD
#include "PTO/Transforms/Passes.h.inc"
} // namespace pto
} // namespace mlir
using namespace mlir;
using namespace mlir::pto;
namespace {
static constexpr llvm::StringLiteral kLayoutAttrName = "layout";
static constexpr llvm::StringLiteral kSingletonAxisPermutationAttrName =
"pto.singleton_axis_permutation";
static Value peelUnrealized(Value v) {
if (auto castOp = v.getDefiningOp<UnrealizedConversionCastOp>())
return castOp.getOperand(0);
return v;
}
static std::optional<int64_t> extractStaticInt(OpFoldResult ofr) {
if (auto attr = ofr.dyn_cast<Attribute>()) {
if (auto ia = dyn_cast<IntegerAttr>(attr))
return ia.getInt();
return std::nullopt;
}
Value v = ofr.get<Value>();
if (auto cIdx = v.getDefiningOp<arith::ConstantIndexOp>())
return cIdx.value();
if (auto cInt = v.getDefiningOp<arith::ConstantIntOp>())
return cInt.value();
if (auto c = v.getDefiningOp<arith::ConstantOp>()) {
if (auto ia = dyn_cast<IntegerAttr>(c.getValue()))
return ia.getInt();
}
return std::nullopt;
}
static std::optional<mlir::pto::Layout> getLayoutAttrFromOp(Operation *op) {
if (!op)
return std::nullopt;
if (auto attr = op->getAttrOfType<mlir::pto::LayoutAttr>(kLayoutAttrName))
return attr.getLayout();
return std::nullopt;
}
static std::optional<mlir::pto::Layout> resolveLayoutFromValueChain(Value v) {
v = peelUnrealized(v);
while (Operation *def = v.getDefiningOp()) {
if (auto layout = getLayoutAttrFromOp(def))
return layout;
if (auto subview = dyn_cast<memref::SubViewOp>(def)) {
v = peelUnrealized(subview.getSource());
continue;
}
if (auto reinterpret = dyn_cast<memref::ReinterpretCastOp>(def)) {
v = peelUnrealized(reinterpret.getSource());
continue;
}
if (auto cast = dyn_cast<memref::CastOp>(def)) {
v = peelUnrealized(cast.getSource());
continue;
}
if (auto unrealized = dyn_cast<UnrealizedConversionCastOp>(def)) {
if (unrealized->getNumOperands() == 0)
break;
v = peelUnrealized(unrealized.getOperand(0));
continue;
}
break;
}
return std::nullopt;
}
static std::optional<mlir::pto::Layout>
resolveLayoutForGlobalTensor(Operation *anchor, Value basePtr) {
if (auto layout = getLayoutAttrFromOp(anchor))
return layout;
return resolveLayoutFromValueChain(basePtr);
}
static std::optional<pto::TileBufConfigAttr>
resolveTileConfigFromValueChain(Value v) {
v = peelUnrealized(v);
while (Operation *def = v.getDefiningOp()) {
if (auto bind = dyn_cast<pto::BindTileOp>(def))
return bind.getConfigAttr();
if (auto cast = dyn_cast<pto::PointerCastOp>(def)) {
if (auto cfg = cast.getConfig())
return *cfg;
return std::nullopt;
}
if (auto mcast = dyn_cast<memref::CastOp>(def)) {
v = peelUnrealized(mcast.getSource());
continue;
}
if (auto rc = dyn_cast<memref::ReinterpretCastOp>(def)) {
v = peelUnrealized(rc.getSource());
continue;
}
if (auto sv = dyn_cast<memref::SubViewOp>(def)) {
v = peelUnrealized(sv.getSource());
continue;
}
if (auto unrealized = dyn_cast<UnrealizedConversionCastOp>(def)) {
if (unrealized->getNumOperands() == 0)
break;
v = peelUnrealized(unrealized.getOperand(0));
continue;
}
break;
}
return std::nullopt;
}
static bool isNZLikeTileConfig(pto::TileBufConfigAttr configAttr) {
int32_t blVal = 0;
if (auto bl = dyn_cast<BLayoutAttr>(configAttr.getBLayout()))
blVal = static_cast<int32_t>(bl.getValue());
int32_t slVal = 0;
if (auto sl = dyn_cast<SLayoutAttr>(configAttr.getSLayout()))
slVal = static_cast<int32_t>(sl.getValue());
int32_t fractal = 0;
if (auto fr = dyn_cast<IntegerAttr>(configAttr.getSFractalSize()))
fractal = fr.getInt();
return blVal == static_cast<int32_t>(BLayout::ColMajor) &&
slVal == static_cast<int32_t>(SLayout::RowMajor) && fractal == 512;
}
static bool tracesBackThroughViewCasts(Value v, Value target) {
Value cur = peelUnrealized(v);
for (int guard = 0; guard < 64; ++guard) {
if (cur == target)
return true;
Operation *def = cur.getDefiningOp();
if (!def)
return false;
if (auto mcast = dyn_cast<memref::CastOp>(def)) {
cur = peelUnrealized(mcast.getSource());
continue;
}
if (auto rc = dyn_cast<memref::ReinterpretCastOp>(def)) {
cur = peelUnrealized(rc.getSource());
continue;
}
if (auto unrealized = dyn_cast<UnrealizedConversionCastOp>(def)) {
if (unrealized->getNumOperands() == 0)
return false;
cur = peelUnrealized(unrealized.getOperand(0));
continue;
}
return false;
}
return false;
}
static void collectUsersThroughViewCasts(Value v,
SmallVectorImpl<Operation *> &out) {
SmallVector<Value, 8> worklist;
llvm::DenseSet<Value> visitedValues;
llvm::DenseSet<Operation *> visitedUsers;
worklist.push_back(v);
while (!worklist.empty()) {
Value cur = worklist.pop_back_val();
if (!visitedValues.insert(cur).second)
continue;
for (Operation *u : cur.getUsers()) {
if (auto unrealized = dyn_cast<UnrealizedConversionCastOp>(u)) {
for (Value r : unrealized->getResults())
worklist.push_back(r);
continue;
}
if (auto mcast = dyn_cast<memref::CastOp>(u)) {
worklist.push_back(mcast.getResult());
continue;
}
if (auto rc = dyn_cast<memref::ReinterpretCastOp>(u)) {
worklist.push_back(rc.getResult());
continue;
}
if (visitedUsers.insert(u).second)
out.push_back(u);
}
}
}
static bool isNdDnToNzLikeTLoad(pto::TLoadOp load) {
if (!load.getDst())
return false;
auto gtLayout =
resolveLayoutForGlobalTensor(load.getOperation(), load.getSrc());
if (!gtLayout ||
(*gtLayout != mlir::pto::Layout::ND &&
*gtLayout != mlir::pto::Layout::DN))
return false;
auto tileCfg = resolveTileConfigFromValueChain(load.getDst());
if (!tileCfg)
return false;
return isNZLikeTileConfig(*tileCfg);
}
static bool shouldCanonicalizeSubviewForNdDnToNz(memref::SubViewOp sv) {
SmallVector<Operation *, 8> users;
collectUsersThroughViewCasts(sv.getResult(), users);
bool sawTarget = false;
for (Operation *user : users) {
auto load = dyn_cast<pto::TLoadOp>(user);
if (!load)
return false;
if (!tracesBackThroughViewCasts(load.getSrc(), sv.getResult()))
continue;
if (!isNdDnToNzLikeTLoad(load))
return false;
sawTarget = true;
}
return sawTarget;
}
static std::optional<SmallVector<int64_t, 8>>
computeSingletonFirstPermutation(memref::SubViewOp sv) {
auto resTy = dyn_cast<MemRefType>(sv.getResult().getType());
if (!resTy)
return std::nullopt;
const int rank = resTy.getRank();
if (rank <= 2)
return std::nullopt;
auto mixedSizes = sv.getMixedSizes();
auto resShape = resTy.getShape();
SmallVector<bool, 8> staticSingletonDims;
staticSingletonDims.reserve(rank);
int nonSingletonCount = 0;
for (int i = 0; i < rank; ++i) {
std::optional<int64_t> staticDim;
if (i < static_cast<int>(mixedSizes.size()))
staticDim = extractStaticInt(mixedSizes[i]);
if (!staticDim && resShape[i] != ShapedType::kDynamic)
staticDim = resShape[i];
bool isSingleton = staticDim && *staticDim == 1;
staticSingletonDims.push_back(isSingleton);
if (!isSingleton)
++nonSingletonCount;
}
if (nonSingletonCount > 2)
return std::nullopt;
SmallVector<int64_t, 8> permutation;
permutation.reserve(rank);
for (int i = 0; i < rank; ++i) {
if (staticSingletonDims[i])
permutation.push_back(i);
}
for (int i = 0; i < rank; ++i) {
if (!staticSingletonDims[i])
permutation.push_back(i);
}
bool changed = false;
for (int i = 0; i < rank; ++i) {
if (permutation[i] != i) {
changed = true;
break;
}
}
if (!changed)
return std::nullopt;
return permutation;
}
struct PTOCanonicalizeSubviewForTLoadPass
: public mlir::pto::impl::PTOCanonicalizeSubviewForTLoadBase<
PTOCanonicalizeSubviewForTLoadPass> {
void runOnOperation() override {
func::FuncOp func = getOperation();
MLIRContext *ctx = &getContext();
func.walk([&](memref::SubViewOp sv) {
sv->removeAttr(kSingletonAxisPermutationAttrName);
auto perm = computeSingletonFirstPermutation(sv);
if (!perm)
return;
if (!shouldCanonicalizeSubviewForNdDnToNz(sv))
return;
sv->setAttr(kSingletonAxisPermutationAttrName,
DenseI64ArrayAttr::get(ctx, *perm));
});
}
};
} // namespace
std::unique_ptr<Pass> mlir::pto::createPTOCanonicalizeSubviewForTLoadPass() {
return std::make_unique<PTOCanonicalizeSubviewForTLoadPass>();
}