1 # Buffer Deallocation - Internals
3 This section covers the internal functionality of the BufferDeallocation
4 transformation. The transformation consists of several passes. The main pass
5 called BufferDeallocation can be applied via “-buffer-deallocation” on MLIR
12 In order to use BufferDeallocation on an arbitrary dialect, several control-flow
13 interfaces have to be implemented when using custom operations. This is
14 particularly important to understand the implicit control-flow dependencies
15 between different parts of the input program. Without implementing the following
16 interfaces, control-flow relations cannot be discovered properly and the
17 resulting program can become invalid:
19 * Branch-like terminators should implement the `BranchOpInterface` to query
20 and manipulate associated operands.
21 * Operations involving structured control flow have to implement the
22 `RegionBranchOpInterface` to model inter-region control flow.
23 * Terminators yielding values to their parent operation (in particular in the
24 scope of nested regions within `RegionBranchOpInterface`-based operations),
25 should implement the `ReturnLike` trait to represent logical “value
28 Example dialects that are fully compatible are the “std” and “scf” dialects with
29 respect to all implemented interfaces.
31 During Bufferization, we convert immutable value types (tensors) to mutable
32 types (memref). This conversion is done in several steps and in all of these
33 steps the IR has to fulfill SSA like properties. The usage of memref has to be
34 in the following consecutive order: allocation, write-buffer, read- buffer. In
35 this case, there are only buffer reads allowed after the initial full buffer
36 write is done. In particular, there must be no partial write to a buffer after
37 the initial write has been finished. However, partial writes in the initializing
38 is allowed (fill buffer step by step in a loop e.g.). This means, all buffer
39 writes needs to dominate all buffer reads.
41 Example for breaking the invariant:
44 func.func @condBranch(%arg0: i1, %arg1: memref<2xf32>) {
45 %0 = memref.alloc() : memref<2xf32>
46 cf.cond_br %arg0, ^bb1, ^bb2
53 test.copy(%0, %arg1) : (memref<2xf32>, memref<2xf32>) -> ()
58 The maintenance of the SSA like properties is only needed in the bufferization
59 process. Afterwards, for example in optimization processes, the property is no
62 ## Detection of Buffer Allocations
64 The first step of the BufferDeallocation transformation is to identify
65 manageable allocation operations that implement the `SideEffects` interface.
66 Furthermore, these ops need to apply the effect `MemoryEffects::Allocate` to a
67 particular result value while not using the resource
68 `SideEffects::AutomaticAllocationScopeResource` (since it is currently reserved
69 for allocations, like `Alloca` that will be automatically deallocated by a
70 parent scope). Allocations that have not been detected in this phase will not be
71 tracked internally, and thus, not deallocated automatically. However,
72 BufferDeallocation is fully compatible with “hybrid” setups in which tracked and
73 untracked allocations are mixed:
76 func.func @mixedAllocation(%arg0: i1) {
77 %0 = memref.alloca() : memref<2xf32> // aliases: %2
78 %1 = memref.alloc() : memref<2xf32> // aliases: %2
79 cf.cond_br %arg0, ^bb1, ^bb2
82 cf.br ^bb3(%0 : memref<2xf32>)
85 cf.br ^bb3(%1 : memref<2xf32>)
86 ^bb3(%2: memref<2xf32>):
91 Example of using a conditional branch with alloc and alloca. BufferDeallocation
92 can detect and handle the different allocation types that might be intermixed.
94 Note: the current version does not support allocation operations returning
95 multiple result buffers.
97 ## Conversion from AllocOp to AllocaOp
99 The PromoteBuffersToStack-pass converts AllocOps to AllocaOps, if possible. In
100 some cases, it can be useful to use such stack-based buffers instead of
101 heap-based buffers. The conversion is restricted to several constraints like:
107 If a buffer is leaving a block, we are not allowed to convert it into an alloca.
108 If the size of the buffer is large, we could convert it, but regarding stack
109 overflow, it makes sense to limit the size of these buffers and only convert
110 small ones. The size can be set via a pass option. The current default value is
111 1KB. Furthermore, we can not convert buffers with dynamic size, since the
112 dimension is not known a priori.
114 ## Movement and Placement of Allocations
116 Using the buffer hoisting pass, all buffer allocations are moved as far upwards
117 as possible in order to group them and make upcoming optimizations easier by
118 limiting the search space. Such a movement is shown in the following graphs. In
119 addition, we are able to statically free an alloc, if we move it into a
120 dominator of all of its uses. This simplifies further optimizations (e.g. buffer
121 fusion) in the future. However, movement of allocations is limited by external
122 data dependencies (in particular in the case of allocations of dynamically
123 shaped types). Furthermore, allocations can be moved out of nested regions, if
124 necessary. In order to move allocations to valid locations with respect to their
125 uses only, we leverage Liveness information.
127 The following code snippets shows a conditional branch before running the
130 ![branch_example_pre_move](/includes/img/branch_example_pre_move.svg)
133 func.func @condBranch(%arg0: i1, %arg1: memref<2xf32>, %arg2: memref<2xf32>) {
134 cf.cond_br %arg0, ^bb1, ^bb2
136 cf.br ^bb3(%arg1 : memref<2xf32>)
138 %0 = memref.alloc() : memref<2xf32> // aliases: %1
140 cf.br ^bb3(%0 : memref<2xf32>)
141 ^bb3(%1: memref<2xf32>): // %1 could be %0 or %arg1
142 test.copy(%1, %arg2) : (memref<2xf32>, memref<2xf32>) -> ()
147 Applying the BufferHoisting pass on this program results in the following piece
150 ![branch_example_post_move](/includes/img/branch_example_post_move.svg)
153 func.func @condBranch(%arg0: i1, %arg1: memref<2xf32>, %arg2: memref<2xf32>) {
154 %0 = memref.alloc() : memref<2xf32> // moved to bb0
155 cf.cond_br %arg0, ^bb1, ^bb2
157 cf.br ^bb3(%arg1 : memref<2xf32>)
160 cf.br ^bb3(%0 : memref<2xf32>)
161 ^bb3(%1: memref<2xf32>):
162 test.copy(%1, %arg2) : (memref<2xf32>, memref<2xf32>) -> ()
167 The alloc is moved from bb2 to the beginning and it is passed as an argument to
170 The following example demonstrates an allocation using dynamically shaped types.
171 Due to the data dependency of the allocation to %0, we cannot move the
172 allocation out of bb2 in this case:
175 func.func @condBranchDynamicType(
177 %arg1: memref<?xf32>,
178 %arg2: memref<?xf32>,
180 cf.cond_br %arg0, ^bb1, ^bb2(%arg3: index)
182 cf.br ^bb3(%arg1 : memref<?xf32>)
184 %1 = memref.alloc(%0) : memref<?xf32> // cannot be moved upwards to the data
187 cf.br ^bb3(%1 : memref<?xf32>)
188 ^bb3(%2: memref<?xf32>):
189 test.copy(%2, %arg2) : (memref<?xf32>, memref<?xf32>) -> ()
194 ## Introduction of Clones
196 In order to guarantee that all allocated buffers are freed properly, we have to
197 pay attention to the control flow and all potential aliases a buffer allocation
198 can have. Since not all allocations can be safely freed with respect to their
199 aliases (see the following code snippet), it is often required to introduce
200 copies to eliminate them. Consider the following example in which the
201 allocations have already been placed:
204 func.func @branch(%arg0: i1) {
205 %0 = memref.alloc() : memref<2xf32> // aliases: %2
206 cf.cond_br %arg0, ^bb1, ^bb2
208 %1 = memref.alloc() : memref<2xf32> // resides here for demonstration purposes
210 cf.br ^bb3(%1 : memref<2xf32>)
213 cf.br ^bb3(%0 : memref<2xf32>)
214 ^bb3(%2: memref<2xf32>):
220 The first alloc can be safely freed after the live range of its post-dominator
221 block (bb3). The alloc in bb1 has an alias %2 in bb3 that also keeps this buffer
222 alive until the end of bb3. Since we cannot determine the actual branches that
223 will be taken at runtime, we have to ensure that all buffers are freed correctly
224 in bb3 regardless of the branches we will take to reach the exit block. This
225 makes it necessary to introduce a copy for %2, which allows us to free %alloc0
226 in bb0 and %alloc1 in bb1. Afterwards, we can continue processing all aliases of
227 %2 (none in this case) and we can safely free %2 at the end of the sample
228 program. This sample demonstrates that not all allocations can be safely freed
229 in their associated post-dominator blocks. Instead, we have to pay attention to
230 all of their aliases.
232 Applying the BufferDeallocation pass to the program above yields the following
236 func.func @branch(%arg0: i1) {
237 %0 = memref.alloc() : memref<2xf32>
238 cf.cond_br %arg0, ^bb1, ^bb2
240 %1 = memref.alloc() : memref<2xf32>
241 %3 = bufferization.clone %1 : (memref<2xf32>) -> (memref<2xf32>)
242 memref.dealloc %1 : memref<2xf32> // %1 can be safely freed here
243 cf.br ^bb3(%3 : memref<2xf32>)
246 %4 = bufferization.clone %0 : (memref<2xf32>) -> (memref<2xf32>)
247 cf.br ^bb3(%4 : memref<2xf32>)
248 ^bb3(%2: memref<2xf32>):
250 memref.dealloc %2 : memref<2xf32> // free temp buffer %2
251 memref.dealloc %0 : memref<2xf32> // %0 can be safely freed here
256 Note that a temporary buffer for %2 was introduced to free all allocations
257 properly. Note further that the unnecessary allocation of %3 can be easily
258 removed using one of the post-pass transformations or the canonicalization pass.
260 The presented example also works with dynamically shaped types.
262 BufferDeallocation performs a fix-point iteration taking all aliases of all
263 tracked allocations into account. We initialize the general iteration process
264 using all tracked allocations and their associated aliases. As soon as we
265 encounter an alias that is not properly dominated by our allocation, we mark
266 this alias as *critical* (needs to be freed and tracked by the internal
267 fix-point iteration). The following sample demonstrates the presence of critical
268 and non-critical aliases:
270 ![nested_branch_example_pre_move](/includes/img/nested_branch_example_pre_move.svg)
273 func.func @condBranchDynamicTypeNested(
275 %arg1: memref<?xf32>, // aliases: %3, %4
276 %arg2: memref<?xf32>,
278 cf.cond_br %arg0, ^bb1, ^bb2(%arg3: index)
280 cf.br ^bb6(%arg1 : memref<?xf32>)
282 %1 = memref.alloc(%0) : memref<?xf32> // cannot be moved upwards due to the data
284 // aliases: %2, %3, %4
286 cf.cond_br %arg0, ^bb3, ^bb4
288 cf.br ^bb5(%1 : memref<?xf32>)
290 cf.br ^bb5(%1 : memref<?xf32>)
291 ^bb5(%2: memref<?xf32>): // non-crit. alias of %1, since %1 dominates %2
292 cf.br ^bb6(%2 : memref<?xf32>)
293 ^bb6(%3: memref<?xf32>): // crit. alias of %arg1 and %2 (in other words %1)
294 cf.br ^bb7(%3 : memref<?xf32>)
295 ^bb7(%4: memref<?xf32>): // non-crit. alias of %3, since %3 dominates %4
296 test.copy(%4, %arg2) : (memref<?xf32>, memref<?xf32>) -> ()
301 Applying BufferDeallocation yields the following output:
303 ![nested_branch_example_post_move](/includes/img/nested_branch_example_post_move.svg)
306 func.func @condBranchDynamicTypeNested(
308 %arg1: memref<?xf32>,
309 %arg2: memref<?xf32>,
311 cf.cond_br %arg0, ^bb1, ^bb2(%arg3 : index)
313 // temp buffer required due to alias %3
314 %5 = bufferization.clone %arg1 : (memref<?xf32>) -> (memref<?xf32>)
315 cf.br ^bb6(%5 : memref<?xf32>)
317 %1 = memref.alloc(%0) : memref<?xf32>
319 cf.cond_br %arg0, ^bb3, ^bb4
321 cf.br ^bb5(%1 : memref<?xf32>)
323 cf.br ^bb5(%1 : memref<?xf32>)
324 ^bb5(%2: memref<?xf32>):
325 %6 = bufferization.clone %1 : (memref<?xf32>) -> (memref<?xf32>)
326 memref.dealloc %1 : memref<?xf32>
327 cf.br ^bb6(%6 : memref<?xf32>)
328 ^bb6(%3: memref<?xf32>):
329 cf.br ^bb7(%3 : memref<?xf32>)
330 ^bb7(%4: memref<?xf32>):
331 test.copy(%4, %arg2) : (memref<?xf32>, memref<?xf32>) -> ()
332 memref.dealloc %3 : memref<?xf32> // free %3, since %4 is a non-crit. alias of %3
337 Since %3 is a critical alias, BufferDeallocation introduces an additional
338 temporary copy in all predecessor blocks. %3 has an additional (non-critical)
339 alias %4 that extends the live range until the end of bb7. Therefore, we can
340 free %3 after its last use, while taking all aliases into account. Note that %4
341 does not need to be freed, since we did not introduce a copy for it.
343 The actual introduction of buffer copies is done after the fix-point iteration
344 has been terminated and all critical aliases have been detected. A critical
345 alias can be either a block argument or another value that is returned by an
346 operation. Copies for block arguments are handled by analyzing all predecessor
347 blocks. This is primarily done by querying the `BranchOpInterface` of the
348 associated branch terminators that can jump to the current block. Consider the
349 following example which involves a simple branch and the critical block argument
353 custom.br ^bb1(..., %0, : ...)
355 custom.br ^bb1(..., %1, : ...)
357 ^bb1(%2: memref<2xf32>):
361 The `BranchOpInterface` allows us to determine the actual values that will be
362 passed to block bb1 and its argument %2 by analyzing its predecessor blocks.
363 Once we have resolved the values %0 and %1 (that are associated with %2 in this
364 sample), we can introduce a temporary buffer and clone its contents into the new
365 buffer. Afterwards, we rewire the branch operands to use the newly allocated
366 buffer instead. However, blocks can have implicitly defined predecessors by
367 parent ops that implement the `RegionBranchOpInterface`. This can be the case if
368 this block argument belongs to the entry block of a region. In this setting, we
369 have to identify all predecessor regions defined by the parent operation. For
370 every region, we need to get all terminator operations implementing the
371 `ReturnLike` trait, indicating that they can branch to our current block.
372 Finally, we can use a similar functionality as described above to add the
373 temporary copy. This time, we can modify the terminator operands directly
374 without touching a high-level interface.
376 Consider the following inner-region control-flow sample that uses an imaginary
377 “custom.region_if” operation. It either executes the “then” or “else” region and
378 always continues to the “join” region. The “custom.region_if_yield” operation
379 returns a result to the parent operation. This sample demonstrates the use of
380 the `RegionBranchOpInterface` to determine predecessors in order to infer the
381 high-level control flow:
384 func.func @inner_region_control_flow(
386 %arg1 : index) -> memref<?x?xf32> {
387 %0 = memref.alloc(%arg0, %arg0) : memref<?x?xf32>
388 %1 = custom.region_if %0 : memref<?x?xf32> -> (memref<?x?xf32>)
389 then(%arg2 : memref<?x?xf32>) { // aliases: %arg4, %1
390 custom.region_if_yield %arg2 : memref<?x?xf32>
391 } else(%arg3 : memref<?x?xf32>) { // aliases: %arg4, %1
392 custom.region_if_yield %arg3 : memref<?x?xf32>
393 } join(%arg4 : memref<?x?xf32>) { // aliases: %1
394 custom.region_if_yield %arg4 : memref<?x?xf32>
396 return %1 : memref<?x?xf32>
400 ![region_branch_example_pre_move](/includes/img/region_branch_example_pre_move.svg)
402 Non-block arguments (other values) can become aliases when they are returned by
403 dialect-specific operations. BufferDeallocation supports this behavior via the
404 `RegionBranchOpInterface`. Consider the following example that uses an “scf.if”
405 operation to determine the value of %2 at runtime which creates an alias:
408 func.func @nested_region_control_flow(%arg0 : index, %arg1 : index) -> memref<?x?xf32> {
409 %0 = arith.cmpi "eq", %arg0, %arg1 : index
410 %1 = memref.alloc(%arg0, %arg0) : memref<?x?xf32>
411 %2 = scf.if %0 -> (memref<?x?xf32>) {
412 scf.yield %1 : memref<?x?xf32> // %2 will be an alias of %1
414 %3 = memref.alloc(%arg0, %arg1) : memref<?x?xf32> // nested allocation in a div.
417 scf.yield %1 : memref<?x?xf32> // %2 will be an alias of %1
419 return %2 : memref<?x?xf32>
423 In this example, a dealloc is inserted to release the buffer within the else
424 block since it cannot be accessed by the remainder of the program. Accessing the
425 `RegionBranchOpInterface`, allows us to infer that %2 is a non-critical alias of
426 %1 which does not need to be tracked.
429 func.func @nested_region_control_flow(%arg0: index, %arg1: index) -> memref<?x?xf32> {
430 %0 = arith.cmpi "eq", %arg0, %arg1 : index
431 %1 = memref.alloc(%arg0, %arg0) : memref<?x?xf32>
432 %2 = scf.if %0 -> (memref<?x?xf32>) {
433 scf.yield %1 : memref<?x?xf32>
435 %3 = memref.alloc(%arg0, %arg1) : memref<?x?xf32>
437 memref.dealloc %3 : memref<?x?xf32> // %3 can be safely freed here
438 scf.yield %1 : memref<?x?xf32>
440 return %2 : memref<?x?xf32>
444 Analogous to the previous case, we have to detect all terminator operations in
445 all attached regions of “scf.if” that provides a value to its parent operation
446 (in this sample via scf.yield). Querying the `RegionBranchOpInterface` allows us
447 to determine the regions that “return” a result to their parent operation. Like
448 before, we have to update all `ReturnLike` terminators as described above.
449 Reconsider a slightly adapted version of the “custom.region_if” example from
450 above that uses a nested allocation:
453 func.func @inner_region_control_flow_div(
455 %arg1 : index) -> memref<?x?xf32> {
456 %0 = memref.alloc(%arg0, %arg0) : memref<?x?xf32>
457 %1 = custom.region_if %0 : memref<?x?xf32> -> (memref<?x?xf32>)
458 then(%arg2 : memref<?x?xf32>) { // aliases: %arg4, %1
459 custom.region_if_yield %arg2 : memref<?x?xf32>
460 } else(%arg3 : memref<?x?xf32>) {
461 %2 = memref.alloc(%arg0, %arg1) : memref<?x?xf32> // aliases: %arg4, %1
462 custom.region_if_yield %2 : memref<?x?xf32>
463 } join(%arg4 : memref<?x?xf32>) { // aliases: %1
464 custom.region_if_yield %arg4 : memref<?x?xf32>
466 return %1 : memref<?x?xf32>
470 Since the allocation %2 happens in a divergent branch and cannot be safely
471 deallocated in a post-dominator, %arg4 will be considered a critical alias.
472 Furthermore, %arg4 is returned to its parent operation and has an alias %1. This
473 causes BufferDeallocation to introduce additional copies:
476 func.func @inner_region_control_flow_div(
478 %arg1 : index) -> memref<?x?xf32> {
479 %0 = memref.alloc(%arg0, %arg0) : memref<?x?xf32>
480 %1 = custom.region_if %0 : memref<?x?xf32> -> (memref<?x?xf32>)
481 then(%arg2 : memref<?x?xf32>) {
482 %4 = bufferization.clone %arg2 : (memref<?x?xf32>) -> (memref<?x?xf32>)
483 custom.region_if_yield %4 : memref<?x?xf32>
484 } else(%arg3 : memref<?x?xf32>) {
485 %2 = memref.alloc(%arg0, %arg1) : memref<?x?xf32>
486 %5 = bufferization.clone %2 : (memref<?x?xf32>) -> (memref<?x?xf32>)
487 memref.dealloc %2 : memref<?x?xf32>
488 custom.region_if_yield %5 : memref<?x?xf32>
489 } join(%arg4: memref<?x?xf32>) {
490 %4 = bufferization.clone %arg4 : (memref<?x?xf32>) -> (memref<?x?xf32>)
491 memref.dealloc %arg4 : memref<?x?xf32>
492 custom.region_if_yield %4 : memref<?x?xf32>
494 memref.dealloc %0 : memref<?x?xf32> // %0 can be safely freed here
495 return %1 : memref<?x?xf32>
499 ## Placement of Deallocs
501 After introducing allocs and copies, deallocs have to be placed to free
502 allocated memory and avoid memory leaks. The deallocation needs to take place
503 after the last use of the given value. The position can be determined by
504 calculating the common post-dominator of all values using their remaining
505 non-critical aliases. A special-case is the presence of back edges: since such
506 edges can cause memory leaks when a newly allocated buffer flows back to another
507 part of the program. In these cases, we need to free the associated buffer
508 instances from the previous iteration by inserting additional deallocs.
510 Consider the following “scf.for” use case containing a nested structured
514 func.func @loop_nested_if(
519 %res: memref<2xf32>) {
520 %0 = scf.for %i = %lb to %ub step %step
521 iter_args(%iterBuf = %buf) -> memref<2xf32> {
522 %1 = arith.cmpi "eq", %i, %ub : index
523 %2 = scf.if %1 -> (memref<2xf32>) {
524 %3 = memref.alloc() : memref<2xf32> // makes %2 a critical alias due to a
525 // divergent allocation
527 scf.yield %3 : memref<2xf32>
529 scf.yield %iterBuf : memref<2xf32>
531 scf.yield %2 : memref<2xf32>
533 test.copy(%0, %res) : (memref<2xf32>, memref<2xf32>) -> ()
538 In this example, the *then* branch of the nested “scf.if” operation returns a
539 newly allocated buffer.
541 Since this allocation happens in the scope of a divergent branch, %2 becomes a
542 critical alias that needs to be handled. As before, we have to insert additional
543 copies to eliminate this alias using copies of %3 and %iterBuf. This guarantees
544 that %2 will be a newly allocated buffer that is returned in each iteration.
545 However, “returning” %2 to its alias %iterBuf turns %iterBuf into a critical
546 alias as well. In other words, we have to create a copy of %2 to pass it to
547 %iterBuf. Since this jump represents a back edge, and %2 will always be a new
548 buffer, we have to free the buffer from the previous iteration to avoid memory
552 func.func @loop_nested_if(
557 %res: memref<2xf32>) {
558 %4 = bufferization.clone %buf : (memref<2xf32>) -> (memref<2xf32>)
559 %0 = scf.for %i = %lb to %ub step %step
560 iter_args(%iterBuf = %4) -> memref<2xf32> {
561 %1 = arith.cmpi "eq", %i, %ub : index
562 %2 = scf.if %1 -> (memref<2xf32>) {
563 %3 = memref.alloc() : memref<2xf32> // makes %2 a critical alias
565 %5 = bufferization.clone %3 : (memref<2xf32>) -> (memref<2xf32>)
566 memref.dealloc %3 : memref<2xf32>
567 scf.yield %5 : memref<2xf32>
569 %6 = bufferization.clone %iterBuf : (memref<2xf32>) -> (memref<2xf32>)
570 scf.yield %6 : memref<2xf32>
572 %7 = bufferization.clone %2 : (memref<2xf32>) -> (memref<2xf32>)
573 memref.dealloc %2 : memref<2xf32>
574 memref.dealloc %iterBuf : memref<2xf32> // free backedge iteration variable
575 scf.yield %7 : memref<2xf32>
577 test.copy(%0, %res) : (memref<2xf32>, memref<2xf32>) -> ()
578 memref.dealloc %0 : memref<2xf32> // free temp copy %0
583 Example for loop-like control flow. The CFG contains back edges that have to be
584 handled to avoid memory leaks. The bufferization is able to free the backedge
585 iteration variable %iterBuf.
587 ## Private Analyses Implementations
589 The BufferDeallocation transformation relies on one primary control-flow
590 analysis: BufferPlacementAliasAnalysis. Furthermore, we also use dominance and
591 liveness to place and move nodes. The liveness analysis determines the live
592 range of a given value. Within this range, a value is alive and can or will be
593 used in the course of the program. After this range, the value is dead and can
594 be discarded - in our case, the buffer can be freed. To place the allocs, we
595 need to know from which position a value will be alive. The allocs have to be
596 placed in front of this position. However, the most important analysis is the
597 alias analysis that is needed to introduce copies and to place all
602 In order to limit the complexity of the BufferDeallocation transformation, some
603 tiny code-polishing/optimization transformations are not applied on-the-fly
604 during placement. Currently, a canonicalization pattern is added to the clone
605 operation to reduce the appearance of unnecessary clones.
607 Note: further transformations might be added to the post-pass phase in the
610 ## Clone Canonicalization
612 During placement of clones it may happen, that unnecessary clones are inserted.
613 If these clones appear with their corresponding dealloc operation within the
614 same block, we can use the canonicalizer to remove these unnecessary operations.
615 Note, that this step needs to take place after the insertion of clones and
616 deallocs in the buffer deallocation step. The canonicalization inludes both, the
617 newly created target value from the clone operation and the source operation.
619 ## Canonicalization of the Source Buffer of the Clone Operation
621 In this case, the source of the clone operation can be used instead of its
622 target. The unused allocation and deallocation operations that are defined for
623 this clone operation are also removed. Here is a working example generated by
624 the BufferDeallocation pass that allocates a buffer with dynamic size. A deeper
625 analysis of this sample reveals that the highlighted operations are redundant
629 func.func @dynamic_allocation(%arg0: index, %arg1: index) -> memref<?x?xf32> {
630 %1 = memref.alloc(%arg0, %arg1) : memref<?x?xf32>
631 %2 = bufferization.clone %1 : (memref<?x?xf32>) -> (memref<?x?xf32>)
632 memref.dealloc %1 : memref<?x?xf32>
633 return %2 : memref<?x?xf32>
637 Will be transformed to:
640 func.func @dynamic_allocation(%arg0: index, %arg1: index) -> memref<?x?xf32> {
641 %1 = memref.alloc(%arg0, %arg1) : memref<?x?xf32>
642 return %1 : memref<?x?xf32>
646 In this case, the additional copy %2 can be replaced with its original source
647 buffer %1. This also applies to the associated dealloc operation of %1.
649 ## Canonicalization of the Target Buffer of the Clone Operation
651 In this case, the target buffer of the clone operation can be used instead of
652 its source. The unused deallocation operation that is defined for this clone
653 operation is also removed.
655 Consider the following example where a generic test operation writes the result
656 to %temp and then copies %temp to %result. However, these two operations can be
657 merged into a single step. Canonicalization removes the clone operation and
658 %temp, and replaces the uses of %temp with %result:
661 func.func @reuseTarget(%arg0: memref<2xf32>, %result: memref<2xf32>){
662 %temp = memref.alloc() : memref<2xf32>
666 indexing_maps = [#map0, #map0],
667 iterator_types = ["parallel"]} %arg0, %temp {
668 ^bb0(%gen2_arg0: f32, %gen2_arg1: f32):
669 %tmp2 = math.exp %gen2_arg0 : f32
670 test.yield %tmp2 : f32
671 }: memref<2xf32>, memref<2xf32>
672 %result = bufferization.clone %temp : (memref<2xf32>) -> (memref<2xf32>)
673 memref.dealloc %temp : memref<2xf32>
678 Will be transformed to:
681 func.func @reuseTarget(%arg0: memref<2xf32>, %result: memref<2xf32>){
685 indexing_maps = [#map0, #map0],
686 iterator_types = ["parallel"]} %arg0, %result {
687 ^bb0(%gen2_arg0: f32, %gen2_arg1: f32):
688 %tmp2 = math.exp %gen2_arg0 : f32
689 test.yield %tmp2 : f32
690 }: memref<2xf32>, memref<2xf32>
697 BufferDeallocation introduces additional clones from “memref” dialect
698 (“bufferization.clone”). Analogous, all deallocations use the “memref”
699 dialect-free operation “memref.dealloc”. The actual copy process is realized
700 using “test.copy”. Furthermore, buffers are essentially immutable after their
701 creation in a block. Another limitations are known in the case using
702 unstructered control flow.