MLIR  20.0.0git
BufferUtils.cpp
Go to the documentation of this file.
1 //===- BufferUtils.cpp - buffer transformation utilities ------------------===//
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 // This file implements utilities for buffer optimization passes.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 
19 #include "mlir/IR/Operation.h"
22 #include "mlir/Pass/Pass.h"
23 #include "llvm/ADT/SetOperations.h"
24 #include "llvm/ADT/SmallString.h"
25 #include <optional>
26 
27 using namespace mlir;
28 using namespace mlir::bufferization;
29 
30 //===----------------------------------------------------------------------===//
31 // BufferPlacementAllocs
32 //===----------------------------------------------------------------------===//
33 
34 /// Get the start operation to place the given alloc value withing the
35 // specified placement block.
37  Block *placementBlock,
38  const Liveness &liveness) {
39  // We have to ensure that we place the alloc before its first use in this
40  // block.
41  const LivenessBlockInfo &livenessInfo = *liveness.getLiveness(placementBlock);
42  Operation *startOperation = livenessInfo.getStartOperation(allocValue);
43  // Check whether the start operation lies in the desired placement block.
44  // If not, we will use the terminator as this is the last operation in
45  // this block.
46  if (startOperation->getBlock() != placementBlock) {
47  Operation *opInPlacementBlock =
48  placementBlock->findAncestorOpInBlock(*startOperation);
49  startOperation = opInPlacementBlock ? opInPlacementBlock
50  : placementBlock->getTerminator();
51  }
52 
53  return startOperation;
54 }
55 
56 /// Initializes the internal list by discovering all supported allocation
57 /// nodes.
59 
60 /// Searches for and registers all supported allocation entries.
61 void BufferPlacementAllocs::build(Operation *op) {
62  op->walk([&](MemoryEffectOpInterface opInterface) {
63  // Try to find a single allocation result.
65  opInterface.getEffects(effects);
66 
68  llvm::copy_if(
69  effects, std::back_inserter(allocateResultEffects),
71  Value value = it.getValue();
72  return isa<MemoryEffects::Allocate>(it.getEffect()) && value &&
73  isa<OpResult>(value) &&
74  it.getResource() !=
76  });
77  // If there is one result only, we will be able to move the allocation and
78  // (possibly existing) deallocation ops.
79  if (allocateResultEffects.size() != 1)
80  return;
81  // Get allocation result.
82  Value allocValue = allocateResultEffects[0].getValue();
83  // Find the associated dealloc value and register the allocation entry.
84  std::optional<Operation *> dealloc = memref::findDealloc(allocValue);
85  // If the allocation has > 1 dealloc associated with it, skip handling it.
86  if (!dealloc)
87  return;
88  allocs.push_back(std::make_tuple(allocValue, *dealloc));
89  });
90 }
91 
92 //===----------------------------------------------------------------------===//
93 // BufferPlacementTransformationBase
94 //===----------------------------------------------------------------------===//
95 
96 /// Constructs a new transformation base using the given root operation.
98  Operation *op)
99  : aliases(op), allocs(op), liveness(op) {}
100 
101 //===----------------------------------------------------------------------===//
102 // BufferPlacementTransformationBase
103 //===----------------------------------------------------------------------===//
104 
105 FailureOr<memref::GlobalOp>
106 bufferization::getGlobalFor(arith::ConstantOp constantOp, uint64_t alignment,
107  Attribute memorySpace) {
108  auto type = cast<RankedTensorType>(constantOp.getType());
109  auto moduleOp = constantOp->getParentOfType<ModuleOp>();
110  if (!moduleOp)
111  return failure();
112 
113  // If we already have a global for this constant value, no need to do
114  // anything else.
115  for (Operation &op : moduleOp.getRegion().getOps()) {
116  auto globalOp = dyn_cast<memref::GlobalOp>(&op);
117  if (!globalOp)
118  continue;
119  if (!globalOp.getInitialValue().has_value())
120  continue;
121  uint64_t opAlignment = globalOp.getAlignment().value_or(0);
122  Attribute initialValue = globalOp.getInitialValue().value();
123  if (opAlignment == alignment && initialValue == constantOp.getValue())
124  return globalOp;
125  }
126 
127  // Create a builder without an insertion point. We will insert using the
128  // symbol table to guarantee unique names.
129  OpBuilder globalBuilder(moduleOp.getContext());
130  SymbolTable symbolTable(moduleOp);
131 
132  // Create a pretty name.
133  SmallString<64> buf;
134  llvm::raw_svector_ostream os(buf);
135  interleave(type.getShape(), os, "x");
136  os << "x" << type.getElementType();
137 
138  // Add an optional alignment to the global memref.
139  IntegerAttr memrefAlignment =
140  alignment > 0 ? IntegerAttr::get(globalBuilder.getI64Type(), alignment)
141  : IntegerAttr();
142 
143  // Memref globals always have an identity layout.
144  auto memrefType =
145  cast<MemRefType>(getMemRefTypeWithStaticIdentityLayout(type));
146  if (memorySpace)
147  memrefType = MemRefType::Builder(memrefType).setMemorySpace(memorySpace);
148  auto global = globalBuilder.create<memref::GlobalOp>(
149  constantOp.getLoc(), (Twine("__constant_") + os.str()).str(),
150  /*sym_visibility=*/globalBuilder.getStringAttr("private"),
151  /*type=*/memrefType,
152  /*initial_value=*/cast<ElementsAttr>(constantOp.getValue()),
153  /*constant=*/true,
154  /*alignment=*/memrefAlignment);
155  symbolTable.insert(global);
156  // The symbol table inserts at the end of the module, but globals are a bit
157  // nicer if they are at the beginning.
158  global->moveBefore(&moduleOp.front());
159  return global;
160 }
Attributes are known-constant values of operations.
Definition: Attributes.h:25
Block represents an ordered list of Operations.
Definition: Block.h:33
Operation * findAncestorOpInBlock(Operation &op)
Returns 'op' if 'op' lies in this block, or otherwise finds the ancestor operation of 'op' that lies ...
Definition: Block.cpp:76
Operation * getTerminator()
Get the terminator operation of this block.
Definition: Block.cpp:246
IntegerType getI64Type()
Definition: Builders.cpp:109
StringAttr getStringAttr(const Twine &bytes)
Definition: Builders.cpp:302
This class represents liveness information on block level.
Definition: Liveness.h:99
Operation * getStartOperation(Value value) const
Gets the start operation for the given value.
Definition: Liveness.cpp:368
Represents an analysis for computing liveness information from a given top-level operation.
Definition: Liveness.h:47
const LivenessBlockInfo * getLiveness(Block *block) const
Gets liveness info (if any) for the block.
Definition: Liveness.cpp:229
This is a builder type that keeps local references to arguments.
Definition: BuiltinTypes.h:213
Builder & setMemorySpace(Attribute newMemorySpace)
Definition: BuiltinTypes.h:239
This class helps build Operations.
Definition: Builders.h:216
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition: Builders.cpp:497
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
Definition: Operation.h:798
Block * getBlock()
Returns the operation block that contains this operation.
Definition: Operation.h:213
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
Definition: Operation.h:687
iterator_range< OpIterator > getOps()
Definition: Region.h:172
This class represents a specific instance of an effect.
Resource * getResource() const
Return the resource that the effect applies to.
EffectT * getEffect() const
Return the effect being applied.
Value getValue() const
Return the value the effect is applied on, or nullptr if there isn't a known value being affected.
static AutomaticAllocationScopeResource * get()
Returns a unique instance for the given effect class.
This class allows for representing and managing the symbol table used by operations with the 'SymbolT...
Definition: SymbolTable.h:24
StringAttr insert(Operation *symbol, Block::iterator insertPt={})
Insert a new symbol into the table, and rename it as necessary to avoid collisions.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:96
static Operation * getStartOperation(Value allocValue, Block *placementBlock, const Liveness &liveness)
Get the start operation to place the given alloc value within the specified placement block.
Definition: BufferUtils.cpp:36
BufferPlacementAllocs(Operation *op)
Initializes the internal list by discovering all supported allocation nodes.
Definition: BufferUtils.cpp:58
BufferPlacementTransformationBase(Operation *op)
Constructs a new operation base using the given root operation.
Definition: BufferUtils.cpp:97
BaseMemRefType getMemRefTypeWithStaticIdentityLayout(TensorType tensorType, Attribute memorySpace=nullptr)
Return a MemRef type with a static identity layout (i.e., no layout map).
FailureOr< memref::GlobalOp > getGlobalFor(arith::ConstantOp constantOp, uint64_t alignment, Attribute memorySpace={})
std::optional< Operation * > findDealloc(Value allocValue)
Finds a single dealloc operation for the given allocated value.
Include the generated interface declarations.
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...