1 //===----------------------------------------------------------------------===//
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 
9 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
10 #include "mlir/Dialect/MemRef/IR/MemRef.h"
11 #include "mlir/Interfaces/SideEffectInterfaces.h"
12 #include "mlir/Transforms/InliningUtils.h"
13 
14 using namespace mlir;
15 using namespace mlir::memref;
16 
17 #include "mlir/Dialect/MemRef/IR/MemRefOpsDialect.cpp.inc"
18 
19 //===----------------------------------------------------------------------===//
20 // MemRefDialect Dialect Interfaces
21 //===----------------------------------------------------------------------===//
22 
23 namespace {
24 struct MemRefInlinerInterface : public DialectInlinerInterface {
25   using DialectInlinerInterface::DialectInlinerInterface;
26   bool isLegalToInline(Region *dest, Region *src, bool wouldBeCloned,
27                        BlockAndValueMapping &valueMapping) const final {
28     return true;
29   }
30   bool isLegalToInline(Operation *, Region *, bool wouldBeCloned,
31                        BlockAndValueMapping &) const final {
32     return true;
33   }
34 };
35 } // namespace
36 
37 void mlir::memref::MemRefDialect::initialize() {
38   addOperations<
39 #define GET_OP_LIST
40 #include "mlir/Dialect/MemRef/IR/MemRefOps.cpp.inc"
41       >();
42   addInterfaces<MemRefInlinerInterface>();
43 }
44 
45 /// Finds a single dealloc operation for the given allocated value.
46 llvm::Optional<Operation *> mlir::memref::findDealloc(Value allocValue) {
47   Operation *dealloc = nullptr;
48   for (Operation *user : allocValue.getUsers()) {
49     auto effectInterface = dyn_cast<MemoryEffectOpInterface>(user);
50     if (!effectInterface)
51       continue;
52     // Try to find a free effect that is applied to one of our values
53     // that will be automatically freed by our pass.
54     SmallVector<MemoryEffects::EffectInstance, 2> effects;
55     effectInterface.getEffectsOnValue(allocValue, effects);
56     const bool isFree =
57         llvm::any_of(effects, [&](MemoryEffects::EffectInstance &it) {
58           return isa<MemoryEffects::Free>(it.getEffect());
59         });
60     if (!isFree)
61       continue;
62     // If we found > 1 dealloc, return None.
63     if (dealloc)
64       return llvm::None;
65     dealloc = user;
66   }
67   return dealloc;
68 }
69