File: BufferizationToMemRef.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (436 lines) | stat: -rw-r--r-- 19,440 bytes parent folder | download | duplicates (2)
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//===- BufferizationToMemRef.cpp - Bufferization to MemRef conversion -----===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This file implements patterns to convert Bufferization dialect to MemRef
// dialect.
//
//===----------------------------------------------------------------------===//

#include "mlir/Conversion/BufferizationToMemRef/BufferizationToMemRef.h"

#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/Bufferization/IR/Bufferization.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/SCF/IR/SCF.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Support/LogicalResult.h"
#include "mlir/Transforms/DialectConversion.h"

namespace mlir {
#define GEN_PASS_DEF_CONVERTBUFFERIZATIONTOMEMREF
#include "mlir/Conversion/Passes.h.inc"
} // namespace mlir

using namespace mlir;

namespace {
/// The CloneOpConversion transforms all bufferization clone operations into
/// memref alloc and memref copy operations. In the dynamic-shape case, it also
/// emits additional dim and constant operations to determine the shape. This
/// conversion does not resolve memory leaks if it is used alone.
struct CloneOpConversion : public OpConversionPattern<bufferization::CloneOp> {
  using OpConversionPattern<bufferization::CloneOp>::OpConversionPattern;

  LogicalResult
  matchAndRewrite(bufferization::CloneOp op, OpAdaptor adaptor,
                  ConversionPatternRewriter &rewriter) const override {
    // Check for unranked memref types which are currently not supported.
    Type type = op.getType();
    if (isa<UnrankedMemRefType>(type)) {
      return rewriter.notifyMatchFailure(
          op, "UnrankedMemRefType is not supported.");
    }
    MemRefType memrefType = cast<MemRefType>(type);
    MemRefLayoutAttrInterface layout;
    auto allocType =
        MemRefType::get(memrefType.getShape(), memrefType.getElementType(),
                        layout, memrefType.getMemorySpace());
    // Since this implementation always allocates, certain result types of the
    // clone op cannot be lowered.
    if (!memref::CastOp::areCastCompatible({allocType}, {memrefType}))
      return failure();

    // Transform a clone operation into alloc + copy operation and pay
    // attention to the shape dimensions.
    Location loc = op->getLoc();
    SmallVector<Value, 4> dynamicOperands;
    for (int i = 0; i < memrefType.getRank(); ++i) {
      if (!memrefType.isDynamicDim(i))
        continue;
      Value dim = rewriter.createOrFold<memref::DimOp>(loc, op.getInput(), i);
      dynamicOperands.push_back(dim);
    }

    // Allocate a memref with identity layout.
    Value alloc = rewriter.create<memref::AllocOp>(op->getLoc(), allocType,
                                                   dynamicOperands);
    // Cast the allocation to the specified type if needed.
    if (memrefType != allocType)
      alloc = rewriter.create<memref::CastOp>(op->getLoc(), memrefType, alloc);
    rewriter.replaceOp(op, alloc);
    rewriter.create<memref::CopyOp>(loc, op.getInput(), alloc);
    return success();
  }
};

/// The DeallocOpConversion transforms all bufferization dealloc operations into
/// memref dealloc operations potentially guarded by scf if operations.
/// Additionally, memref extract_aligned_pointer_as_index and arith operations
/// are inserted to compute the guard conditions. We distinguish multiple cases
/// to provide an overall more efficient lowering. In the general case, a helper
/// func is created to avoid quadratic code size explosion (relative to the
/// number of operands of the dealloc operation). For examples of each case,
/// refer to the documentation of the member functions of this class.
class DeallocOpConversion
    : public OpConversionPattern<bufferization::DeallocOp> {

  /// Lower a simple case avoiding the helper function. Ideally, static analysis
  /// can provide enough aliasing information to split the dealloc operations up
  /// into this simple case as much as possible before running this pass.
  ///
  /// Example:
  /// ```
  /// %0 = bufferization.dealloc (%arg0 : memref<2xf32>) if (%arg1)
  /// ```
  /// is lowered to
  /// ```
  /// scf.if %arg1 {
  ///   memref.dealloc %arg0 : memref<2xf32>
  /// }
  /// %0 = arith.constant false
  /// ```
  LogicalResult
  rewriteOneMemrefNoRetainCase(bufferization::DeallocOp op, OpAdaptor adaptor,
                               ConversionPatternRewriter &rewriter) const {
    rewriter.create<scf::IfOp>(op.getLoc(), adaptor.getConditions()[0],
                               [&](OpBuilder &builder, Location loc) {
                                 builder.create<memref::DeallocOp>(
                                     loc, adaptor.getMemrefs()[0]);
                                 builder.create<scf::YieldOp>(loc);
                               });
    rewriter.replaceOpWithNewOp<arith::ConstantOp>(op,
                                                   rewriter.getBoolAttr(false));
    return success();
  }

  /// Lowering that supports all features the dealloc operation has to offer. It
  /// computes the base pointer of each memref (as an index), stores them in a
  /// new memref and passes it to the helper function generated in
  /// 'buildDeallocationHelperFunction'. The two return values are used as
  /// condition for the scf if operation containing the memref deallocate and as
  /// replacement for the original bufferization dealloc respectively.
  ///
  /// Example:
  /// ```
  /// %0:2 = bufferization.dealloc (%arg0, %arg1 : memref<2xf32>, memref<5xf32>)
  ///                           if (%arg3, %arg4) retain (%arg2 : memref<1xf32>)
  /// ```
  /// lowers to (simplified):
  /// ```
  /// %c0 = arith.constant 0 : index
  /// %c1 = arith.constant 1 : index
  /// %alloc = memref.alloc() : memref<2xindex>
  /// %alloc_0 = memref.alloc() : memref<1xindex>
  /// %intptr = memref.extract_aligned_pointer_as_index %arg0
  /// memref.store %intptr, %alloc[%c0] : memref<2xindex>
  /// %intptr_1 = memref.extract_aligned_pointer_as_index %arg1
  /// memref.store %intptr_1, %alloc[%c1] : memref<2xindex>
  /// %intptr_2 = memref.extract_aligned_pointer_as_index %arg2
  /// memref.store %intptr_2, %alloc_0[%c0] : memref<1xindex>
  /// %cast = memref.cast %alloc : memref<2xindex> to memref<?xindex>
  /// %cast_4 = memref.cast %alloc_0 : memref<1xindex> to memref<?xindex>
  /// %0:2 = call @dealloc_helper(%cast, %cast_4, %c0)
  /// %1 = arith.andi %0#0, %arg3 : i1
  /// %2 = arith.andi %0#1, %arg3 : i1
  /// scf.if %1 {
  ///   memref.dealloc %arg0 : memref<2xf32>
  /// }
  /// %3:2 = call @dealloc_helper(%cast, %cast_4, %c1)
  /// %4 = arith.andi %3#0, %arg4 : i1
  /// %5 = arith.andi %3#1, %arg4 : i1
  /// scf.if %4 {
  ///   memref.dealloc %arg1 : memref<5xf32>
  /// }
  /// memref.dealloc %alloc : memref<2xindex>
  /// memref.dealloc %alloc_0 : memref<1xindex>
  /// // replace %0#0 with %2
  /// // replace %0#1 with %5
  /// ```
  LogicalResult rewriteGeneralCase(bufferization::DeallocOp op,
                                   OpAdaptor adaptor,
                                   ConversionPatternRewriter &rewriter) const {
    // Allocate two memrefs holding the base pointer indices of the list of
    // memrefs to be deallocated and the ones to be retained. These can then be
    // passed to the helper function and the for-loops can iterate over them.
    // Without storing them to memrefs, we could not use for-loops but only a
    // completely unrolled version of it, potentially leading to code-size
    // blow-up.
    Value toDeallocMemref = rewriter.create<memref::AllocOp>(
        op.getLoc(), MemRefType::get({(int64_t)adaptor.getMemrefs().size()},
                                     rewriter.getIndexType()));
    Value toRetainMemref = rewriter.create<memref::AllocOp>(
        op.getLoc(), MemRefType::get({(int64_t)adaptor.getRetained().size()},
                                     rewriter.getIndexType()));

    auto getConstValue = [&](uint64_t value) -> Value {
      return rewriter.create<arith::ConstantOp>(op.getLoc(),
                                                rewriter.getIndexAttr(value));
    };

    // Extract the base pointers of the memrefs as indices to check for aliasing
    // at runtime.
    for (auto [i, toDealloc] : llvm::enumerate(adaptor.getMemrefs())) {
      Value memrefAsIdx =
          rewriter.create<memref::ExtractAlignedPointerAsIndexOp>(op.getLoc(),
                                                                  toDealloc);
      rewriter.create<memref::StoreOp>(op.getLoc(), memrefAsIdx,
                                       toDeallocMemref, getConstValue(i));
    }
    for (auto [i, toRetain] : llvm::enumerate(adaptor.getRetained())) {
      Value memrefAsIdx =
          rewriter.create<memref::ExtractAlignedPointerAsIndexOp>(op.getLoc(),
                                                                  toRetain);
      rewriter.create<memref::StoreOp>(op.getLoc(), memrefAsIdx, toRetainMemref,
                                       getConstValue(i));
    }

    // Cast the allocated memrefs to dynamic shape because we want only one
    // helper function no matter how many operands the bufferization.dealloc
    // has.
    Value castedDeallocMemref = rewriter.create<memref::CastOp>(
        op->getLoc(),
        MemRefType::get({ShapedType::kDynamic}, rewriter.getIndexType()),
        toDeallocMemref);
    Value castedRetainMemref = rewriter.create<memref::CastOp>(
        op->getLoc(),
        MemRefType::get({ShapedType::kDynamic}, rewriter.getIndexType()),
        toRetainMemref);

    SmallVector<Value> replacements;
    for (unsigned i = 0, e = adaptor.getMemrefs().size(); i < e; ++i) {
      auto callOp = rewriter.create<func::CallOp>(
          op.getLoc(), deallocHelperFunc,
          SmallVector<Value>{castedDeallocMemref, castedRetainMemref,
                             getConstValue(i)});
      Value shouldDealloc = rewriter.create<arith::AndIOp>(
          op.getLoc(), callOp.getResult(0), adaptor.getConditions()[i]);
      Value ownership = rewriter.create<arith::AndIOp>(
          op.getLoc(), callOp.getResult(1), adaptor.getConditions()[i]);
      replacements.push_back(ownership);
      rewriter.create<scf::IfOp>(
          op.getLoc(), shouldDealloc, [&](OpBuilder &builder, Location loc) {
            builder.create<memref::DeallocOp>(loc, adaptor.getMemrefs()[i]);
            builder.create<scf::YieldOp>(loc);
          });
    }

    // Deallocate above allocated memrefs again to avoid memory leaks.
    // Deallocation will not be run on code after this stage.
    rewriter.create<memref::DeallocOp>(op.getLoc(), toDeallocMemref);
    rewriter.create<memref::DeallocOp>(op.getLoc(), toRetainMemref);

    rewriter.replaceOp(op, replacements);
    return success();
  }

public:
  DeallocOpConversion(MLIRContext *context, func::FuncOp deallocHelperFunc)
      : OpConversionPattern<bufferization::DeallocOp>(context),
        deallocHelperFunc(deallocHelperFunc) {}

  LogicalResult
  matchAndRewrite(bufferization::DeallocOp op, OpAdaptor adaptor,
                  ConversionPatternRewriter &rewriter) const override {
    // Lower the trivial case.
    if (adaptor.getMemrefs().empty())
      return rewriter.eraseOp(op), success();

    if (adaptor.getMemrefs().size() == 1 && adaptor.getRetained().empty())
      return rewriteOneMemrefNoRetainCase(op, adaptor, rewriter);

    return rewriteGeneralCase(op, adaptor, rewriter);
  }

  /// Build a helper function per compilation unit that can be called at
  /// bufferization dealloc sites to determine aliasing and ownership.
  ///
  /// The generated function takes two memrefs of indices and one index value as
  /// arguments and returns two boolean values:
  ///   * The first memref argument A should contain the result of the
  ///   extract_aligned_pointer_as_index operation applied to the memrefs to be
  ///   deallocated
  ///   * The second memref argument B should contain the result of the
  ///   extract_aligned_pointer_as_index operation applied to the memrefs to be
  ///   retained
  ///   * The index argument I represents the currently processed index of
  ///   memref A and is needed because aliasing with all previously deallocated
  ///   memrefs has to be checked to avoid double deallocation
  ///   * The first result indicates whether the memref at position I should be
  ///   deallocated
  ///   * The second result provides the updated ownership value corresponding
  ///   the the memref at position I
  ///
  /// This helper function is supposed to be called for each element in the list
  /// of memrefs to be deallocated to determine the deallocation need and new
  /// ownership indicator, but does not perform the deallocation itself.
  ///
  /// The first scf for loop in the body computes whether the memref at index I
  /// aliases with any memref in the list of retained memrefs.
  /// The second loop additionally checks whether one of the previously
  /// deallocated memrefs aliases with the currently processed one.
  ///
  /// Generated code:
  /// ```
  /// func.func @dealloc_helper(%arg0: memref<?xindex>,
  ///                           %arg1: memref<?xindex>,
  ///                           %arg2: index) -> (i1, i1) {
  ///   %c0 = arith.constant 0 : index
  ///   %c1 = arith.constant 1 : index
  ///   %true = arith.constant true
  ///   %dim = memref.dim %arg1, %c0 : memref<?xindex>
  ///   %0 = memref.load %arg0[%arg2] : memref<?xindex>
  ///   %1 = scf.for %i = %c0 to %dim step %c1 iter_args(%arg4 = %true) -> (i1){
  ///     %4 = memref.load %arg1[%i] : memref<?xindex>
  ///     %5 = arith.cmpi ne, %4, %0 : index
  ///     %6 = arith.andi %arg4, %5 : i1
  ///     scf.yield %6 : i1
  ///   }
  ///   %2 = scf.for %i = %c0 to %arg2 step %c1 iter_args(%arg4 = %1) -> (i1) {
  ///     %4 = memref.load %arg0[%i] : memref<?xindex>
  ///     %5 = arith.cmpi ne, %4, %0 : index
  ///     %6 = arith.andi %arg4, %5 : i1
  ///     scf.yield %6 : i1
  ///   }
  ///   %3 = arith.xori %1, %true : i1
  ///   return %2, %3 : i1, i1
  /// }
  /// ```
  static func::FuncOp
  buildDeallocationHelperFunction(OpBuilder &builder, Location loc,
                                  SymbolTable &symbolTable) {
    Type idxType = builder.getIndexType();
    Type memrefArgType = MemRefType::get({ShapedType::kDynamic}, idxType);
    SmallVector<Type> argTypes{memrefArgType, memrefArgType, idxType};
    builder.clearInsertionPoint();

    // Generate the func operation itself.
    auto helperFuncOp = func::FuncOp::create(
        loc, "dealloc_helper",
        builder.getFunctionType(argTypes,
                                {builder.getI1Type(), builder.getI1Type()}));
    symbolTable.insert(helperFuncOp);
    auto &block = helperFuncOp.getFunctionBody().emplaceBlock();
    block.addArguments(argTypes, SmallVector<Location>(argTypes.size(), loc));

    builder.setInsertionPointToStart(&block);
    Value toDeallocMemref = helperFuncOp.getArguments()[0];
    Value toRetainMemref = helperFuncOp.getArguments()[1];
    Value idxArg = helperFuncOp.getArguments()[2];

    // Insert some prerequisites.
    Value c0 = builder.create<arith::ConstantOp>(loc, builder.getIndexAttr(0));
    Value c1 = builder.create<arith::ConstantOp>(loc, builder.getIndexAttr(1));
    Value trueValue =
        builder.create<arith::ConstantOp>(loc, builder.getBoolAttr(true));
    Value toRetainSize = builder.create<memref::DimOp>(loc, toRetainMemref, c0);
    Value toDealloc =
        builder.create<memref::LoadOp>(loc, toDeallocMemref, idxArg);

    // Build the first for loop that computes aliasing with retained memrefs.
    Value noRetainAlias =
        builder
            .create<scf::ForOp>(
                loc, c0, toRetainSize, c1, trueValue,
                [&](OpBuilder &builder, Location loc, Value i,
                    ValueRange iterArgs) {
                  Value retainValue =
                      builder.create<memref::LoadOp>(loc, toRetainMemref, i);
                  Value doesntAlias = builder.create<arith::CmpIOp>(
                      loc, arith::CmpIPredicate::ne, retainValue, toDealloc);
                  Value yieldValue = builder.create<arith::AndIOp>(
                      loc, iterArgs[0], doesntAlias);
                  builder.create<scf::YieldOp>(loc, yieldValue);
                })
            .getResult(0);

    // Build the second for loop that adds aliasing with previously deallocated
    // memrefs.
    Value noAlias =
        builder
            .create<scf::ForOp>(
                loc, c0, idxArg, c1, noRetainAlias,
                [&](OpBuilder &builder, Location loc, Value i,
                    ValueRange iterArgs) {
                  Value prevDeallocValue =
                      builder.create<memref::LoadOp>(loc, toDeallocMemref, i);
                  Value doesntAlias = builder.create<arith::CmpIOp>(
                      loc, arith::CmpIPredicate::ne, prevDeallocValue,
                      toDealloc);
                  Value yieldValue = builder.create<arith::AndIOp>(
                      loc, iterArgs[0], doesntAlias);
                  builder.create<scf::YieldOp>(loc, yieldValue);
                })
            .getResult(0);

    Value ownership =
        builder.create<arith::XOrIOp>(loc, noRetainAlias, trueValue);
    builder.create<func::ReturnOp>(loc, SmallVector<Value>{noAlias, ownership});

    return helperFuncOp;
  }

private:
  func::FuncOp deallocHelperFunc;
};
} // namespace

namespace {
struct BufferizationToMemRefPass
    : public impl::ConvertBufferizationToMemRefBase<BufferizationToMemRefPass> {
  BufferizationToMemRefPass() = default;

  void runOnOperation() override {
    ModuleOp module = cast<ModuleOp>(getOperation());
    OpBuilder builder =
        OpBuilder::atBlockBegin(&module.getBodyRegion().front());
    SymbolTable symbolTable(module);

    // Build dealloc helper function if there are deallocs.
    func::FuncOp helperFuncOp;
    getOperation()->walk([&](bufferization::DeallocOp deallocOp) {
      if (deallocOp.getMemrefs().size() > 1 ||
          !deallocOp.getRetained().empty()) {
        helperFuncOp = DeallocOpConversion::buildDeallocationHelperFunction(
            builder, getOperation()->getLoc(), symbolTable);
        return WalkResult::interrupt();
      }
      return WalkResult::advance();
    });

    RewritePatternSet patterns(&getContext());
    patterns.add<CloneOpConversion>(patterns.getContext());
    patterns.add<DeallocOpConversion>(patterns.getContext(), helperFuncOp);

    ConversionTarget target(getContext());
    target.addLegalDialect<memref::MemRefDialect, arith::ArithDialect,
                           scf::SCFDialect, func::FuncDialect>();
    target.addIllegalDialect<bufferization::BufferizationDialect>();

    if (failed(applyPartialConversion(getOperation(), target,
                                      std::move(patterns))))
      signalPassFailure();
  }
};
} // namespace

std::unique_ptr<OperationPass<ModuleOp>>
mlir::createBufferizationToMemRefPass() {
  return std::make_unique<BufferizationToMemRefPass>();
}