1 //===- BufferizableOpInterface.cpp - Bufferizable Ops  ---=----------------===//
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/Bufferization/IR/BufferizableOpInterface.h"
10 #include "mlir/Dialect/Bufferization/IR/Bufferization.h"
11 #include "mlir/Dialect/Func/IR/FuncOps.h"
12 #include "mlir/Dialect/MemRef/IR/MemRef.h"
13 #include "mlir/IR/AsmState.h"
14 #include "mlir/IR/BlockAndValueMapping.h"
15 #include "mlir/IR/BuiltinOps.h"
16 #include "mlir/IR/Operation.h"
17 #include "mlir/IR/TypeUtilities.h"
18 #include "mlir/IR/Value.h"
19 #include "llvm/Support/Debug.h"
20 
21 namespace mlir {
22 namespace bufferization {
23 
24 #include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.cpp.inc"
25 
26 } // namespace bufferization
27 } // namespace mlir
28 
29 #define DEBUG_TYPE "bufferizable-op-interface"
30 #define DBGS() (llvm::dbgs() << '[' << DEBUG_TYPE << "] ")
31 #define LDBG(X) LLVM_DEBUG(DBGS() << (X))
32 
33 using namespace mlir;
34 using namespace bufferization;
35 
36 /// Attribute name used to mark region arguments that can be bufferized
37 /// in-place during linalg comprehensive bufferization.
38 constexpr const ::llvm::StringLiteral
39     bufferization::BufferizableOpInterface::kInplaceableAttrName;
40 
41 /// Attribute name used to mark allocs that are created by the bufferization.
42 static const char *kBufferAllocationAttr = "bufferization.allocation";
43 
44 /// Attribute name used to mark allocs that should not be deallocated.
45 static const char *kSkipDeallocAttr = "bufferization.skip_dealloc";
46 
47 //===----------------------------------------------------------------------===//
48 // BufferizationOptions
49 //===----------------------------------------------------------------------===//
50 
51 // Default constructor for BufferizationOptions.
52 BufferizationOptions::BufferizationOptions() = default;
53 
54 bool BufferizationOptions::isOpAllowed(Operation *op) const {
55   // Special case: If function boundary bufferization is deactivated, do not
56   // allow ops that belong to the `func` dialect.
57   bool isFuncBoundaryOp = isa_and_nonnull<func::FuncDialect>(op->getDialect());
58   if (!bufferizeFunctionBoundaries && isFuncBoundaryOp)
59     return false;
60 
61   // All other ops: Allow/disallow according to filter.
62   bool isAllowed = !filterHasAllowRule();
63   for (const OpFilterEntry &entry : opFilter) {
64     bool filterResult = entry.fn(op);
65     switch (entry.type) {
66     case OpFilterEntry::ALLOW:
67       isAllowed |= filterResult;
68       break;
69     case OpFilterEntry::DENY:
70       if (filterResult)
71         // DENY filter matches. This op is no allowed. (Even if other ALLOW
72         // filters may match.)
73         return false;
74     };
75   }
76   return isAllowed;
77 }
78 
79 BufferizableOpInterface
80 BufferizationOptions::dynCastBufferizableOp(Operation *op) const {
81   auto bufferizableOp = dyn_cast<BufferizableOpInterface>(op);
82   if (!bufferizableOp)
83     return nullptr;
84   if (!isOpAllowed(op))
85     return nullptr;
86   return bufferizableOp;
87 }
88 
89 BufferizableOpInterface
90 BufferizationOptions::dynCastBufferizableOp(Value value) const {
91   if (auto bufferizableOp = value.getDefiningOp<BufferizableOpInterface>())
92     if (isOpAllowed(bufferizableOp.getOperation()))
93       return bufferizableOp;
94   return nullptr;
95 }
96 
97 void BufferizationOptions::addDialectStateInitializer(
98     StringRef name, const DialectStateInitFn &fn) {
99   stateInitializers.push_back(
100       [=](AnalysisState &state) { state.insertDialectState(name, fn()); });
101 }
102 
103 //===----------------------------------------------------------------------===//
104 // Helper functions for BufferizableOpInterface
105 //===----------------------------------------------------------------------===//
106 
107 static void setInsertionPointAfter(OpBuilder &b, Value value) {
108   if (auto bbArg = value.dyn_cast<BlockArgument>()) {
109     b.setInsertionPointToStart(bbArg.getOwner());
110   } else {
111     b.setInsertionPointAfter(value.getDefiningOp());
112   }
113 }
114 
115 /// Determine which OpOperand* will alias with `result` if the op is bufferized
116 /// in place. Return an empty vector if the op is not bufferizable.
117 SmallVector<OpOperand *>
118 AnalysisState::getAliasingOpOperand(OpResult result) const {
119   if (Operation *op = result.getDefiningOp())
120     if (auto bufferizableOp = getOptions().dynCastBufferizableOp(op))
121       return bufferizableOp.getAliasingOpOperand(result, *this);
122   return {};
123 }
124 
125 /// Determine which OpResult will alias with `opOperand` if the op is bufferized
126 /// in place. Return an empty vector if the op is not bufferizable.
127 SmallVector<OpResult>
128 AnalysisState::getAliasingOpResult(OpOperand &opOperand) const {
129   if (auto bufferizableOp =
130           getOptions().dynCastBufferizableOp(opOperand.getOwner()))
131     return bufferizableOp.getAliasingOpResult(opOperand, *this);
132   return {};
133 }
134 
135 /// Return true if `opOperand` bufferizes to a memory read. Return `true` if the
136 /// op is not bufferizable.
137 bool AnalysisState::bufferizesToMemoryRead(OpOperand &opOperand) const {
138   if (auto bufferizableOp =
139           getOptions().dynCastBufferizableOp(opOperand.getOwner()))
140     return bufferizableOp.bufferizesToMemoryRead(opOperand, *this);
141 
142   // Unknown op that returns a tensor. The inplace analysis does not support it.
143   // Conservatively return true.
144   return true;
145 }
146 
147 /// Return true if `opOperand` bufferizes to a memory write. Return
148 /// `true` if the op is not bufferizable.
149 bool AnalysisState::bufferizesToMemoryWrite(OpOperand &opOperand) const {
150   if (auto bufferizableOp =
151           getOptions().dynCastBufferizableOp(opOperand.getOwner()))
152     return bufferizableOp.bufferizesToMemoryWrite(opOperand, *this);
153 
154   // Unknown op that returns a tensor. The inplace analysis does not support it.
155   // Conservatively return true.
156   return true;
157 }
158 
159 /// Return true if `opOperand` does neither read nor write but bufferizes to an
160 /// alias. Return false if the op is not bufferizable.
161 bool AnalysisState::bufferizesToAliasOnly(OpOperand &opOperand) const {
162   if (auto bufferizableOp =
163           getOptions().dynCastBufferizableOp(opOperand.getOwner()))
164     return bufferizableOp.bufferizesToAliasOnly(opOperand, *this);
165 
166   // Unknown op that returns a tensor. The inplace analysis does not support it.
167   // Conservatively return false.
168   return false;
169 }
170 
171 /// Return true if the given value is read by an op that bufferizes to a memory
172 /// read. Also takes into account ops that create an alias but do not read by
173 /// themselves (e.g., ExtractSliceOp).
174 bool AnalysisState::isValueRead(Value value) const {
175   assert(value.getType().isa<TensorType>() && "expected TensorType");
176   SmallVector<OpOperand *> workingSet;
177   for (OpOperand &use : value.getUses())
178     workingSet.push_back(&use);
179 
180   while (!workingSet.empty()) {
181     OpOperand *uMaybeReading = workingSet.pop_back_val();
182     // Skip over all ops that neither read nor write (but create an alias).
183     if (bufferizesToAliasOnly(*uMaybeReading))
184       for (OpResult opResult : getAliasingOpResult(*uMaybeReading))
185         for (OpOperand &use : opResult.getUses())
186           workingSet.push_back(&use);
187     if (bufferizesToMemoryRead(*uMaybeReading))
188       return true;
189   }
190 
191   return false;
192 }
193 
194 // Starting from `value`, follow the use-def chain in reverse, always selecting
195 // the aliasing OpOperands. Find and return Values for which `condition`
196 // evaluates to true. OpOperands of such matching Values are not traversed any
197 // further.
198 llvm::SetVector<Value> AnalysisState::findValueInReverseUseDefChain(
199     Value value, llvm::function_ref<bool(Value)> condition) const {
200   llvm::SetVector<Value> result, workingSet;
201   workingSet.insert(value);
202 
203   while (!workingSet.empty()) {
204     Value value = workingSet.pop_back_val();
205     if (condition(value) || value.isa<BlockArgument>()) {
206       result.insert(value);
207       continue;
208     }
209 
210     OpResult opResult = value.cast<OpResult>();
211     SmallVector<OpOperand *> opOperands = getAliasingOpOperand(opResult);
212     if (opOperands.empty() || !options.isOpAllowed(value.getDefiningOp())) {
213       result.insert(value);
214       continue;
215     }
216 
217     for (OpOperand *o : opOperands)
218       workingSet.insert(o->get());
219   }
220 
221   return result;
222 }
223 
224 // Find the Values of the last preceding write of a given Value.
225 llvm::SetVector<Value>
226 AnalysisState::findLastPrecedingWrite(Value value) const {
227   return findValueInReverseUseDefChain(value, [&](Value value) {
228     Operation *op = value.getDefiningOp();
229     if (!op)
230       return true;
231     auto bufferizableOp = options.dynCastBufferizableOp(op);
232     if (!bufferizableOp)
233       return true;
234     return bufferizableOp.isMemoryWrite(value.cast<OpResult>(), *this);
235   });
236 }
237 
238 AnalysisState::AnalysisState(const BufferizationOptions &options)
239     : options(options) {
240   for (const BufferizationOptions::AnalysisStateInitFn &fn :
241        options.stateInitializers)
242     fn(*this);
243 }
244 
245 // bufferization.to_memref is not allowed to change the rank.
246 static void ensureToMemrefOpIsValid(Value tensor, Type memrefType) {
247 #ifndef NDEBUG
248   auto rankedTensorType = tensor.getType().dyn_cast<RankedTensorType>();
249   assert((!rankedTensorType || memrefType.cast<MemRefType>().getRank() ==
250                                    rankedTensorType.getRank()) &&
251          "to_memref would be invalid: mismatching ranks");
252 #endif
253 }
254 
255 Value mlir::bufferization::lookupBuffer(RewriterBase &rewriter, Value tensor,
256                                         const BufferizationOptions &options) {
257   auto tensorType = tensor.getType().dyn_cast<TensorType>();
258   assert(tensorType && "unexpected non-tensor type");
259 
260   // Replace "%t = to_tensor %m" with %m.
261   if (auto toTensorOp = tensor.getDefiningOp<bufferization::ToTensorOp>())
262     return toTensorOp.memref();
263 
264   // Insert to_memref op.
265   OpBuilder::InsertionGuard g(rewriter);
266   setInsertionPointAfter(rewriter, tensor);
267   Type memrefType = getMemRefType(tensorType, options);
268   ensureToMemrefOpIsValid(tensor, memrefType);
269   return rewriter.create<bufferization::ToMemrefOp>(tensor.getLoc(), memrefType,
270                                                     tensor);
271 }
272 
273 /// Return the buffer (memref) for a given OpOperand (tensor). Allocate
274 /// a new buffer and copy over data from the existing buffer if out-of-place
275 /// bufferization was decided.
276 FailureOr<Value>
277 BufferizationState::getBuffer(RewriterBase &rewriter, OpOperand &opOperand,
278                               Optional<ForceInPlacability> overrideInPlace,
279                               Optional<Operation *> customCopyInsertionPoint) {
280   const BufferizationOptions &options = analysisState.getOptions();
281   OpBuilder::InsertionGuard guard(rewriter);
282   Operation *op = opOperand.getOwner();
283   Location loc = op->getLoc();
284   SmallVector<OpResult> aliasingOpResults =
285       analysisState.getAliasingOpResult(opOperand);
286   Value operand = opOperand.get();
287   Value operandBuffer = lookupBuffer(rewriter, operand, options);
288 
289   // Can `operandBuffer` be used directly or do we need a copy?
290   bool inplace =
291       overrideInPlace != FORCE_OUT_OF_PLACE &&
292       (overrideInPlace == FORCE_INPLACE || analysisState.isInPlace(opOperand));
293   if (inplace)
294     return operandBuffer;
295 
296   // Bufferizing out-of-place: Allocate a new buffer.
297   // Move insertion point right after `operandBuffer`. That is where the
298   // allocation should be inserted (in the absence of allocation hoisting).
299   setInsertionPointAfter(rewriter, operandBuffer);
300   // Allocate the result buffer. The buffer should be deallocated if the tensor
301   // is not yielded and deallocs are enabled in general.
302   bool dealloc = llvm::none_of(aliasingOpResults, [&](Value v) {
303     return getAnalysisState().isTensorYielded(v);
304   });
305   FailureOr<Value> resultBuffer = createAlloc(
306       rewriter, loc, operandBuffer, dealloc && getOptions().createDeallocs);
307   if (failed(resultBuffer))
308     return failure();
309   // Do not copy the buffer if its contents are undefined.
310   if (analysisState.hasUndefinedContents(&opOperand))
311     return resultBuffer;
312   // Do not copy if the copied data is never read.
313   if (!aliasingOpResults.empty() &&
314       !analysisState.bufferizesToMemoryRead(opOperand) &&
315       llvm::none_of(aliasingOpResults, [&](OpResult opResult) {
316         return analysisState.isValueRead(opResult);
317       }))
318     return resultBuffer;
319   // Do not copy if this op does not read the data, but writes it.
320   if (analysisState.bufferizesToMemoryWrite(opOperand) &&
321       !analysisState.bufferizesToMemoryRead(opOperand))
322     return resultBuffer;
323 
324   if (customCopyInsertionPoint) {
325     rewriter.setInsertionPoint(*customCopyInsertionPoint);
326   } else {
327     // The copy happens right before the op that is bufferized.
328     rewriter.setInsertionPoint(op);
329   }
330   if (failed(options.createMemCpy(rewriter, loc, operandBuffer, *resultBuffer)))
331     return failure();
332 
333   return resultBuffer;
334 }
335 
336 /// Return the buffer type for a given OpOperand (tensor) after bufferization.
337 BaseMemRefType BufferizationState::getBufferType(OpOperand &opOperand) const {
338   Value tensor = opOperand.get();
339   auto tensorType = tensor.getType().dyn_cast<TensorType>();
340   assert(tensorType && "unexpected non-tensor type");
341 
342   if (auto toTensorOp = tensor.getDefiningOp<bufferization::ToTensorOp>())
343     return toTensorOp.memref().getType().cast<BaseMemRefType>();
344 
345   return getMemRefType(tensorType, getOptions());
346 }
347 
348 void bufferization::replaceOpWithBufferizedValues(RewriterBase &rewriter,
349                                                   Operation *op,
350                                                   ValueRange values) {
351   assert(values.size() == op->getNumResults() &&
352          "expected one value per OpResult");
353   OpBuilder::InsertionGuard g(rewriter);
354 
355   // Replace all OpResults with the given values.
356   SmallVector<Value> replacements;
357   for (OpResult opResult : op->getOpResults()) {
358     Value replacement = values[opResult.getResultNumber()];
359     if (opResult.getType().isa<TensorType>()) {
360       // The OpResult is a tensor. Such values are replaced with memrefs during
361       // bufferization.
362       assert((replacement.getType().isa<MemRefType>() ||
363               replacement.getType().isa<UnrankedMemRefType>()) &&
364              "tensor op result should be replaced with a memref value");
365       // The existing uses of the OpResult still expect a tensor. Insert a
366       // ToTensorOp. Throughout bufferization, this ToTensorOp will gradually
367       // loose all of its users and eventually DCE away.
368       rewriter.setInsertionPointAfter(op);
369       replacement = rewriter.create<bufferization::ToTensorOp>(
370           replacement.getLoc(), replacement);
371     }
372     replacements.push_back(replacement);
373   }
374 
375   rewriter.replaceOp(op, replacements);
376 }
377 
378 AlwaysCopyAnalysisState::AlwaysCopyAnalysisState(
379     const BufferizationOptions &options)
380     : AnalysisState(options) {
381   // Note: Allocations must be deallocated with a subsequent run of the buffer
382   // deallocation pass.
383   assert(!options.createDeallocs &&
384          "cannot create deallocs with AlwaysCopyBufferizationState");
385 }
386 
387 /// Return `true` if the given OpResult has been decided to bufferize inplace.
388 bool AlwaysCopyAnalysisState::isInPlace(OpOperand &opOperand) const {
389   // OpOperands that bufferize to a memory write are out-of-place, i.e., an
390   // alloc and copy is inserted.
391   return !bufferizesToMemoryWrite(opOperand);
392 }
393 
394 /// Return true if `v1` and `v2` bufferize to equivalent buffers.
395 bool AlwaysCopyAnalysisState::areEquivalentBufferizedValues(Value v1,
396                                                             Value v2) const {
397   // There is no analysis, so we do not know if the values are equivalent. The
398   // conservative answer is "false".
399   return false;
400 }
401 
402 /// Return `true` if the given tensor has undefined contents.
403 bool AlwaysCopyAnalysisState::hasUndefinedContents(OpOperand *opOperand) const {
404   // There is no analysis, so the conservative answer is "false".
405   return false;
406 }
407 
408 /// Return true if the given tensor (or an aliasing tensor) is yielded from
409 /// the containing block. Also include all aliasing tensors in the same block.
410 bool AlwaysCopyAnalysisState::isTensorYielded(Value tensor) const {
411   // There is no analysis, so conservatively answer "true".
412   return true;
413 }
414 
415 //===----------------------------------------------------------------------===//
416 // Bufferization-specific scoped alloc/dealloc insertion support.
417 //===----------------------------------------------------------------------===//
418 
419 /// Create a memref allocation with the given type and dynamic extents.
420 FailureOr<Value> BufferizationOptions::createAlloc(OpBuilder &b, Location loc,
421                                                    MemRefType type,
422                                                    ValueRange dynShape) const {
423   if (allocationFn)
424     return (*allocationFn)(b, loc, type, dynShape, bufferAlignment);
425 
426   // Default bufferallocation via AllocOp.
427   Value allocated = b.create<memref::AllocOp>(
428       loc, type, dynShape, b.getI64IntegerAttr(bufferAlignment));
429   return allocated;
430 }
431 
432 /// Creates a memref deallocation. The given memref buffer must have been
433 /// allocated using `createAlloc`.
434 LogicalResult BufferizationOptions::createDealloc(OpBuilder &b, Location loc,
435                                                   Value allocatedBuffer) const {
436   if (deallocationFn)
437     return (*deallocationFn)(b, loc, allocatedBuffer);
438 
439   // Default buffer deallocation via DeallocOp.
440   b.create<memref::DeallocOp>(loc, allocatedBuffer);
441   return success();
442 }
443 
444 /// Compute the type of the `memref` to use for allocating the buffer for
445 /// `shapedValue`. Also returns (by reference in `dynShape`), the value for the
446 /// dynamic dimensions in the returned `memref` type.
447 static MemRefType getAllocationTypeAndShape(OpBuilder &b, Location loc,
448                                             Value shapedValue,
449                                             SmallVectorImpl<Value> &dynShape) {
450   MemRefType allocMemRefType =
451       getContiguousMemRefType(shapedValue.getType().cast<ShapedType>());
452 
453   // Compute the dynamic part of the shape.
454   bool reifiedShapes = false;
455   if (auto rankedOp = dyn_cast_or_null<ReifyRankedShapedTypeOpInterface>(
456           shapedValue.getDefiningOp())) {
457     ReifiedRankedShapedTypeDims resultDims;
458     if (succeeded(rankedOp.reifyResultShapes(b, resultDims))) {
459       reifiedShapes = true;
460       OpResult resultValue = shapedValue.dyn_cast<OpResult>();
461       auto &shape = resultDims[resultValue.getResultNumber()];
462       for (const auto &dim : enumerate(allocMemRefType.getShape()))
463         if (ShapedType::isDynamic(dim.value()))
464           dynShape.push_back(shape[dim.index()]);
465     }
466   }
467 
468   if (!reifiedShapes) {
469     for (const auto &dim : enumerate(allocMemRefType.getShape()))
470       if (ShapedType::isDynamic(dim.value())) {
471         assert((shapedValue.getType().isa<UnrankedMemRefType>() ||
472                 shapedValue.getType().isa<MemRefType>()) &&
473                "expected MemRef type");
474         dynShape.push_back(
475             b.create<memref::DimOp>(loc, shapedValue, dim.index()));
476       }
477   }
478 
479   return allocMemRefType;
480 }
481 
482 static Value createBufferAllocation(OpBuilder &b, Location loc, MemRefType type,
483                                     ValueRange dynShape, bool skipDealloc) {
484   auto allocaOp = b.create<memref::AllocaOp>(loc, type, dynShape);
485   allocaOp->setAttr(kBufferAllocationAttr, b.getUnitAttr());
486   if (skipDealloc)
487     allocaOp->setAttr(kSkipDeallocAttr, b.getUnitAttr());
488   return allocaOp.getResult();
489 }
490 
491 /// Create an allocation after `shapedValue.getDefiningOp` (or at the top of the
492 /// block in case of a bbArg).
493 FailureOr<Value> BufferizationState::createAlloc(OpBuilder &b, Location loc,
494                                                  Value shapedValue,
495                                                  Optional<bool> dealloc) {
496   // Take a guard before anything else.
497   OpBuilder::InsertionGuard g(b);
498 
499   // Compute allocation memref type.
500   assert(shapedValue.getType().isa<ShapedType>());
501   SmallVector<Value> dynShape;
502   MemRefType allocMemRefType =
503       getAllocationTypeAndShape(b, loc, shapedValue, dynShape);
504 
505   // Should be the buffer be deallocated again or should we let it leak?
506   bool skipDealloc;
507   if (dealloc) {
508     skipDealloc = !dealloc.getValue();
509   } else {
510     assert(shapedValue.getType().isa<TensorType>() &&
511            "must specify `dealloc` if non-tensor value is passed");
512     // Buffer should be not be deallocated if deallocs are generally deactivated
513     // or if the tensor is yielded from a block.
514     skipDealloc = !getOptions().createDeallocs ||
515                   getAnalysisState().isTensorYielded(shapedValue);
516   }
517 
518   // Create the buffer allocation.
519   return createBufferAllocation(b, loc, allocMemRefType, dynShape, skipDealloc);
520 }
521 
522 /// Create a memory copy between two memref buffers.
523 LogicalResult BufferizationOptions::createMemCpy(OpBuilder &b, Location loc,
524                                                  Value from, Value to) const {
525   if (memCpyFn)
526     return (*memCpyFn)(b, loc, from, to);
527 
528   b.create<memref::CopyOp>(loc, from, to);
529   return success();
530 }
531 
532 LogicalResult
533 bufferization::createAllocDeallocOps(Operation *op,
534                                      const BufferizationOptions &options,
535                                      bool onlyLeakingAllocs, bool *changed) {
536   IRRewriter rewriter(op->getContext());
537   if (changed)
538     *changed = false;
539 
540   // Bufferization creates memref.alloca ops. After bufferization, these must be
541   // rewritten to alloc/dealloc ops as specified in the bufferization options.
542   WalkResult status = op->walk([&](memref::AllocaOp allocaOp) {
543     // Ignore memref.alloca ops that were not created by the bufferization.
544     if (!allocaOp->hasAttr(kBufferAllocationAttr))
545       return WalkResult::skip();
546     // If `onlyLeakingAllocs`, process only ops that are marked as
547     // "skip dealloc".
548     bool skipDealloc = allocaOp->hasAttr(kSkipDeallocAttr);
549     if (onlyLeakingAllocs && !skipDealloc)
550       return WalkResult::skip();
551 
552     // Create alloc.
553     Block *block = allocaOp->getBlock();
554     rewriter.setInsertionPoint(allocaOp);
555     FailureOr<Value> alloc =
556         options.createAlloc(rewriter, allocaOp->getLoc(), allocaOp.getType(),
557                             allocaOp.dynamicSizes());
558     if (failed(alloc))
559       return WalkResult::interrupt();
560     rewriter.replaceOp(allocaOp, *alloc);
561     if (changed)
562       *changed = true;
563 
564     // Stop here if the buffer should not be deallocated.
565     if (skipDealloc)
566       return WalkResult::advance();
567 
568     // Create dealloc.
569     rewriter.setInsertionPoint(block->getTerminator());
570     if (failed(options.createDealloc(rewriter, alloc->getLoc(), *alloc)))
571       return WalkResult::interrupt();
572 
573     return WalkResult::advance();
574   });
575 
576   return success(!status.wasInterrupted());
577 }
578 
579 /// Try to hoist all new buffer allocations until the next hoisting barrier.
580 // TODO: Consolidate this function with the existing buffer hoisting pass.
581 LogicalResult
582 bufferization::hoistBufferAllocations(Operation *op,
583                                       const BufferizationOptions &options) {
584   // Nothing to do if allocation hoisting is deactivated.
585   if (!options.hoistAllocations)
586     return success();
587 
588   // Gather all buffer allocations that were created by the bufferization.
589   SmallVector<Operation *> allocaOps;
590   op->walk([&](memref::AllocaOp allocaOp) {
591     if (allocaOp->hasAttr(kBufferAllocationAttr))
592       allocaOps.push_back(allocaOp);
593   });
594 
595   for (Operation *allocaOp : allocaOps) {
596     // TODO: Hoisting of allocs with dynamic shape not implemented.
597     if (!allocaOp->getOpOperands().empty())
598       continue;
599 
600     Operation *op = allocaOp->getParentOp();
601     while (op) {
602       if (auto bufferizableOp = dyn_cast<BufferizableOpInterface>(op)) {
603         if (bufferizableOp.isAllocationHoistingBarrier()) {
604           break;
605         }
606       } else {
607         // Op is not bufferizable: It may not be safe to hoist across this op.
608         break;
609       }
610       op = op->getParentOp();
611     }
612 
613     // FuncOp is an allocation hoisting barrier, so this should never happen.
614     assert(op && "allocation hoisting barrier not found");
615 
616     // Nothing to do if the insertion point is in the same block.
617     if (op == allocaOp->getParentOp())
618       continue;
619 
620     // `op` may have multiple blocks. Make sure that we insert in the right one.
621     SmallVector<Block *> blocks;
622     for (Region &r : op->getRegions())
623       for (Block &b : r.getBlocks())
624         blocks.push_back(&b);
625     auto *insertionBlock = llvm::find_if(
626         blocks, [&](Block *b) { return b->findAncestorOpInBlock(*allocaOp); });
627     assert(insertionBlock != blocks.end() && "owning block not found");
628 
629     // Move to the beginning of the block.
630     allocaOp->moveBefore(&(*insertionBlock)->front());
631   }
632 
633   return success();
634 }
635 
636 //===----------------------------------------------------------------------===//
637 // Bufferization-specific BlockAndValueMapping support with debugging.
638 //===----------------------------------------------------------------------===//
639 
640 bool bufferization::isFunctionArgument(Value value) {
641   auto bbArg = value.dyn_cast<BlockArgument>();
642   if (!bbArg)
643     return false;
644   return isa<func::FuncOp>(bbArg.getOwner()->getParentOp());
645 }
646 
647 MemRefType bufferization::getContiguousMemRefType(ShapedType shapedType,
648                                                   Attribute memorySpace) {
649   MemRefLayoutAttrInterface layout = {};
650   return MemRefType::get(shapedType.getShape(), shapedType.getElementType(),
651                          layout, memorySpace);
652 }
653 
654 BaseMemRefType bufferization::getMemRefType(TensorType tensorType,
655                                             const BufferizationOptions &options,
656                                             MemRefLayoutAttrInterface layout,
657                                             Attribute memorySpace) {
658   // Case 1: Unranked memref type.
659   if (auto unrankedTensorType = tensorType.dyn_cast<UnrankedTensorType>()) {
660     assert(!layout && "UnrankedTensorType cannot have a layout map");
661     return UnrankedMemRefType::get(unrankedTensorType.getElementType(),
662                                    memorySpace);
663   }
664 
665   // Case 2: Ranked memref type with specified layout. If fully dynamic layout
666   // maps are not requested, generate a type with `layout`, which is empty (no
667   // layout map) by default.
668   auto rankedTensorType = tensorType.cast<RankedTensorType>();
669   if (layout || !options.fullyDynamicLayoutMaps) {
670     return MemRefType::get(rankedTensorType.getShape(),
671                            rankedTensorType.getElementType(), layout,
672                            memorySpace);
673   }
674 
675   // Case 3: Ranked memref type with unspecified layout. Choose the most dynamic
676   // one.
677   // TODO: address space decisions to connect with the actual alloc.
678   int64_t dynamicOffset = ShapedType::kDynamicStrideOrOffset;
679   SmallVector<int64_t> dynamicStrides(rankedTensorType.getRank(),
680                                       ShapedType::kDynamicStrideOrOffset);
681   AffineMap stridedLayout = makeStridedLinearLayoutMap(
682       dynamicStrides, dynamicOffset, rankedTensorType.getContext());
683   return MemRefType::get(rankedTensorType.getShape(),
684                          rankedTensorType.getElementType(), stridedLayout,
685                          memorySpace);
686 }
687