MLIR  22.0.0git
OneShotAnalysis.cpp
Go to the documentation of this file.
1 //===- OneShotAnalysis.cpp - One-Shot (Single Pass) Analysis --------------===//
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 // One-Shot Analysis analyzes function bodies. By default, function boundaries
10 // (FuncOp bbArgs, CallOps, ReturnOps) are treated as "unknown" ops.
11 // OneShotModuleBufferization.cpp is an extension of One-Shot Analysis for
12 // simple call graphs without loops.
13 //
14 // One-Shot Bufferize consists of three phases.
15 //
16 // 1. Analyze ops to decide which OpOperands can bufferize inplace, i.e.,
17 // without inserting buffer copies. The analysis queries op bufferization
18 // semantics via `BufferizableOpInterface`.
19 // 2. Insert copies for OpOperands that were decided to bufferize out-of-place
20 // in tensor land during `TensorCopyInsertion`.
21 // 3. Bufferize ops by calling `BufferizableOpInterface::bufferize`.
22 //
23 // This file contains only the analysis. For convenience, this file also
24 // contains a helper function `runOneShotBufferize` that analyzes an op (and its
25 // nested ops) and then bufferizes it.
26 //
27 // Inplace bufferization decisions are passed from the analysis to the
28 // `TensorCopyInsertion` phase via `AnalysisState`. They can be printed for
29 // debugging purposes with `testAnalysisOnly`.
30 //
31 // Ops that do not implement `BufferizableOpInterface` can be analyzed but are
32 // treated conservatively. E.g., the analysis has to assume that their tensor
33 // OpOperands bufferize to memory writes. While such ops can be analyzed, they
34 // are not bufferized and remain in the IR. to_tensor and to_buffer ops are
35 // inserted at the bufferization boundary.
36 //
37 // This analysis caters to high-performance codegen where buffer reuse is deemed
38 // critical: the analysis should fail if the bufferized form of the function
39 // needs to return a buffer, unless `allowReturnAllocs` is enabled.
40 
42 
43 #include <random>
44 
50 #include "mlir/IR/AsmState.h"
51 #include "mlir/IR/Dominance.h"
52 #include "mlir/IR/Iterators.h"
53 #include "mlir/IR/Operation.h"
54 #include "mlir/IR/TypeUtilities.h"
57 #include "llvm/ADT/DenseSet.h"
58 #include "llvm/ADT/SetVector.h"
59 #include "llvm/Support/DebugLog.h"
60 
62 
63 // Run mlir-opt with `-debug-only="one-shot-analysis"` for detailed debug
64 // output.
65 #define DEBUG_TYPE "one-shot-analysis"
66 
67 using namespace mlir;
68 using namespace mlir::bufferization;
69 
70 static bool isaTensor(Type t) { return isa<TensorType>(t); }
71 
72 //===----------------------------------------------------------------------===//
73 // Bufferization-specific attribute manipulation.
74 // These are for testing and debugging only. Bufferization information is stored
75 // in OneShotBufferizationState. When run with `testAnalysisOnly`, the IR is
76 // annotated with the results of the analysis, so that they can be checked in
77 // tests.
78 //===----------------------------------------------------------------------===//
79 
80 /// Attribute marker to specify op operands that bufferize in-place.
81 constexpr StringLiteral kInPlaceOperandsAttrName = "__inplace_operands_attr__";
82 
83 constexpr StringLiteral kOpResultAliasSetAttrName =
84  "__opresult_alias_set_attr__";
85 
86 constexpr StringLiteral kBbArgAliasSetAttrName = "__bbarg_alias_set_attr__";
87 
88 /// Mark whether OpOperand will be bufferized inplace.
89 static void setInPlaceOpOperand(OpOperand &opOperand, bool inPlace) {
90  Operation *op = opOperand.getOwner();
91  SmallVector<StringRef> inPlaceVector;
92  if (auto attr = op->getAttr(kInPlaceOperandsAttrName)) {
93  inPlaceVector = SmallVector<StringRef>(llvm::to_vector<4>(
94  cast<ArrayAttr>(attr).getAsValueRange<StringAttr>()));
95  } else {
96  inPlaceVector = SmallVector<StringRef>(op->getNumOperands(), "none");
97  for (OpOperand &opOperand : op->getOpOperands())
98  if (isa<TensorType>(opOperand.get().getType()))
99  inPlaceVector[opOperand.getOperandNumber()] = "false";
100  }
101  inPlaceVector[opOperand.getOperandNumber()] = inPlace ? "true" : "false";
103  OpBuilder(op).getStrArrayAttr(inPlaceVector));
104 }
105 
106 //===----------------------------------------------------------------------===//
107 // OneShotAnalysisState
108 //===----------------------------------------------------------------------===//
109 
113  // Set up alias sets.
114  op->walk([&](Operation *op) {
115  for (Value v : op->getResults())
116  if (isa<TensorType>(v.getType()))
118  for (Region &r : op->getRegions())
119  for (Block &b : r.getBlocks())
120  for (auto bbArg : b.getArguments())
121  if (isa<TensorType>(bbArg.getType()))
122  createAliasInfoEntry(bbArg);
123  });
124 
125  // Mark OpOperands in-place that must bufferize in-place.
126  op->walk([&](BufferizableOpInterface bufferizableOp) {
127  if (!options.isOpAllowed(bufferizableOp))
128  return WalkResult::skip();
129  for (OpOperand &opOperand : bufferizableOp->getOpOperands())
130  if (isa<TensorType>(opOperand.get().getType()))
131  if (bufferizableOp.mustBufferizeInPlace(opOperand, *this))
132  bufferizeInPlace(opOperand);
133  return WalkResult::advance();
134  });
135 }
136 
138  Value v, function_ref<void(Value)> fun) const {
139  auto leaderIt = equivalentInfo.findLeader(v);
140  for (auto mit = leaderIt, meit = equivalentInfo.member_end(); mit != meit;
141  ++mit) {
142  fun(*mit);
143  }
144 }
145 
147  function_ref<void(Value)> fun) const {
148  auto leaderIt = aliasInfo.findLeader(v);
149  for (auto mit = leaderIt, meit = aliasInfo.member_end(); mit != meit; ++mit) {
150  fun(*mit);
151  }
152 }
153 
155  Value v2) const {
156  return equivalentInfo.isEquivalent(v1, v2);
157 }
158 
160  Value v2) const {
161  return aliasInfo.isEquivalent(v1, v2);
162 }
163 
165  if (inplaceBufferized.contains(&operand))
166  return;
167  inplaceBufferized.insert(&operand);
168  for (AliasingValue alias : getAliasingValues(operand))
169  aliasInfo.unionSets(alias.value, operand.get());
170  ++statNumTensorInPlace;
171 }
172 
174  assert(!inplaceBufferized.contains(&operand) &&
175  "OpOperand was already decided to bufferize inplace");
176  ++statNumTensorOutOfPlace;
177 }
178 
180  aliasInfo.insert(v);
181  equivalentInfo.insert(v);
182 }
183 
185  op->walk([&](Operation *op) {
186  // Skip unknown ops.
187  auto bufferizableOp = getOptions().dynCastBufferizableOp(op);
188  if (!bufferizableOp)
189  return WalkResult::skip();
190 
191  // Check all tensor OpResults.
192  for (OpResult opResult : op->getOpResults()) {
193  if (!isa<TensorType>(opResult.getType()))
194  continue;
195 
196  // If there is no preceding definition, the tensor contents are
197  // undefined.
198  if (opResult.getUses().empty())
199  continue;
200  // It does not really matter which use to take to search about
201  // the value's definitions.
202  OpOperand *opOperand = &(*opResult.getUses().begin());
203  if (findDefinitionsCached(opOperand).empty())
204  for (OpOperand &use : opResult.getUses())
205  undefinedTensorUses.insert(&use);
206  }
207 
208  return WalkResult::advance();
209  });
210 }
211 
213  return undefinedTensorUses.contains(opOperand);
214 }
215 
217  return inplaceBufferized.contains(&opOperand);
218 }
219 
221  bool isWritten = false;
222  applyOnAliases(value, [&](Value val) {
223  for (OpOperand &use : val.getUses())
224  if (isInPlace(use) && bufferizesToMemoryWrite(use))
225  isWritten = true;
226  });
227  return isWritten;
228 }
229 
231  // TODO: Out-of-place bufferized value could be considered writable.
232  // Query BufferizableOpInterface to see if the BlockArgument is writable.
233  if (auto bufferizableOp =
234  getOptions().dynCastBufferizableOp(getOwnerOfValue(value)))
235  return bufferizableOp.isWritable(value, *this);
236 
237  // Not a bufferizable op: The conservative answer is "not writable".
238  return false;
239 }
240 
242  aliasInfo.unionSets(v1, v2);
243 }
244 
246  equivalentInfo.unionSets(v1, v2);
247 }
248 
250 
251 //===----------------------------------------------------------------------===//
252 // Bufferization-specific alias analysis.
253 //===----------------------------------------------------------------------===//
254 
255 /// Return true if opOperand has been decided to bufferize in-place.
256 static bool isInplaceMemoryWrite(OpOperand &opOperand,
257  const OneShotAnalysisState &state) {
258  // OpOperands that do not bufferize to a memory write do not write in-place.
259  if (!state.bufferizesToMemoryWrite(opOperand))
260  return false;
261  // Check current bufferization decisions.
262  return state.isInPlace(opOperand);
263 }
264 
265 /// Return true if `a` happens before `b`, i.e., `a` or one of its ancestors
266 /// properly dominates `b` and `b` is not inside `a`.
267 static bool happensBefore(Operation *a, Operation *b,
268  const DominanceInfo &domInfo) {
269  do {
270  // TODO: Instead of isProperAncestor + properlyDominates, we should use
271  // properlyDominatesImpl(a, b, /*enclosingOpOk=*/false)
272  if (a->isProperAncestor(b))
273  return false;
274  if (domInfo.properlyDominates(a, b))
275  return true;
276  } while ((a = a->getParentOp()));
277  return false;
278 }
279 
280 /// Return `true` if op dominance can be used to rule out a read-after-write
281 /// conflicts based on the ordering of ops. Returns `false` if op dominance
282 /// cannot be used to due region-based loops.
283 ///
284 /// Generalized op dominance can often be used to rule out potential conflicts
285 /// due to "read happens before write". E.g., the following IR is not a RaW
286 /// conflict because the read happens *before* the write.
287 ///
288 /// Example 1:
289 /// %0 = ... : tensor<?xf32> // DEF
290 /// "reading_op"(%0) : tensor<?xf32> // READ
291 /// %1 = "writing_op"(%0) : tensor<?xf32> -> tensor<?xf32> // WRITE
292 ///
293 /// This is no longer true inside loops (or repetitive regions). In such cases,
294 /// there may not be a meaningful `happensBefore` relationship because ops
295 /// could be executed multiple times. E.g.:
296 ///
297 /// Example 2:
298 /// %0 = ... : tensor<?xf32> // DEF
299 /// scf.for ... {
300 /// "reading_op"(%0) : tensor<?xf32> // READ
301 /// %1 = "writing_op"(%0) : tensor<?xf32> -> tensor<?xf32> // WRITE
302 /// ...
303 /// }
304 ///
305 /// In the above example, reading_op happens before writing_op according to
306 /// op dominance. However, both ops may happen multiple times; in
307 /// particular, the second execution of reading_op happens after the first
308 /// execution of writing_op. This is problematic because the tensor %0 they
309 /// operate on (i.e., the "definition") is defined outside of the loop.
310 ///
311 /// On a high-level, there is a potential RaW in a program if there exists a
312 /// possible program execution such that there is a sequence of DEF, followed
313 /// by WRITE, followed by READ. Each additional DEF resets the sequence.
314 ///
315 /// E.g.:
316 /// No conflict: DEF, WRITE, DEF, READ
317 /// Potential conflict: DEF, READ, WRITE, READ, WRITE
318 ///
319 /// Example 1 has no conflict: DEF, READ, WRITE
320 /// Example 2 has a potential conflict: DEF, (READ, WRITE)*
321 //
322 /// Example 3:
323 /// scf.for ... {
324 /// %0 = ... : tensor<?xf32>
325 /// "reading_op"(%0) : tensor<?xf32>
326 /// %1 = "writing_op"(%0) : tensor<?xf32> -> tensor<?xf32>
327 /// ...
328 /// }
329 /// This has no conflict: (DEF, READ, WRITE)*
330 ///
331 /// Example 4:
332 /// %0 = ... : tensor<?xf32>
333 /// scf.for ... {
334 /// scf.for ... { "reading_op"(%0) }
335 /// %1 = "writing_op"(%0)
336 /// }
337 /// This has a potential conflict: DEF, ((READ)*, WRITE)*
338 ///
339 /// Example 5:
340 /// %0 = ... : tensor<?xf32>
341 /// scf.for ... { %1 = "writing_op"(%0) }
342 /// scf.for ... { "reading_op"(%0) }
343 /// This has a potential conflict: DEF, WRITE*, READ*
344 ///
345 /// The following rules are used to rule out RaW conflicts via ordering of ops:
346 ///
347 /// 1. If the closest enclosing repetitive region of DEF is a proper ancestor of
348 /// a repetitive region that enclosing both READ and WRITE, we cannot rule
349 /// out RaW conflict due to the ordering of ops.
350 /// 2. Otherwise: There are no loops that interfere with our analysis; for
351 /// analysis purposes, we can assume that there are no loops/repetitive
352 /// regions. I.e., we can rule out a RaW conflict if READ happensBefore WRITE
353 /// or WRITE happensBefore DEF. (Checked in `hasReadAfterWriteInterference`.)
354 ///
356  const SetVector<Value> &definitions,
357  AnalysisState &state) {
358  const BufferizationOptions &options = state.getOptions();
359  for (Value def : definitions) {
360  Region *rRead =
361  state.getEnclosingRepetitiveRegion(uRead->getOwner(), options);
362  Region *rDef = state.getEnclosingRepetitiveRegion(def, options);
363 
364  // READ and DEF are in the same repetitive region. `happensBefore` can be
365  // used to rule out RaW conflicts due to op ordering.
366  if (rRead == rDef)
367  continue;
368 
369  // Find the enclosing repetitive region of READ that is closest to DEF but
370  // not the repetitive region of DEF itself.
371  while (true) {
372  Region *nextRegion = getNextEnclosingRepetitiveRegion(rRead, options);
373  if (nextRegion == rDef)
374  break;
375  assert(nextRegion && "expected to find another repetitive region");
376  rRead = nextRegion;
377  }
378 
379  // We cannot use op dominance if WRITE is inside the same repetitive region.
380  if (rRead->getParentOp()->isAncestor(uWrite->getOwner()))
381  return false;
382  }
383 
384  return true;
385 }
386 
387 /// Return `true` if op dominance can be used to rule out a read-after-write
388 /// conflicts based on the ordering of ops. Returns `false` if op dominance
389 /// cannot be used to due block-based loops within a region.
390 ///
391 /// Refer to the `canUseOpDominanceDueToRegions` documentation for details on
392 /// how op domiance is used during RaW conflict detection.
393 ///
394 /// On a high-level, there is a potential RaW in a program if there exists a
395 /// possible program execution such that there is a sequence of DEF, followed
396 /// by WRITE, followed by READ. Each additional DEF resets the sequence.
397 ///
398 /// Op dominance cannot be used if there is a path from block(READ) to
399 /// block(WRITE) and a path from block(WRITE) to block(READ). block(DEF) should
400 /// not appear on that path.
402  const SetVector<Value> &definitions,
403  AnalysisState &state) {
404  // Fast path: If READ and WRITE are in different regions, their block cannot
405  // be reachable just via unstructured control flow. (Loops due to regions are
406  // covered by `canUseOpDominanceDueToRegions`.)
407  if (uRead->getOwner()->getParentRegion() !=
408  uWrite->getOwner()->getParentRegion())
409  return true;
410 
411  Block *readBlock = uRead->getOwner()->getBlock();
412  Block *writeBlock = uWrite->getOwner()->getBlock();
413  for (Value def : definitions) {
414  Block *defBlock = def.getParentBlock();
415  if (readBlock->isReachable(writeBlock, {defBlock}) &&
416  writeBlock->isReachable(readBlock, {defBlock}))
417  return false;
418  }
419 
420  return true;
421 }
422 
423 static bool canUseOpDominance(OpOperand *uRead, OpOperand *uWrite,
424  const SetVector<Value> &definitions,
425  AnalysisState &state) {
426  return canUseOpDominanceDueToRegions(uRead, uWrite, definitions, state) &&
427  canUseOpDominanceDueToBlocks(uRead, uWrite, definitions, state);
428 }
429 
430 /// Annotate IR with details about the detected RaW conflict.
431 static void annotateConflict(OpOperand *uRead, OpOperand *uConflictingWrite,
432  Value definition) {
433  static uint64_t counter = 0;
434  Operation *readingOp = uRead->getOwner();
435  Operation *conflictingWritingOp = uConflictingWrite->getOwner();
436 
437  OpBuilder b(conflictingWritingOp->getContext());
438  std::string id = "C_" + std::to_string(counter++);
439 
440  std::string conflictingWriteAttr =
441  id +
442  "[CONFL-WRITE: " + std::to_string(uConflictingWrite->getOperandNumber()) +
443  "]";
444  conflictingWritingOp->setAttr(conflictingWriteAttr, b.getUnitAttr());
445 
446  std::string readAttr =
447  id + "[READ: " + std::to_string(uRead->getOperandNumber()) + "]";
448  readingOp->setAttr(readAttr, b.getUnitAttr());
449 
450  if (auto opResult = dyn_cast<OpResult>(definition)) {
451  std::string defAttr =
452  id + "[DEF: result " + std::to_string(opResult.getResultNumber()) + "]";
453  opResult.getDefiningOp()->setAttr(defAttr, b.getUnitAttr());
454  } else {
455  auto bbArg = cast<BlockArgument>(definition);
456  std::string defAttr =
457  id + "[DEF: bbArg " + std::to_string(bbArg.getArgNumber()) + "]";
458  bbArg.getOwner()->getParentOp()->setAttr(defAttr, b.getUnitAttr());
459  }
460 }
461 
462 /// Return 'true' if a tensor that is equivalent to `other` can be found in the
463 /// reverse use-def chain of `start`. Note: If an OpOperand bufferizes out of
464 /// place along that use-def chain, the two tensors may not materialize as
465 /// equivalent buffers (but separate allocations).
466 ///
467 /// Note: This function also requires that the two tensors have equivalent
468 /// indexing. I.e., the tensor types do not change along the use-def chain,
469 /// apart from static <-> dynamic dim casts.
471  OpOperand *start,
472  Value other) {
474  config.followEquivalentOnly = true;
475  config.alwaysIncludeLeaves = false;
476  config.followSameTypeOrCastsOnly = true;
477  return !state
478  .findValueInReverseUseDefChain(
479  start, [&](Value v) { return v == other; }, config)
480  .empty();
481 }
482 
483 /// Return "true" if the given operand's value is originating from a subset
484 /// that is equivalent to the subset that `subsetOp` inserts into.
485 static bool matchesInsertDestination(const AnalysisState &state,
486  OpOperand *opOperand,
487  SubsetInsertionOpInterface subsetOp) {
488  auto matchingSubset = [&](Value val) {
489  if (auto opResult = dyn_cast<OpResult>(val))
490  if (subsetOp.isEquivalentSubset(opResult, [&](Value v1, Value v2) {
491  return state.areEquivalentBufferizedValues(v1, v2);
492  }))
493  return true;
494  return false;
495  };
496  // There may be multiple leaves at which the reverse SSA use-def chain lookup
497  // terminates. All of them must be equivalent subsets.
498  SetVector<Value> backwardSlice =
499  state.findValueInReverseUseDefChain(opOperand, matchingSubset);
500  return static_cast<bool>(llvm::all_of(backwardSlice, matchingSubset));
501 }
502 
503 /// Return "true" if the given "read" and potentially conflicting "write" are
504 /// not conflicting due to their subset relationship. The comments in this
505 /// function are expressed in terms of tensor.extract_slice/tensor.insert_slice
506 /// pairs, but apply to any subset ops that implement the
507 /// `SubsetInsertionOpInterface`.
509  OpOperand *uConflictingWrite,
510  const AnalysisState &state) {
511  Operation *readingOp = uRead->getOwner();
512  Operation *conflictingWritingOp = uConflictingWrite->getOwner();
513 
514  // Special rules for matching ExtractSliceOp/InsertSliceOp pairs. If
515  // uRead is an InsertSliceOp...
516  if (auto subsetOp = dyn_cast<SubsetInsertionOpInterface>(readingOp)) {
517  // As an example, consider the following IR.
518  //
519  // %0 = tensor.extract_slice %t[%a, %b][%c, %d][1, 1] {inplace = [true] }
520  // %1 = linalg.fill %cst, %0 {inplace= [true] }
521  // %2 = tensor.insert_slice %1 into %t[%a, %b][%c, %d][1, 1]
522  // {inplace= [true] }
523 
524  if (uRead == &subsetOp.getDestinationOperand() &&
525  matchesInsertDestination(state, uConflictingWrite, subsetOp))
526  // Case 1: The main insight is that InsertSliceOp reads only part of
527  // the destination tensor. The overwritten area is not read. If
528  // uConflictingWrite writes into exactly the memory location that is
529  // being read by uRead, this is not a conflict.
530  //
531  // In the above example:
532  // uRead = OpOperand 1 (%t) of tensor.insert_slice
533  // uConflictingWrite = OpOperand 1 (%0) of linalg.fill
534  //
535  // The read of %t does not conflict with the write of the FillOp
536  // (same aliases!) because the area that the FillOp operates on is
537  // exactly the one that is *not* read via %t.
538  return true;
539 
540  if (uRead == &subsetOp.getSourceOperand() &&
541  uConflictingWrite == &subsetOp.getDestinationOperand() &&
542  matchesInsertDestination(state, uRead, subsetOp))
543  // Case 2: The read of the source tensor and the write to the dest
544  // tensor via an InsertSliceOp is not a conflict if the read is
545  // reading exactly that part of an equivalent tensor that the
546  // InsertSliceOp is writing.
547  //
548  // In the above example:
549  // uRead = OpOperand 0 (%1) of tensor.insert_slice
550  // uConflictingWrite = OpOperand 1 (%t) of tensor.insert_slice
551  return true;
552  }
553 
554  // If uConflictingWrite is an InsertSliceOp...
555  if (auto subsetOp =
556  dyn_cast<SubsetInsertionOpInterface>(conflictingWritingOp))
557  // As an example, consider the following IR.
558  //
559  // %0 = tensor.extract_slice %t[%a, %b][%c, %d][1, 1] {inplace = [true] }
560  // %1 = linalg.fill %cst, %0 {inplace= [true] }
561  // %2 = tensor.insert_slice %1 into %t[%a, %b][%c, %d][1, 1]
562  // {inplace= [true] }
563  // %3 = vector.transfer_read %1, %cst
564  //
565  // In the above example:
566  // uRead = OpOperand 0 (%1) of vector.transfer_read
567  // uConflictingWrite = OpOperand 1 (%t) of tensor.insert_slice
568  // definition = %1
569  //
570  // This is not a conflict because the InsertSliceOp overwrites the
571  // memory segment of %1 with the exact same data. (Effectively, there
572  // is no memory write here.)
573  if (uConflictingWrite == &subsetOp.getDestinationOperand() &&
574  state.areEquivalentBufferizedValues(
575  uRead->get(), subsetOp.getSourceOperand().get()) &&
576  matchesInsertDestination(state, &subsetOp.getSourceOperand(), subsetOp))
577  return true;
578 
579  return false;
580 }
581 
582 /// Given sets of uses and writes, return true if there is a RaW conflict under
583 /// the assumption that all given reads/writes alias the same buffer and that
584 /// all given writes bufferize inplace.
585 ///
586 /// A conflict is: According to SSA use-def chains, a read R is supposed to read
587 /// the result of a definition W1. But because of bufferization decisions, R
588 /// actually reads another definition W2.
589 static bool
591  const DenseSet<OpOperand *> &usesWrite,
592  const DominanceInfo &domInfo,
593  OneShotAnalysisState &state) {
594  const BufferizationOptions &options = state.getOptions();
595 
596  // Before going through the main RaW analysis, find cases where a buffer must
597  // be privatized due to parallelism. If the result of a write is never read,
598  // privatization is not necessary (and large parts of the IR are likely dead).
599  if (options.checkParallelRegions && !usesRead.empty()) {
600  for (OpOperand *uConflictingWrite : usesWrite) {
601  // Find the allocation point or last write (definition) of the buffer.
602  // Note: In contrast to `findDefinitions`, this also returns results of
603  // ops that do not bufferize to memory write when no other definition
604  // could be found. E.g., "bufferization.alloc_tensor" would be included,
605  // even though that op just bufferizes to an allocation but does define
606  // the contents of the buffer.
607  SetVector<Value> definitionsOrLeaves =
608  state.findValueInReverseUseDefChain(uConflictingWrite, [&](Value v) {
609  return state.bufferizesToMemoryWrite(v);
610  });
611  assert(!definitionsOrLeaves.empty() &&
612  "expected at least one definition or leaf");
613 
614  // The writing op must bufferize out-of-place if the definition is in a
615  // different parallel region than this write.
616  for (Value def : definitionsOrLeaves) {
617  if (getParallelRegion(def.getParentRegion(), options) !=
618  getParallelRegion(uConflictingWrite->getOwner()->getParentRegion(),
619  options)) {
620  LDBG() << "\n- bufferizes out-of-place due to parallel region:\n"
621  << " unConflictingWrite = operand "
622  << uConflictingWrite->getOperandNumber() << " of "
623  << *uConflictingWrite->getOwner();
624  return true;
625  }
626  }
627  }
628  }
629 
630  for (OpOperand *uRead : usesRead) {
631  Operation *readingOp = uRead->getOwner();
632  LDBG() << "\n- check conflict:\n"
633  << " uRead = operand " << uRead->getOperandNumber() << " of "
634  << *readingOp;
635 
636  // Find the definition of uRead by following the SSA use-def chain.
637  // E.g.:
638  //
639  // %0 = "writing_op"(%t) : tensor<?x32> -> tensor<?xf32>
640  // %1 = "aliasing_op"(%0) : tensor<?x32> -> tensor<?xf32>
641  // %2 = "reading_op"(%1) : : tensor<?x32> -> not_a_tensor_type
642  //
643  // In the above example, if uRead is the OpOperand of reading_op, the
644  // definition is %0. Note that operations that create an alias but do not
645  // bufferize to a memory write (such as ExtractSliceOp) are skipped.
646  const SetVector<Value> &definitions = state.findDefinitionsCached(uRead);
647  if (definitions.empty()) {
648  // Fast path: No conflict if there are no definitions.
649  LDBG() << " no conflict: read value has no definitions";
650  continue;
651  }
652 
653  // Look for conflicting memory writes. Potential conflicts are writes to an
654  // alias that have been decided to bufferize inplace.
655  for (OpOperand *uConflictingWrite : usesWrite) {
656  LDBG() << " unConflictingWrite = operand "
657  << uConflictingWrite->getOperandNumber() << " of "
658  << *uConflictingWrite->getOwner();
659 
660  // Check if op dominance can be used to rule out read-after-write
661  // conflicts.
662  bool useDominance =
663  canUseOpDominance(uRead, uConflictingWrite, definitions, state);
664  LDBG() << "\n- useDominance = " << useDominance;
665 
666  // Throughout this loop, check for multiple requirements that have to be
667  // met for uConflictingWrite to be an actual conflict.
668  Operation *conflictingWritingOp = uConflictingWrite->getOwner();
669 
670  // Inside of repetitive regions, ops may be executed multiple times and op
671  // dominance cannot be used to rule out conflicts.
672  if (useDominance) {
673  // No conflict if the readingOp dominates conflictingWritingOp, i.e.,
674  // the write is not visible when reading.
675  //
676  // Note: If ops are executed multiple times (e.g., because they are
677  // inside a loop), there may be no meaningful `happensBefore`
678  // relationship.
679  if (happensBefore(readingOp, conflictingWritingOp, domInfo)) {
680  LDBG() << " no conflict: read happens before write";
681  continue;
682  }
683 
684  // No conflict if the reading use equals the use of the conflicting
685  // write. A use cannot conflict with itself.
686  //
687  // Note: Just being the same op is not enough. It has to be the same
688  // use.
689  // Note: If the op is executed multiple times (e.g., because it is
690  // inside a loop), it may be conflicting with itself.
691  if (uConflictingWrite == uRead) {
692  LDBG() << " no conflict: read and write are same use";
693  continue;
694  }
695 
696  // Ops are not conflicting if they are in mutually exclusive regions.
697  //
698  // Note: If ops are executed multiple times (e.g., because they are
699  // inside a loop), mutually exclusive regions may be executed
700  // multiple times.
701  if (state.insideMutuallyExclusiveRegions(readingOp,
702  conflictingWritingOp)) {
703  LDBG() << " no conflict: read and write are in "
704  "mutually exclusive regions";
705  continue;
706  }
707 
708  // Two equivalent operands of the same op are not conflicting if the op
709  // bufferizes to element-wise access. I.e., all loads at a position
710  // happen before all stores to the same position.
711  if (conflictingWritingOp == readingOp) {
712  if (auto bufferizableOp = options.dynCastBufferizableOp(readingOp)) {
713  if (bufferizableOp.bufferizesToElementwiseAccess(
714  state, {uRead, uConflictingWrite})) {
716  state, uRead, uConflictingWrite->get()) ||
718  state, uConflictingWrite, uRead->get())) {
719  LDBG() << " no conflict: op bufferizes to element-wise access";
720  continue;
721  }
722  }
723  }
724  }
725  }
726 
727  // No conflict if the operands are non-conflicting subsets.
728  if (areNonConflictingSubsets(uRead, uConflictingWrite, state)) {
729  LDBG() << " no conflict: non-conflicting subsets";
730  continue;
731  }
732 
733  // No conflict if the op interface says so.
734  if (auto bufferizableOp = options.dynCastBufferizableOp(readingOp)) {
735  if (bufferizableOp.isNotConflicting(uRead, uConflictingWrite, state)) {
736  LDBG() << " no conflict: op interace of reading op says 'no'";
737  continue;
738  }
739  }
740 
741  if (conflictingWritingOp != readingOp) {
742  if (auto bufferizableOp =
743  options.dynCastBufferizableOp(conflictingWritingOp)) {
744  if (bufferizableOp.isNotConflicting(uRead, uConflictingWrite,
745  state)) {
746  LDBG() << " no conflict: op interace of writing op says 'no'";
747  continue;
748  }
749  }
750  }
751 
752  // Check all possible definitions.
753  for (Value definition : definitions) {
754  LDBG() << " * definition = " << definition;
755 
756  // No conflict if the conflicting write happens before the definition.
757  if (Operation *defOp = definition.getDefiningOp()) {
758  if (happensBefore(conflictingWritingOp, defOp, domInfo)) {
759  // conflictingWritingOp happens before defOp. No conflict.
760  LDBG() << " no conflict: write happens before definition";
761  continue;
762  }
763  // No conflict if conflictingWritingOp is contained in defOp.
764  if (defOp->isProperAncestor(conflictingWritingOp)) {
765  LDBG() << " no conflict: write is contained in definition";
766  continue;
767  }
768  } else {
769  auto bbArg = cast<BlockArgument>(definition);
770  Block *block = bbArg.getOwner();
771  if (!block->findAncestorOpInBlock(*conflictingWritingOp)) {
772  LDBG() << " no conflict: definition is bbArg "
773  "and write happens outside of block";
774  // conflictingWritingOp happens outside of the block. No
775  // conflict.
776  continue;
777  }
778  }
779 
780  // No conflict if the conflicting write and the definition are the same
781  // use.
782  AliasingValueList aliases = state.getAliasingValues(*uConflictingWrite);
783  if (aliases.getNumAliases() == 1 &&
784  aliases.getAliases()[0].value == definition) {
785  LDBG() << " no conflict: definition and write are same";
786  continue;
787  }
788 
789  // All requirements are met. Conflict found!
790 
791  if (options.printConflicts)
792  annotateConflict(uRead, uConflictingWrite, definition);
793  LDBG() << " => RaW CONFLICT FOUND";
794  return true;
795  }
796  }
797  }
798 
799  return false;
800 }
801 
802 // Helper function to iterate on aliases of `root` and capture the writes.
804  const OneShotAnalysisState &state) {
805  state.applyOnAliases(root, [&](Value alias) {
806  for (auto &use : alias.getUses())
807  // Inplace write to a value that aliases root.
808  if (isInplaceMemoryWrite(use, state))
809  res.insert(&use);
810  });
811 }
812 
813 // Helper function to iterate on aliases of `root` and capture the reads.
815  const OneShotAnalysisState &state) {
816  state.applyOnAliases(root, [&](Value alias) {
817  for (auto &use : alias.getUses()) {
818  // Read of a value that aliases root.
819  if (state.bufferizesToMemoryRead(use)) {
820  res.insert(&use);
821  continue;
822  }
823 
824  // Read of a dependent value in the SSA use-def chain. E.g.:
825  //
826  // %0 = ...
827  // %1 = tensor.extract_slice %0 {not_analyzed_yet}
828  // "read"(%1)
829  //
830  // In the above example, getAliasingReads(%0) includes the first OpOperand
831  // of the tensor.extract_slice op. The extract_slice itself does not read
832  // but its aliasing result is eventually fed into an op that does.
833  //
834  // Note: This is considered a "read" only if the use does not bufferize to
835  // a memory write. (We already ruled out memory reads. In case of a memory
836  // write, the buffer would be entirely overwritten; in the above example
837  // there would then be no flow of data from the extract_slice operand to
838  // its result's uses.)
839  if (!state.bufferizesToMemoryWrite(use)) {
840  AliasingValueList aliases = state.getAliasingValues(use);
841  if (llvm::any_of(aliases, [&](AliasingValue a) {
842  return state.isValueRead(a.value);
843  }))
844  res.insert(&use);
845  }
846  }
847  });
848 }
849 
850 /// Return true if bufferizing `operand` inplace would create a conflict. A read
851 /// R and a write W of the same alias set is a conflict if inplace bufferization
852 /// of W changes the value read by R to a value different from the one that
853 /// would be expected by tracing back R's origin through SSA use-def chains.
854 /// A conflict can only be introduced by a new alias and/or an inplace
855 /// bufferization decision.
856 ///
857 /// Example:
858 /// %0 = tensor.extract_slice %t[...][...][1, 1] {inplace?}
859 /// %1 = vector.transfer_write %v1, %t {inplace} : vector<5xf32>, tensor<?xf32>
860 /// %e = tensor.extract_slice %1
861 /// %2 = vector.transfer_write %v2, %0 {inplace} : vector<6xf32>, tensor<?xf32>
862 /// %3 = vector.transfer_read %e, %cst : tensor<?xf32>, vector<7xf32>
863 ///
864 /// In the above example, the two TransferWriteOps have already been decided to
865 /// bufferize inplace. Bufferizing the ExtractSliceOp inplace would create a
866 /// conflict because:
867 /// * According to SSA use-def chains, we expect to read the result of %1.
868 /// * However, adding an alias {%0, %t} would mean that the second
869 /// TransferWriteOp overwrites the result of the first one. Therefore, the
870 /// TransferReadOp would no longer be reading the result of %1.
871 ///
872 /// If `checkConsistencyOnly` is true, this function checks if there is a
873 /// read-after-write conflict without bufferizing `operand` inplace. This would
874 /// indicate a problem with the current inplace bufferization decisions.
875 ///
876 /// Note: If `checkConsistencyOnly`, this function may be called with a null
877 /// OpResult. In that case, only the consistency of bufferization decisions
878 /// involving aliases of the given OpOperand are checked.
880  OpOperand &operand, const DominanceInfo &domInfo,
881  OneShotAnalysisState &state, bool checkConsistencyOnly = false) {
882  // Collect reads and writes of all aliases of OpOperand and OpResult.
883  DenseSet<OpOperand *> usesRead, usesWrite;
884  getAliasingReads(usesRead, operand.get(), state);
885  getAliasingInplaceWrites(usesWrite, operand.get(), state);
886  for (AliasingValue alias : state.getAliasingValues(operand)) {
887  getAliasingReads(usesRead, alias.value, state);
888  getAliasingInplaceWrites(usesWrite, alias.value, state);
889  }
890  if (!checkConsistencyOnly && state.bufferizesToMemoryWrite(operand))
891  usesWrite.insert(&operand);
892 
893  return hasReadAfterWriteInterference(usesRead, usesWrite, domInfo, state);
894 }
895 
896 /// Annotate IR with details about the detected non-writability conflict.
897 static void annotateNonWritableTensor(Value value) {
898  static int64_t counter = 0;
899  OpBuilder b(value.getContext());
900  std::string id = "W_" + std::to_string(counter++);
901  if (auto opResult = dyn_cast<OpResult>(value)) {
902  std::string attr = id + "[NOT-WRITABLE: result " +
903  std::to_string(opResult.getResultNumber()) + "]";
904  opResult.getDefiningOp()->setAttr(attr, b.getUnitAttr());
905  } else {
906  auto bbArg = cast<BlockArgument>(value);
907  std::string attr = id + "[NOT-WRITABLE: bbArg " +
908  std::to_string(bbArg.getArgNumber()) + "]";
909  bbArg.getOwner()->getParentOp()->setAttr(attr, b.getUnitAttr());
910  }
911 }
912 
913 /// Return true if bufferizing `operand` inplace would create a write to a
914 /// non-writable buffer.
915 static bool
917  OneShotAnalysisState &state,
918  bool checkConsistencyOnly = false) {
919  bool foundWrite =
920  !checkConsistencyOnly && state.bufferizesToMemoryWrite(operand);
921 
922  if (!foundWrite) {
923  // Collect writes of all aliases of OpOperand and OpResult.
924  DenseSet<OpOperand *> usesWrite;
925  getAliasingInplaceWrites(usesWrite, operand.get(), state);
926  for (AliasingValue alias : state.getAliasingValues(operand))
927  getAliasingInplaceWrites(usesWrite, alias.value, state);
928  foundWrite = !usesWrite.empty();
929  }
930 
931  if (!foundWrite)
932  return false;
933 
934  // Look for a read-only tensor among all aliases.
935  bool foundReadOnly = false;
936  auto checkReadOnly = [&](Value v) {
937  if (!state.isWritable(v)) {
938  foundReadOnly = true;
939  if (state.getOptions().printConflicts)
941  }
942  };
943  state.applyOnAliases(operand.get(), checkReadOnly);
944  for (AliasingValue alias : state.getAliasingValues(operand))
945  state.applyOnAliases(alias.value, checkReadOnly);
946  if (foundReadOnly) {
947  LDBG() << "=> NOT WRITABLE";
948  return true;
949  }
950 
951  return false;
952 }
953 
954 //===----------------------------------------------------------------------===//
955 // Bufferization analyses.
956 //===----------------------------------------------------------------------===//
957 
958 // Find the values that define the contents of the given operand's value.
960 OneShotAnalysisState::findDefinitionsCached(OpOperand *opOperand) {
961  Value value = opOperand->get();
962  if (!cachedDefinitions.count(value))
963  cachedDefinitions[value] = findDefinitions(opOperand);
964  return cachedDefinitions[value];
965 }
966 
969  cachedDefinitions.clear();
970 }
971 
972 /// Determine if `operand` can be bufferized in-place.
973 static LogicalResult
975  const DominanceInfo &domInfo) {
976  LDBG() << "//===-------------------------------------------===//\n"
977  << "Analyzing operand #" << operand.getOperandNumber() << " of "
978  << *operand.getOwner();
979 
980  bool foundInterference =
981  wouldCreateWriteToNonWritableBuffer(operand, state) ||
982  wouldCreateReadAfterWriteInterference(operand, domInfo, state);
983 
984  if (foundInterference)
985  state.bufferizeOutOfPlace(operand);
986  else
987  state.bufferizeInPlace(operand);
988 
989  LDBG() << "//===-------------------------------------------===//";
990  return success();
991 }
992 
993 LogicalResult
995  const DominanceInfo &domInfo) {
996  for (OpOperand &opOperand : op->getOpOperands())
997  if (isa<TensorType>(opOperand.get().getType()))
998  if (failed(bufferizableInPlaceAnalysisImpl(opOperand, *this, domInfo)))
999  return failure();
1000  return success();
1001 }
1002 
1003 /// Analyze equivalence of tied OpResult/OpOperand pairs of the given ops.
1005  OneShotAnalysisState &state) {
1006  for (Operation *op : ops) {
1007  if (auto bufferizableOp = state.getOptions().dynCastBufferizableOp(op)) {
1008  for (OpResult opResult : op->getOpResults()) {
1009  if (!isa<TensorType>(opResult.getType()))
1010  continue;
1011  AliasingOpOperandList aliases = state.getAliasingOpOperands(opResult);
1012  if (aliases.getNumAliases() == 0)
1013  // Nothing to do if there are no aliasing OpOperands.
1014  continue;
1015 
1016  Value firstOperand = aliases.begin()->opOperand->get();
1017  bool allEquivalent = true;
1018  for (AliasingOpOperand alias : aliases) {
1019  bool isEquiv = alias.relation == BufferRelation::Equivalent;
1020  bool isInPlace = state.isInPlace(*alias.opOperand);
1021  Value operand = alias.opOperand->get();
1022  if (isEquiv && isInPlace && alias.isDefinite) {
1023  // Found a definite, equivalent alias. Merge equivalence sets.
1024  // There can only be one definite alias, so we can stop here.
1025  state.unionEquivalenceClasses(opResult, operand);
1026  allEquivalent = false;
1027  break;
1028  }
1029  if (!isEquiv || !isInPlace)
1030  allEquivalent = false;
1031  if (!state.areEquivalentBufferizedValues(operand, firstOperand))
1032  allEquivalent = false;
1033  }
1034 
1035  // If all "maybe" aliases are equivalent and the OpResult is not a new
1036  // allocation, it is a definite, equivalent alias. E.g.:
1037  //
1038  // aliasingOpOperands(%r) = {(%t0, EQUIV, MAYBE), (%t1, EQUIV, MAYBE)}
1039  // aliasingValues(%t0) = {(%r, EQUIV, MAYBE)}
1040  // aliasingValues(%t1) = {(%r, EQUIV, MAYBE)}
1041  // %r = arith.select %c, %t0, %t1 : tensor<?xf32>
1042  //
1043  // If %t0 and %t1 are equivalent, it is safe to union the equivalence
1044  // classes of %r, %t0 and %t1.
1045  if (allEquivalent && !bufferizableOp.bufferizesToAllocation(opResult))
1046  state.unionEquivalenceClasses(opResult, firstOperand);
1047  }
1048  }
1049  }
1050 }
1051 
1052 /// Analyze equivalence of tied OpResult/OpOperand pairs of all ops contained
1053 /// in `op`.
1055  // Traverse ops in PostOrder: Nested ops first, then enclosing ops.
1057  op->walk<WalkOrder::PostOrder>([&](Operation *op) {
1058  // No tensors => no buffers.
1059  if (none_of(op->getResultTypes(), isaTensor))
1060  return;
1061  ops.push_back(op);
1062  });
1063 
1064  equivalenceAnalysis(ops, state);
1065 }
1066 
1067 /// "Bottom-up from terminators" heuristic.
1070  const OneShotAnalysisState &state) {
1071  SetVector<Operation *> traversedOps;
1072 
1073  // Find region terminators.
1074  op->walk<WalkOrder::PostOrder>([&](RegionBranchTerminatorOpInterface term) {
1075  if (!traversedOps.insert(term))
1076  return;
1077  // Follow the reverse SSA use-def chain from each yielded value as long as
1078  // we stay within the same region.
1079  SmallVector<OpResult> worklist;
1080  for (Value v : term->getOperands()) {
1081  if (!isa<TensorType>(v.getType()))
1082  continue;
1083  auto opResult = dyn_cast<OpResult>(v);
1084  if (!opResult)
1085  continue;
1086  worklist.push_back(opResult);
1087  }
1088  while (!worklist.empty()) {
1089  OpResult opResult = worklist.pop_back_val();
1090  Operation *defOp = opResult.getDefiningOp();
1091  if (!traversedOps.insert(defOp))
1092  continue;
1093  if (!term->getParentRegion()->findAncestorOpInRegion(*defOp))
1094  continue;
1095  AliasingOpOperandList aliases = state.getAliasingOpOperands(opResult);
1096  for (auto alias : aliases) {
1097  Value v = alias.opOperand->get();
1098  if (!isa<TensorType>(v.getType()))
1099  continue;
1100  auto opResult = dyn_cast<OpResult>(v);
1101  if (!opResult)
1102  continue;
1103  worklist.push_back(opResult);
1104  }
1105  }
1106  });
1107 
1108  // Analyze traversed ops, then all remaining ops.
1109  SmallVector<Operation *> result(traversedOps.begin(), traversedOps.end());
1111  if (!traversedOps.contains(op) && hasTensorSemantics(op))
1112  result.push_back(op);
1113  });
1114  return result;
1115 }
1116 
1118  const DominanceInfo &domInfo) {
1121 
1122  SmallVector<Operation *> orderedOps;
1123  if (heuristic ==
1125  orderedOps = bottomUpFromTerminatorsHeuristic(op, *this);
1126  } else {
1127  op->walk([&](Operation *op) {
1128  // No tensors => no buffers.
1129  if (!hasTensorSemantics(op))
1130  return;
1131  orderedOps.push_back(op);
1132  });
1133  switch (heuristic) {
1135  // Default: Walk ops in reverse for better interference analysis.
1136  std::reverse(orderedOps.begin(), orderedOps.end());
1137  break;
1138  }
1140  // Ops are already sorted top-down in `orderedOps`.
1141  break;
1142  }
1144  assert(getOptions().analysisFuzzerSeed &&
1145  "expected that fuzzer seed it set");
1146  // This is a fuzzer. For testing purposes only. Randomize the order in
1147  // which operations are analyzed. The bufferization quality is likely
1148  // worse, but we want to make sure that no assertions are triggered
1149  // anywhere.
1150  std::mt19937 g(getOptions().analysisFuzzerSeed);
1151  llvm::shuffle(orderedOps.begin(), orderedOps.end(), g);
1152  break;
1153  }
1154  default: {
1155  llvm_unreachable("unsupported heuristic");
1156  }
1157  }
1158  }
1159 
1160  // Analyze ops in the computed order.
1161  for (Operation *op : orderedOps)
1162  if (failed(analyzeSingleOp(op, domInfo)))
1163  return failure();
1164 
1165  equivalenceAnalysis(op, *this);
1166  return success();
1167 }
1168 
1169 /// Perform various checks on the input IR to see if it contains IR constructs
1170 /// that are unsupported by One-Shot Bufferize.
1171 static LogicalResult
1173  OneShotAnalysisState &state) {
1174  const BufferizationOptions &options = state.getOptions();
1175 
1176  // Note: This walk cannot be combined with the one below because interface
1177  // methods of invalid/unsupported ops may be called during the second walk.
1178  // (On ops different from `op`.)
1179  WalkResult walkResult = op->walk([&](BufferizableOpInterface op) {
1180  // Skip ops that are not in the filter.
1181  if (!options.isOpAllowed(op.getOperation()))
1182  return WalkResult::advance();
1183 
1184  // Check for unsupported unstructured control flow.
1185  if (!op.supportsUnstructuredControlFlow()) {
1186  for (Region &r : op->getRegions()) {
1187  if (r.getBlocks().size() > 1) {
1188  op->emitOpError("op or BufferizableOpInterface implementation does "
1189  "not support unstructured control flow, but at least "
1190  "one region has multiple blocks");
1191  return WalkResult::interrupt();
1192  }
1193  }
1194  }
1195 
1196  return WalkResult::advance();
1197  });
1198  if (walkResult.wasInterrupted())
1199  return failure();
1200 
1201  walkResult = op->walk([&](BufferizableOpInterface op) {
1202  // Skip ops that are not in the filter.
1203  if (!options.isOpAllowed(op.getOperation()))
1204  return WalkResult::advance();
1205 
1206  // Input IR may not contain any ToTensorOps without the "restrict"
1207  // attribute. Such tensors may alias any other tensor, which is currently
1208  // not handled in the analysis.
1209  if (auto toTensorOp = dyn_cast<ToTensorOp>(op.getOperation())) {
1210  if (!toTensorOp.getRestrict() && !toTensorOp->getUses().empty()) {
1211  op->emitOpError("to_tensor ops without `restrict` are not supported by "
1212  "One-Shot Analysis");
1213  return WalkResult::interrupt();
1214  }
1215  }
1216 
1217  for (OpOperand &opOperand : op->getOpOperands()) {
1218  if (isa<TensorType>(opOperand.get().getType())) {
1220  opOperand, domInfo, state,
1221  /*checkConsistencyOnly=*/true)) {
1222  // This error can happen if certain "mustBufferizeInPlace" interface
1223  // methods are implemented incorrectly, such that the IR already has
1224  // a RaW conflict before making any bufferization decisions. It can
1225  // also happen if the bufferization.materialize_in_destination is used
1226  // in such a way that a RaW conflict is not avoidable.
1227  op->emitOpError("not bufferizable under the given constraints: "
1228  "cannot avoid RaW conflict");
1229  return WalkResult::interrupt();
1230  }
1231 
1232  if (state.isInPlace(opOperand) &&
1234  opOperand, state, /*checkConsistencyOnly=*/true)) {
1235  op->emitOpError("not bufferizable under the given constraints: would "
1236  "write to read-only buffer");
1237  return WalkResult::interrupt();
1238  }
1239  }
1240  }
1241 
1242  return WalkResult::advance();
1243  });
1244 
1245  return success(!walkResult.wasInterrupted());
1246 }
1247 
1248 /// Annotate the IR with the result of the analysis. For testing/debugging only.
1249 static void
1251  const OneShotAnalysisState &state) {
1252  // Add __inplace_operands_attr__.
1253  op->walk([&](Operation *op) {
1254  for (OpOperand &opOperand : op->getOpOperands())
1255  if (isa<TensorType>(opOperand.get().getType()))
1256  setInPlaceOpOperand(opOperand, state.isInPlace(opOperand));
1257  });
1258 }
1259 
1261  const OneShotAnalysisState &state) {
1262  AsmState asmState(op);
1263  Builder b(op->getContext());
1264  // Helper function to build an array attribute of aliasing SSA value strings.
1265  auto buildAliasesArray = [&](Value v) {
1266  SmallVector<Attribute> aliases;
1267  state.applyOnAliases(v, [&](Value alias) {
1268  std::string buffer;
1269  llvm::raw_string_ostream stream(buffer);
1270  alias.printAsOperand(stream, asmState);
1271  aliases.push_back(b.getStringAttr(buffer));
1272  });
1273  return b.getArrayAttr(aliases);
1274  };
1275 
1276  op->walk([&](Operation *op) {
1277  // Build alias set array for every OpResult.
1278  SmallVector<Attribute> opResultAliasSets;
1279  for (OpResult opResult : op->getOpResults()) {
1280  if (llvm::isa<TensorType>(opResult.getType())) {
1281  opResultAliasSets.push_back(buildAliasesArray(opResult));
1282  }
1283  }
1284  if (!opResultAliasSets.empty())
1285  op->setAttr(kOpResultAliasSetAttrName, b.getArrayAttr(opResultAliasSets));
1286 
1287  // Build alias set array for every BlockArgument.
1288  SmallVector<Attribute> regionAliasSets;
1289  bool hasTensorBbArg = false;
1290  for (Region &r : op->getRegions()) {
1291  SmallVector<Attribute> blockAliasSets;
1292  for (Block &block : r.getBlocks()) {
1293  SmallVector<Attribute> bbArgAliasSets;
1294  for (BlockArgument bbArg : block.getArguments()) {
1295  if (llvm::isa<TensorType>(bbArg.getType())) {
1296  bbArgAliasSets.push_back(buildAliasesArray(bbArg));
1297  hasTensorBbArg = true;
1298  }
1299  }
1300  blockAliasSets.push_back(b.getArrayAttr(bbArgAliasSets));
1301  }
1302  regionAliasSets.push_back(b.getArrayAttr(blockAliasSets));
1303  }
1304  if (hasTensorBbArg)
1305  op->setAttr(kBbArgAliasSetAttrName, b.getArrayAttr(regionAliasSets));
1306  });
1307 }
1308 
1310  OneShotAnalysisState &state,
1311  BufferizationStatistics *statistics) {
1312  DominanceInfo domInfo(op);
1313  const OneShotBufferizationOptions &options = state.getOptions();
1314 
1315  if (failed(checkPreBufferizationAssumptions(op, domInfo, state)))
1316  return failure();
1317 
1318  // If the analysis fails, just return.
1319  if (failed(state.analyzeOp(op, domInfo)))
1320  return failure();
1321 
1322  if (statistics) {
1323  statistics->numTensorInPlace = state.getStatNumTensorInPlace();
1324  statistics->numTensorOutOfPlace = state.getStatNumTensorOutOfPlace();
1325  }
1326 
1327  bool failedAnalysis = false;
1328 
1329  // Gather some extra analysis data.
1330  state.gatherUndefinedTensorUses(op);
1331 
1332  // Analysis verification: After setting up alias/equivalence sets, each op
1333  // can check for expected invariants/limitations and fail the analysis if
1334  // necessary.
1335  op->walk([&](Operation *op) {
1336  if (BufferizableOpInterface bufferizableOp =
1337  options.dynCastBufferizableOp(op))
1338  failedAnalysis |= failed(bufferizableOp.verifyAnalysis(state));
1339  });
1340 
1341  // Annotate operations if we only want to report the analysis.
1342  if (options.testAnalysisOnly)
1344  if (options.dumpAliasSets)
1345  annotateOpsWithAliasSets(op, state);
1346 
1347  return success(!failedAnalysis);
1348 }
1349 
1352  BufferizationState &state, BufferizationStatistics *statistics) {
1353  // copy-before-write deactivates the analysis. It cannot be used together with
1354  // test-analysis-only.
1355  assert(!(options.copyBeforeWrite && options.testAnalysisOnly) &&
1356  "invalid combination of bufferization flags");
1357 
1358  if (options.copyBeforeWrite) {
1359  // Copy buffer before each write. No analysis is needed.
1360  } else {
1361  // Run One-Shot Analysis and insert buffer copies (on the tensor level)
1362  // only where needed. This is the default and much more efficient than
1363  // copy-before-write.
1364  if (failed(insertTensorCopies(op, options, state, statistics)))
1365  return failure();
1366 
1367  // If test-analysis-only is set, the IR was annotated with RaW conflict
1368  // markers (attributes) during One-Shot Analysis.
1369  if (options.testAnalysisOnly)
1370  return success();
1371  }
1372 
1373  // Bufferize the op and its nested ops. If options.copyBeforeWrite is set,
1374  // a new buffer copy is allocated every time a buffer is written to.
1375  return bufferizeOp(op, options, state, statistics);
1376 }
static bool hasReadAfterWriteInterference(const DenseSet< OpOperand * > &usesRead, const DenseSet< OpOperand * > &usesWrite, const DominanceInfo &domInfo, OneShotAnalysisState &state)
Given sets of uses and writes, return true if there is a RaW conflict under the assumption that all g...
static void getAliasingReads(DenseSet< OpOperand * > &res, Value root, const OneShotAnalysisState &state)
static void equivalenceAnalysis(SmallVector< Operation * > &ops, OneShotAnalysisState &state)
Analyze equivalence of tied OpResult/OpOperand pairs of the given ops.
static void setInPlaceOpOperand(OpOperand &opOperand, bool inPlace)
Mark whether OpOperand will be bufferized inplace.
static SmallVector< Operation * > bottomUpFromTerminatorsHeuristic(Operation *op, const OneShotAnalysisState &state)
"Bottom-up from terminators" heuristic.
constexpr StringLiteral kInPlaceOperandsAttrName
Attribute marker to specify op operands that bufferize in-place.
static bool isaTensor(Type t)
static void annotateNonWritableTensor(Value value)
Annotate IR with details about the detected non-writability conflict.
static bool canUseOpDominanceDueToRegions(OpOperand *uRead, OpOperand *uWrite, const SetVector< Value > &definitions, AnalysisState &state)
Return true if op dominance can be used to rule out a read-after-write conflicts based on the orderin...
static LogicalResult bufferizableInPlaceAnalysisImpl(OpOperand &operand, OneShotAnalysisState &state, const DominanceInfo &domInfo)
Determine if operand can be bufferized in-place.
constexpr StringLiteral kOpResultAliasSetAttrName
static bool happensBefore(Operation *a, Operation *b, const DominanceInfo &domInfo)
Return true if a happens before b, i.e., a or one of its ancestors properly dominates b and b is not ...
static bool canUseOpDominance(OpOperand *uRead, OpOperand *uWrite, const SetVector< Value > &definitions, AnalysisState &state)
static bool matchesInsertDestination(const AnalysisState &state, OpOperand *opOperand, SubsetInsertionOpInterface subsetOp)
Return "true" if the given operand's value is originating from a subset that is equivalent to the sub...
static bool wouldCreateWriteToNonWritableBuffer(OpOperand &operand, OneShotAnalysisState &state, bool checkConsistencyOnly=false)
Return true if bufferizing operand inplace would create a write to a non-writable buffer.
static void annotateOpsWithAliasSets(Operation *op, const OneShotAnalysisState &state)
static LogicalResult checkPreBufferizationAssumptions(Operation *op, const DominanceInfo &domInfo, OneShotAnalysisState &state)
Perform various checks on the input IR to see if it contains IR constructs that are unsupported by On...
static void annotateOpsWithBufferizationMarkers(Operation *op, const OneShotAnalysisState &state)
Annotate the IR with the result of the analysis. For testing/debugging only.
static bool wouldCreateReadAfterWriteInterference(OpOperand &operand, const DominanceInfo &domInfo, OneShotAnalysisState &state, bool checkConsistencyOnly=false)
Return true if bufferizing operand inplace would create a conflict.
constexpr StringLiteral kBbArgAliasSetAttrName
static bool canUseOpDominanceDueToBlocks(OpOperand *uRead, OpOperand *uWrite, const SetVector< Value > &definitions, AnalysisState &state)
Return true if op dominance can be used to rule out a read-after-write conflicts based on the orderin...
static void getAliasingInplaceWrites(DenseSet< OpOperand * > &res, Value root, const OneShotAnalysisState &state)
static bool areNonConflictingSubsets(OpOperand *uRead, OpOperand *uConflictingWrite, const AnalysisState &state)
Return "true" if the given "read" and potentially conflicting "write" are not conflicting due to thei...
static void annotateConflict(OpOperand *uRead, OpOperand *uConflictingWrite, Value definition)
Annotate IR with details about the detected RaW conflict.
static bool hasEquivalentValueInReverseUseDefChain(AnalysisState &state, OpOperand *start, Value other)
Return 'true' if a tensor that is equivalent to other can be found in the reverse use-def chain of st...
static bool isInplaceMemoryWrite(OpOperand &opOperand, const OneShotAnalysisState &state)
Return true if opOperand has been decided to bufferize in-place.
static llvm::ManagedStatic< PassManagerOptions > options
#define MLIR_DEFINE_EXPLICIT_TYPE_ID(CLASS_NAME)
Definition: TypeID.h:323
Base class for generic analysis states.
This class provides management for the lifetime of the state used when printing the IR.
Definition: AsmState.h:542
This class represents an argument of a Block.
Definition: Value.h:309
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:74
bool isReachable(Block *other, SmallPtrSet< Block *, 16 > &&except={})
Return "true" if there is a path from this block to the given block (according to the successors rela...
Definition: Block.cpp:363
This class is a general helper class for creating context-global objects like types,...
Definition: Builders.h:51
UnitAttr getUnitAttr()
Definition: Builders.cpp:97
StringAttr getStringAttr(const Twine &bytes)
Definition: Builders.cpp:261
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
Definition: Builders.cpp:265
A class for computing basic dominance information.
Definition: Dominance.h:140
bool properlyDominates(Operation *a, Operation *b, bool enclosingOpOk=true) const
Return true if operation A properly dominates operation B, i.e.
Definition: Dominance.cpp:323
IRValueT get() const
Return the current value being used by this operand.
Definition: UseDefLists.h:160
This class helps build Operations.
Definition: Builders.h:207
This class represents an operand of an operation.
Definition: Value.h:257
unsigned getOperandNumber()
Return which operand this is in the OpOperand list of the Operation.
Definition: Value.cpp:226
This is a value defined by a result of an operation.
Definition: Value.h:447
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
Attribute getAttr(StringAttr name)
Return the specified attribute if present, null otherwise.
Definition: Operation.h:534
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:797
MLIRContext * getContext()
Return the context this operation is associated with.
Definition: Operation.h:216
unsigned getNumOperands()
Definition: Operation.h:346
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition: Operation.h:234
Block * getBlock()
Returns the operation block that contains this operation.
Definition: Operation.h:213
void setAttr(StringAttr name, Attribute value)
If the an attribute exists with the specified name, change it to the new value.
Definition: Operation.h:582
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
Definition: Operation.h:677
MutableArrayRef< OpOperand > getOpOperands()
Definition: Operation.h:383
result_type_range getResultTypes()
Definition: Operation.h:428
bool isAncestor(Operation *other)
Return true if this operation is an ancestor of the other operation.
Definition: Operation.h:263
result_range getOpResults()
Definition: Operation.h:420
Region * getParentRegion()
Returns the region to which the instruction belongs.
Definition: Operation.h:230
result_range getResults()
Definition: Operation.h:415
bool isProperAncestor(Operation *other)
Return true if this operation is a proper ancestor of the other operation.
Definition: Operation.cpp:218
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition: Region.h:26
Operation * getParentOp()
Return the parent operation this region is attached to.
Definition: Region.h:200
This class provides an efficient unique identifier for a specific C++ type.
Definition: TypeID.h:107
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:74
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:96
MLIRContext * getContext() const
Utility to get the associated MLIRContext that this value is defined in.
Definition: Value.h:108
Type getType() const
Return the type of this value.
Definition: Value.h:105
use_range getUses() const
Returns a range of all uses, which is useful for iterating over all uses.
Definition: Value.h:188
void printAsOperand(raw_ostream &os, AsmState &state) const
Print this value as if it were an operand.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition: Value.cpp:18
A utility result that is used to signal how to proceed with an ongoing walk:
Definition: WalkResult.h:29
static WalkResult skip()
Definition: WalkResult.h:48
static WalkResult advance()
Definition: WalkResult.h:47
static WalkResult interrupt()
Definition: WalkResult.h:46
AnalysisState provides a variety of helper functions for dealing with tensor values.
AliasingValueList getAliasingValues(OpOperand &opOperand) const
Determine which Value will alias with opOperand if the op is bufferized in place.
bool bufferizesToMemoryWrite(OpOperand &opOperand) const
Return true if opOperand bufferizes to a memory write.
SetVector< Value > findDefinitions(OpOperand *opOperand) const
Find the values that may define the contents of the given value at runtime.
BufferizationState provides information about the state of the IR during the bufferization process.
virtual ~Extension()
Base virtual destructor.
State for analysis-enabled bufferization.
void bufferizeOutOfPlace(OpOperand &operand)
Mark the given OpOperand as out-of-place.
bool isWritable(Value value) const
Return true if the buffer of the given tensor value is writable.
const SetVector< Value > & findDefinitionsCached(OpOperand *opOperand)
Find the definitions of the given operand's value or retrieve them from the cache.
bool isInPlace(OpOperand &opOperand) const override
Return true if the given OpResult has been decided to bufferize inplace.
LogicalResult analyzeOp(Operation *op, const DominanceInfo &domInfo)
Analyze the given op and its nested ops.
bool isValueWritten(Value value) const
Return true if the buffer of the given tensor value is written to.
const OneShotBufferizationOptions & getOptions() const
Return a reference to the BufferizationOptions.
void unionEquivalenceClasses(Value v1, Value v2)
Union the equivalence classes of v1 and v2.
void gatherUndefinedTensorUses(Operation *op)
Find all tensor values in the given operation that have undefined contents and store them in undefine...
void resetCache() override
Reset cached data structures.
LogicalResult analyzeSingleOp(Operation *op, const DominanceInfo &domInfo)
Analyze a single op (without nested ops).
void applyOnEquivalenceClass(Value v, function_ref< void(Value)> fun) const
Apply fun to all the members of the equivalence class of v.
bool hasUndefinedContents(OpOperand *opOperand) const override
Return true if the given tensor has undefined contents.
void bufferizeInPlace(OpOperand &operand)
Mark the given OpOperand as in-place and merge the results' and operand's aliasing sets.
void applyOnAliases(Value v, function_ref< void(Value)> fun) const
Apply fun to all aliases of v.
bool areEquivalentBufferizedValues(Value v1, Value v2) const override
Return true if v1 and v2 bufferize to equivalent buffers.
OneShotAnalysisState(Operation *op, const OneShotBufferizationOptions &options)
bool areAliasingBufferizedValues(Value v1, Value v2) const override
Return true if v1 and v2 may bufferize to aliasing buffers.
void unionAliasSets(Value v1, Value v2)
Union the alias sets of v1 and v2.
void createAliasInfoEntry(Value v)
Add a new entry for v in the aliasInfo and equivalentInfo.
Operation * getOwner() const
Return the owner of this operand.
Definition: UseDefLists.h:38
LogicalResult bufferizeOp(Operation *op, const BufferizationOptions &options, BufferizationState &bufferizationState, BufferizationStatistics *statistics=nullptr)
Bufferize op and its nested ops that implement BufferizableOpInterface.
Definition: Bufferize.cpp:277
LogicalResult analyzeOp(Operation *op, OneShotAnalysisState &state, BufferizationStatistics *statistics=nullptr)
Analyze op and its nested ops.
Operation * getOwnerOfValue(Value value)
Return the owner of the given value.
LogicalResult insertTensorCopies(Operation *op, const OneShotBufferizationOptions &options, const BufferizationState &bufferizationState, BufferizationStatistics *statistics=nullptr)
Resolve RaW and other conflicts by inserting bufferization.alloc_tensor ops.
LogicalResult runOneShotBufferize(Operation *op, const OneShotBufferizationOptions &options, BufferizationState &state, BufferizationStatistics *statistics=nullptr)
Run One-Shot Bufferize on the given op: Analysis + Bufferization.
Region * getParallelRegion(Region *region, const BufferizationOptions &options)
If region is a parallel region, return region.
Region * getNextEnclosingRepetitiveRegion(Region *region, const BufferizationOptions &options)
Assuming that the given region is repetitive, find the next enclosing repetitive region.
bool hasTensorSemantics(Operation *op)
Return "true" if the given op has tensor semantics and should be bufferized.
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition: Remarks.h:491
Include the generated interface declarations.
const FrozenRewritePatternSet GreedyRewriteConfig config
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
This iterator enumerates elements in "reverse" order.
Definition: Iterators.h:29
Options for BufferizableOpInterface-based bufferization.
BufferizableOpInterface dynCastBufferizableOp(Operation *op) const
Try to cast the given op to BufferizableOpInterface if the op is allow listed.
bool isOpAllowed(Operation *op) const
Return true if the given op should be bufferized.
Bufferization statistics for debugging.
Definition: Bufferize.h:35
Options for analysis-enabled bufferization.
AnalysisHeuristic analysisHeuristic
The heuristic controls the order in which ops are traversed during the analysis.
Traversal parameters for findValueInReverseUseDefChain.