MLIR  20.0.0git
Builders.h
Go to the documentation of this file.
1 //===- Builders.h - Helpers for constructing MLIR Classes -------*- C++ -*-===//
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 #ifndef MLIR_IR_BUILDERS_H
10 #define MLIR_IR_BUILDERS_H
11 
12 #include "mlir/IR/OpDefinition.h"
13 #include "llvm/Support/Compiler.h"
14 #include <optional>
15 
16 namespace mlir {
17 
18 class AffineExpr;
19 class IRMapping;
20 class UnknownLoc;
21 class FileLineColLoc;
22 class Type;
23 class PrimitiveType;
24 class IntegerType;
25 class FloatType;
26 class FunctionType;
27 class IndexType;
28 class MemRefType;
29 class VectorType;
30 class RankedTensorType;
31 class UnrankedTensorType;
32 class TupleType;
33 class NoneType;
34 class BoolAttr;
35 class IntegerAttr;
36 class FloatAttr;
37 class StringAttr;
38 class TypeAttr;
39 class ArrayAttr;
40 class SymbolRefAttr;
41 class ElementsAttr;
42 class DenseElementsAttr;
43 class DenseIntElementsAttr;
44 class AffineMapAttr;
45 class AffineMap;
46 class UnitAttr;
47 
48 /// This class is a general helper class for creating context-global objects
49 /// like types, attributes, and affine expressions.
50 class Builder {
51 public:
53  explicit Builder(Operation *op) : Builder(op->getContext()) {}
54 
55  MLIRContext *getContext() const { return context; }
56 
57  // Locations.
60  Attribute metadata = Attribute());
61 
62  // Types.
81 
82  IndexType getIndexType();
83 
84  IntegerType getI1Type();
85  IntegerType getI2Type();
86  IntegerType getI4Type();
87  IntegerType getI8Type();
88  IntegerType getI16Type();
89  IntegerType getI32Type();
90  IntegerType getI64Type();
91  IntegerType getIntegerType(unsigned width);
92  IntegerType getIntegerType(unsigned width, bool isSigned);
93  FunctionType getFunctionType(TypeRange inputs, TypeRange results);
94  TupleType getTupleType(TypeRange elementTypes);
95  NoneType getNoneType();
96 
97  /// Get or construct an instance of the type `Ty` with provided arguments.
98  template <typename Ty, typename... Args>
99  Ty getType(Args &&...args) {
100  return Ty::get(context, std::forward<Args>(args)...);
101  }
102 
103  /// Get or construct an instance of the attribute `Attr` with provided
104  /// arguments.
105  template <typename Attr, typename... Args>
106  Attr getAttr(Args &&...args) {
107  return Attr::get(context, std::forward<Args>(args)...);
108  }
109 
110  // Attributes.
111  NamedAttribute getNamedAttr(StringRef name, Attribute val);
112 
113  UnitAttr getUnitAttr();
114  BoolAttr getBoolAttr(bool value);
115  DictionaryAttr getDictionaryAttr(ArrayRef<NamedAttribute> value);
116  IntegerAttr getIntegerAttr(Type type, int64_t value);
117  IntegerAttr getIntegerAttr(Type type, const APInt &value);
118  FloatAttr getFloatAttr(Type type, double value);
119  FloatAttr getFloatAttr(Type type, const APFloat &value);
120  StringAttr getStringAttr(const Twine &bytes);
121  ArrayAttr getArrayAttr(ArrayRef<Attribute> value);
122 
123  // Returns a 0-valued attribute of the given `type`. This function only
124  // supports boolean, integer, and 16-/32-/64-bit float types, and vector or
125  // ranked tensor of them. Returns null attribute otherwise.
126  TypedAttr getZeroAttr(Type type);
127  // Returns a 1-valued attribute of the given `type`.
128  // Type constraints are the same as `getZeroAttr`.
129  TypedAttr getOneAttr(Type type);
130 
131  // Convenience methods for fixed types.
132  FloatAttr getF16FloatAttr(float value);
133  FloatAttr getF32FloatAttr(float value);
134  FloatAttr getF64FloatAttr(double value);
135 
136  IntegerAttr getI8IntegerAttr(int8_t value);
137  IntegerAttr getI16IntegerAttr(int16_t value);
138  IntegerAttr getI32IntegerAttr(int32_t value);
139  IntegerAttr getI64IntegerAttr(int64_t value);
140  IntegerAttr getIndexAttr(int64_t value);
141 
142  /// Signed and unsigned integer attribute getters.
143  IntegerAttr getSI32IntegerAttr(int32_t value);
144  IntegerAttr getUI32IntegerAttr(uint32_t value);
145 
146  /// Vector-typed DenseIntElementsAttr getters. `values` must not be empty.
151 
154 
155  /// Tensor-typed DenseIntElementsAttr getters. `values` can be empty.
156  /// These are generally preferable for representing general lists of integers
157  /// as attributes.
161 
162  /// Tensor-typed DenseArrayAttr getters.
170 
171  ArrayAttr getAffineMapArrayAttr(ArrayRef<AffineMap> values);
172  ArrayAttr getBoolArrayAttr(ArrayRef<bool> values);
173  ArrayAttr getI32ArrayAttr(ArrayRef<int32_t> values);
174  ArrayAttr getI64ArrayAttr(ArrayRef<int64_t> values);
175  ArrayAttr getIndexArrayAttr(ArrayRef<int64_t> values);
176  ArrayAttr getF32ArrayAttr(ArrayRef<float> values);
177  ArrayAttr getF64ArrayAttr(ArrayRef<double> values);
178  ArrayAttr getStrArrayAttr(ArrayRef<StringRef> values);
179  ArrayAttr getTypeArrayAttr(TypeRange values);
180 
181  // Affine expressions and affine maps.
182  AffineExpr getAffineDimExpr(unsigned position);
183  AffineExpr getAffineSymbolExpr(unsigned position);
184  AffineExpr getAffineConstantExpr(int64_t constant);
185 
186  // Special cases of affine maps and integer sets
187  /// Returns a zero result affine map with no dimensions or symbols: () -> ().
189  /// Returns a single constant result affine map with 0 dimensions and 0
190  /// symbols. One constant result: () -> (val).
191  AffineMap getConstantAffineMap(int64_t val);
192  // One dimension id identity map: (i) -> (i).
194  // Multi-dimensional identity map: (d0, d1, d2) -> (d0, d1, d2).
195  AffineMap getMultiDimIdentityMap(unsigned rank);
196  // One symbol identity map: ()[s] -> (s).
198 
199  /// Returns a map that shifts its (single) input dimension by 'shift'.
200  /// (d0) -> (d0 + shift)
201  AffineMap getSingleDimShiftAffineMap(int64_t shift);
202 
203  /// Returns an affine map that is a translation (shift) of all result
204  /// expressions in 'map' by 'shift'.
205  /// Eg: input: (d0, d1)[s0] -> (d0, d1 + s0), shift = 2
206  /// returns: (d0, d1)[s0] -> (d0 + 2, d1 + s0 + 2)
207  AffineMap getShiftedAffineMap(AffineMap map, int64_t shift);
208 
209 protected:
211 };
212 
213 /// This class helps build Operations. Operations that are created are
214 /// automatically inserted at an insertion point. The builder is copyable.
215 class OpBuilder : public Builder {
216 public:
217  class InsertPoint;
218  struct Listener;
219 
220  /// Create a builder with the given context.
221  explicit OpBuilder(MLIRContext *ctx, Listener *listener = nullptr)
222  : Builder(ctx), listener(listener) {}
223 
224  /// Create a builder and set the insertion point to the start of the region.
225  explicit OpBuilder(Region *region, Listener *listener = nullptr)
226  : OpBuilder(region->getContext(), listener) {
227  if (!region->empty())
228  setInsertionPointToStart(&region->front());
229  }
230  explicit OpBuilder(Region &region, Listener *listener = nullptr)
231  : OpBuilder(&region, listener) {}
232 
233  /// Create a builder and set insertion point to the given operation, which
234  /// will cause subsequent insertions to go right before it.
235  explicit OpBuilder(Operation *op, Listener *listener = nullptr)
236  : OpBuilder(op->getContext(), listener) {
237  setInsertionPoint(op);
238  }
239 
240  OpBuilder(Block *block, Block::iterator insertPoint,
241  Listener *listener = nullptr)
242  : OpBuilder(block->getParent()->getContext(), listener) {
243  setInsertionPoint(block, insertPoint);
244  }
245 
246  /// Create a builder and set the insertion point to before the first operation
247  /// in the block but still inside the block.
248  static OpBuilder atBlockBegin(Block *block, Listener *listener = nullptr) {
249  return OpBuilder(block, block->begin(), listener);
250  }
251 
252  /// Create a builder and set the insertion point to after the last operation
253  /// in the block but still inside the block.
254  static OpBuilder atBlockEnd(Block *block, Listener *listener = nullptr) {
255  return OpBuilder(block, block->end(), listener);
256  }
257 
258  /// Create a builder and set the insertion point to before the block
259  /// terminator.
261  Listener *listener = nullptr) {
262  auto *terminator = block->getTerminator();
263  assert(terminator != nullptr && "the block has no terminator");
264  return OpBuilder(block, Block::iterator(terminator), listener);
265  }
266 
267  //===--------------------------------------------------------------------===//
268  // Listeners
269  //===--------------------------------------------------------------------===//
270 
271  /// Base class for listeners.
272  struct ListenerBase {
273  /// The kind of listener.
274  enum class Kind {
275  /// OpBuilder::Listener or user-derived class.
276  OpBuilderListener = 0,
277 
278  /// RewriterBase::Listener or user-derived class.
280  };
281 
282  Kind getKind() const { return kind; }
283 
284  protected:
285  ListenerBase(Kind kind) : kind(kind) {}
286 
287  private:
288  const Kind kind;
289  };
290 
291  /// This class represents a listener that may be used to hook into various
292  /// actions within an OpBuilder.
293  struct Listener : public ListenerBase {
294  Listener() : ListenerBase(ListenerBase::Kind::OpBuilderListener) {}
295 
296  virtual ~Listener() = default;
297 
298  /// Notify the listener that the specified operation was inserted.
299  ///
300  /// * If the operation was moved, then `previous` is the previous location
301  /// of the op.
302  /// * If the operation was unlinked before it was inserted, then `previous`
303  /// is empty.
304  ///
305  /// Note: Creating an (unlinked) op does not trigger this notification.
306  virtual void notifyOperationInserted(Operation *op, InsertPoint previous) {}
307 
308  /// Notify the listener that the specified block was inserted.
309  ///
310  /// * If the block was moved, then `previous` and `previousIt` are the
311  /// previous location of the block.
312  /// * If the block was unlinked before it was inserted, then `previous`
313  /// is "nullptr".
314  ///
315  /// Note: Creating an (unlinked) block does not trigger this notification.
316  virtual void notifyBlockInserted(Block *block, Region *previous,
317  Region::iterator previousIt) {}
318 
319  protected:
320  Listener(Kind kind) : ListenerBase(kind) {}
321  };
322 
323  /// Sets the listener of this builder to the one provided.
324  void setListener(Listener *newListener) { listener = newListener; }
325 
326  /// Returns the current listener of this builder, or nullptr if this builder
327  /// doesn't have a listener.
328  Listener *getListener() const { return listener; }
329 
330  //===--------------------------------------------------------------------===//
331  // Insertion Point Management
332  //===--------------------------------------------------------------------===//
333 
334  /// This class represents a saved insertion point.
335  class InsertPoint {
336  public:
337  /// Creates a new insertion point which doesn't point to anything.
338  InsertPoint() = default;
339 
340  /// Creates a new insertion point at the given location.
341  InsertPoint(Block *insertBlock, Block::iterator insertPt)
342  : block(insertBlock), point(insertPt) {}
343 
344  /// Returns true if this insert point is set.
345  bool isSet() const { return (block != nullptr); }
346 
347  Block *getBlock() const { return block; }
348  Block::iterator getPoint() const { return point; }
349 
350  private:
351  Block *block = nullptr;
352  Block::iterator point;
353  };
354 
355  /// RAII guard to reset the insertion point of the builder when destroyed.
357  public:
359  : builder(&builder), ip(builder.saveInsertionPoint()) {}
360 
362  if (builder)
363  builder->restoreInsertionPoint(ip);
364  }
365 
366  InsertionGuard(const InsertionGuard &) = delete;
368 
369  /// Implement the move constructor to clear the builder field of `other`.
370  /// That way it does not restore the insertion point upon destruction as
371  /// that should be done exclusively by the just constructed InsertionGuard.
372  InsertionGuard(InsertionGuard &&other) noexcept
373  : builder(other.builder), ip(other.ip) {
374  other.builder = nullptr;
375  }
376 
378 
379  private:
380  OpBuilder *builder;
382  };
383 
384  /// Reset the insertion point to no location. Creating an operation without a
385  /// set insertion point is an error, but this can still be useful when the
386  /// current insertion point a builder refers to is being removed.
388  this->block = nullptr;
389  insertPoint = Block::iterator();
390  }
391 
392  /// Return a saved insertion point.
395  }
396 
397  /// Restore the insert point to a previously saved point.
399  if (ip.isSet())
400  setInsertionPoint(ip.getBlock(), ip.getPoint());
401  else
403  }
404 
405  /// Set the insertion point to the specified location.
406  void setInsertionPoint(Block *block, Block::iterator insertPoint) {
407  // TODO: check that insertPoint is in this rather than some other block.
408  this->block = block;
409  this->insertPoint = insertPoint;
410  }
411 
412  /// Sets the insertion point to the specified operation, which will cause
413  /// subsequent insertions to go right before it.
416  }
417 
418  /// Sets the insertion point to the node after the specified operation, which
419  /// will cause subsequent insertions to go right after it.
422  }
423 
424  /// Sets the insertion point to the node after the specified value. If value
425  /// has a defining operation, sets the insertion point to the node after such
426  /// defining operation. This will cause subsequent insertions to go right
427  /// after it. Otherwise, value is a BlockArgument. Sets the insertion point to
428  /// the start of its block.
430  if (Operation *op = val.getDefiningOp()) {
432  } else {
433  auto blockArg = llvm::cast<BlockArgument>(val);
434  setInsertionPointToStart(blockArg.getOwner());
435  }
436  }
437 
438  /// Sets the insertion point to the start of the specified block.
440  setInsertionPoint(block, block->begin());
441  }
442 
443  /// Sets the insertion point to the end of the specified block.
445  setInsertionPoint(block, block->end());
446  }
447 
448  /// Return the block the current insertion point belongs to. Note that the
449  /// insertion point is not necessarily the end of the block.
450  Block *getInsertionBlock() const { return block; }
451 
452  /// Returns the current insertion point of the builder.
453  Block::iterator getInsertionPoint() const { return insertPoint; }
454 
455  /// Returns the current block of the builder.
456  Block *getBlock() const { return block; }
457 
458  //===--------------------------------------------------------------------===//
459  // Block Creation
460  //===--------------------------------------------------------------------===//
461 
462  /// Add new block with 'argTypes' arguments and set the insertion point to the
463  /// end of it. The block is inserted at the provided insertion point of
464  /// 'parent'. `locs` contains the locations of the inserted arguments, and
465  /// should match the size of `argTypes`.
466  Block *createBlock(Region *parent, Region::iterator insertPt = {},
467  TypeRange argTypes = std::nullopt,
468  ArrayRef<Location> locs = std::nullopt);
469 
470  /// Add new block with 'argTypes' arguments and set the insertion point to the
471  /// end of it. The block is placed before 'insertBefore'. `locs` contains the
472  /// locations of the inserted arguments, and should match the size of
473  /// `argTypes`.
474  Block *createBlock(Block *insertBefore, TypeRange argTypes = std::nullopt,
475  ArrayRef<Location> locs = std::nullopt);
476 
477  //===--------------------------------------------------------------------===//
478  // Operation Creation
479  //===--------------------------------------------------------------------===//
480 
481  /// Insert the given operation at the current insertion point and return it.
482  Operation *insert(Operation *op);
483 
484  /// Creates an operation given the fields represented as an OperationState.
485  Operation *create(const OperationState &state);
486 
487  /// Creates an operation with the given fields.
488  Operation *create(Location loc, StringAttr opName, ValueRange operands,
489  TypeRange types = {},
490  ArrayRef<NamedAttribute> attributes = {},
491  BlockRange successors = {},
492  MutableArrayRef<std::unique_ptr<Region>> regions = {});
493 
494 private:
495  /// Helper for sanity checking preconditions for create* methods below.
496  template <typename OpT>
497  RegisteredOperationName getCheckRegisteredInfo(MLIRContext *ctx) {
498  std::optional<RegisteredOperationName> opName =
499  RegisteredOperationName::lookup(TypeID::get<OpT>(), ctx);
500  if (LLVM_UNLIKELY(!opName)) {
501  llvm::report_fatal_error(
502  "Building op `" + OpT::getOperationName() +
503  "` but it isn't known in this MLIRContext: the dialect may not "
504  "be loaded or this operation hasn't been added by the dialect. See "
505  "also https://mlir.llvm.org/getting_started/Faq/"
506  "#registered-loaded-dependent-whats-up-with-dialects-management");
507  }
508  return *opName;
509  }
510 
511 public:
512  /// Create an operation of specific op type at the current insertion point.
513  template <typename OpTy, typename... Args>
514  OpTy create(Location location, Args &&...args) {
515  OperationState state(location,
516  getCheckRegisteredInfo<OpTy>(location.getContext()));
517  OpTy::build(*this, state, std::forward<Args>(args)...);
518  auto *op = create(state);
519  auto result = dyn_cast<OpTy>(op);
520  assert(result && "builder didn't return the right type");
521  return result;
522  }
523 
524  /// Create an operation of specific op type at the current insertion point,
525  /// and immediately try to fold it. This functions populates 'results' with
526  /// the results of the operation.
527  template <typename OpTy, typename... Args>
529  Args &&...args) {
530  // Create the operation without using 'create' as we want to control when
531  // the listener is notified.
532  OperationState state(location,
533  getCheckRegisteredInfo<OpTy>(location.getContext()));
534  OpTy::build(*this, state, std::forward<Args>(args)...);
535  Operation *op = Operation::create(state);
536  if (block)
537  block->getOperations().insert(insertPoint, op);
538 
539  // Attempt to fold the operation.
540  if (succeeded(tryFold(op, results)) && !results.empty()) {
541  // Erase the operation, if the fold removed the need for this operation.
542  // Note: The fold already populated the results in this case.
543  op->erase();
544  return;
545  }
546 
547  ResultRange opResults = op->getResults();
548  results.assign(opResults.begin(), opResults.end());
549  if (block && listener)
550  listener->notifyOperationInserted(op, /*previous=*/{});
551  }
552 
553  /// Overload to create or fold a single result operation.
554  template <typename OpTy, typename... Args>
555  std::enable_if_t<OpTy::template hasTrait<OpTrait::OneResult>(), Value>
556  createOrFold(Location location, Args &&...args) {
557  SmallVector<Value, 1> results;
558  createOrFold<OpTy>(results, location, std::forward<Args>(args)...);
559  return results.front();
560  }
561 
562  /// Overload to create or fold a zero result operation.
563  template <typename OpTy, typename... Args>
564  std::enable_if_t<OpTy::template hasTrait<OpTrait::ZeroResults>(), OpTy>
565  createOrFold(Location location, Args &&...args) {
566  auto op = create<OpTy>(location, std::forward<Args>(args)...);
567  SmallVector<Value, 0> unused;
568  (void)tryFold(op.getOperation(), unused);
569 
570  // Folding cannot remove a zero-result operation, so for convenience we
571  // continue to return it.
572  return op;
573  }
574 
575  /// Attempts to fold the given operation and places new results within
576  /// `results`. Returns success if the operation was folded, failure otherwise.
577  /// If the fold was in-place, `results` will not be filled.
578  /// Note: This function does not erase the operation on a successful fold.
579  LogicalResult tryFold(Operation *op, SmallVectorImpl<Value> &results);
580 
581  /// Creates a deep copy of the specified operation, remapping any operands
582  /// that use values outside of the operation using the map that is provided
583  /// ( leaving them alone if no entry is present). Replaces references to
584  /// cloned sub-operations to the corresponding operation that is copied,
585  /// and adds those mappings to the map.
586  Operation *clone(Operation &op, IRMapping &mapper);
587  Operation *clone(Operation &op);
588 
589  /// Creates a deep copy of this operation but keep the operation regions
590  /// empty. Operands are remapped using `mapper` (if present), and `mapper` is
591  /// updated to contain the results.
593  return insert(op.cloneWithoutRegions(mapper));
594  }
596  return insert(op.cloneWithoutRegions());
597  }
598  template <typename OpT>
599  OpT cloneWithoutRegions(OpT op) {
600  return cast<OpT>(cloneWithoutRegions(*op.getOperation()));
601  }
602 
603  /// Clone the blocks that belong to "region" before the given position in
604  /// another region "parent". The two regions must be different. The caller is
605  /// responsible for creating or updating the operation transferring flow of
606  /// control to the region and passing it the correct block arguments.
607  void cloneRegionBefore(Region &region, Region &parent,
608  Region::iterator before, IRMapping &mapping);
609  void cloneRegionBefore(Region &region, Region &parent,
610  Region::iterator before);
611  void cloneRegionBefore(Region &region, Block *before);
612 
613 protected:
614  /// The optional listener for events of this builder.
616 
617 private:
618  /// The current block this builder is inserting into.
619  Block *block = nullptr;
620  /// The insertion point within the block that this builder is inserting
621  /// before.
622  Block::iterator insertPoint;
623 };
624 
625 } // namespace mlir
626 
627 #endif
Base type for affine expression.
Definition: AffineExpr.h:68
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition: AffineMap.h:46
Attributes are known-constant values of operations.
Definition: Attributes.h:25
Block represents an ordered list of Operations.
Definition: Block.h:33
OpListType::iterator iterator
Definition: Block.h:140
Operation * getTerminator()
Get the terminator operation of this block.
Definition: Block.cpp:246
OpListType & getOperations()
Definition: Block.h:137
iterator end()
Definition: Block.h:144
iterator begin()
Definition: Block.h:143
Special case of IntegerAttr to represent boolean integers, i.e., signless i1 integers.
This class is a general helper class for creating context-global objects like types,...
Definition: Builders.h:50
FloatType getFloat8E5M2Type()
Definition: Builders.cpp:49
IntegerAttr getIndexAttr(int64_t value)
Definition: Builders.cpp:148
AffineMap getSingleDimShiftAffineMap(int64_t shift)
Returns a map that shifts its (single) input dimension by 'shift'.
Definition: Builders.cpp:441
IntegerType getI16Type()
Definition: Builders.cpp:105
UnitAttr getUnitAttr()
Definition: Builders.cpp:138
ArrayAttr getIndexArrayAttr(ArrayRef< int64_t > values)
Definition: Builders.cpp:327
DenseF64ArrayAttr getDenseF64ArrayAttr(ArrayRef< double > values)
Definition: Builders.cpp:215
IntegerType getI2Type()
Definition: Builders.cpp:99
FloatType getF80Type()
Definition: Builders.cpp:91
FloatType getF128Type()
Definition: Builders.cpp:93
DenseI8ArrayAttr getDenseI8ArrayAttr(ArrayRef< int8_t > values)
Definition: Builders.cpp:195
FloatType getFloat8E8M0FNUType()
Definition: Builders.cpp:77
IntegerAttr getI32IntegerAttr(int32_t value)
Definition: Builders.cpp:240
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
Definition: Builders.cpp:203
DenseIntElementsAttr getBoolVectorAttr(ArrayRef< bool > values)
Vector-typed DenseIntElementsAttr getters. values must not be empty.
Definition: Builders.cpp:156
FloatType getF32Type()
Definition: Builders.cpp:87
FloatType getTF32Type()
Definition: Builders.cpp:85
TupleType getTupleType(TypeRange elementTypes)
Definition: Builders.cpp:124
IntegerAttr getIntegerAttr(Type type, int64_t value)
Definition: Builders.cpp:268
FloatAttr getF64FloatAttr(double value)
Definition: Builders.cpp:282
AffineMap getShiftedAffineMap(AffineMap map, int64_t shift)
Returns an affine map that is a translation (shift) of all result expressions in 'map' by 'shift'.
Definition: Builders.cpp:447
FloatType getFloat8E4M3B11FNUZType()
Definition: Builders.cpp:69
ArrayAttr getI32ArrayAttr(ArrayRef< int32_t > values)
Definition: Builders.cpp:316
DenseI64ArrayAttr getDenseI64ArrayAttr(ArrayRef< int64_t > values)
Definition: Builders.cpp:207
FloatAttr getF16FloatAttr(float value)
Definition: Builders.cpp:290
AffineMap getDimIdentityMap()
Definition: Builders.cpp:423
AffineMap getMultiDimIdentityMap(unsigned rank)
Definition: Builders.cpp:427
IntegerAttr getI16IntegerAttr(int16_t value)
Definition: Builders.cpp:257
DenseI16ArrayAttr getDenseI16ArrayAttr(ArrayRef< int16_t > values)
Definition: Builders.cpp:199
FloatType getFloat6E3M2FNType()
Definition: Builders.cpp:45
AffineExpr getAffineSymbolExpr(unsigned position)
Definition: Builders.cpp:408
DenseFPElementsAttr getF32VectorAttr(ArrayRef< float > values)
Definition: Builders.cpp:180
FloatAttr getFloatAttr(Type type, double value)
Definition: Builders.cpp:294
AffineExpr getAffineConstantExpr(int64_t constant)
Definition: Builders.cpp:412
DenseIntElementsAttr getI32TensorAttr(ArrayRef< int32_t > values)
Tensor-typed DenseIntElementsAttr getters.
Definition: Builders.cpp:219
FunctionType getFunctionType(TypeRange inputs, TypeRange results)
Definition: Builders.cpp:120
IntegerType getI64Type()
Definition: Builders.cpp:109
IntegerType getI32Type()
Definition: Builders.cpp:107
IntegerAttr getI64IntegerAttr(int64_t value)
Definition: Builders.cpp:152
IntegerType getIntegerType(unsigned width)
Definition: Builders.cpp:111
NoneType getNoneType()
Definition: Builders.cpp:128
DenseIntElementsAttr getI64TensorAttr(ArrayRef< int64_t > values)
Definition: Builders.cpp:226
Ty getType(Args &&...args)
Get or construct an instance of the type Ty with provided arguments.
Definition: Builders.h:99
BoolAttr getBoolAttr(bool value)
Definition: Builders.cpp:140
IntegerType getI4Type()
Definition: Builders.cpp:101
StringAttr getStringAttr(const Twine &bytes)
Definition: Builders.cpp:302
MLIRContext * context
Definition: Builders.h:210
Builder(MLIRContext *context)
Definition: Builders.h:52
AffineMap getEmptyAffineMap()
Returns a zero result affine map with no dimensions or symbols: () -> ().
Definition: Builders.cpp:416
Builder(Operation *op)
Definition: Builders.h:53
FloatType getFloat8E3M4Type()
Definition: Builders.cpp:73
IntegerAttr getSI32IntegerAttr(int32_t value)
Signed and unsigned integer attribute getters.
Definition: Builders.cpp:247
FloatType getFloat8E4M3Type()
Definition: Builders.cpp:53
TypedAttr getZeroAttr(Type type)
Definition: Builders.cpp:364
FloatType getF16Type()
Definition: Builders.cpp:83
Location getFusedLoc(ArrayRef< Location > locs, Attribute metadata=Attribute())
Definition: Builders.cpp:29
FloatType getBF16Type()
Definition: Builders.cpp:81
AffineExpr getAffineDimExpr(unsigned position)
Definition: Builders.cpp:404
DenseIntElementsAttr getIndexTensorAttr(ArrayRef< int64_t > values)
Definition: Builders.cpp:233
AffineMap getConstantAffineMap(int64_t val)
Returns a single constant result affine map with 0 dimensions and 0 symbols.
Definition: Builders.cpp:418
MLIRContext * getContext() const
Definition: Builders.h:55
ArrayAttr getTypeArrayAttr(TypeRange values)
Definition: Builders.cpp:352
DenseIntElementsAttr getI32VectorAttr(ArrayRef< int32_t > values)
Definition: Builders.cpp:162
DenseF32ArrayAttr getDenseF32ArrayAttr(ArrayRef< float > values)
Definition: Builders.cpp:211
FloatType getFloat4E2M1FNType()
Definition: Builders.cpp:37
FloatType getFloat8E4M3FNType()
Definition: Builders.cpp:57
DenseIntElementsAttr getI64VectorAttr(ArrayRef< int64_t > values)
Definition: Builders.cpp:168
AffineMap getSymbolIdentityMap()
Definition: Builders.cpp:436
ArrayAttr getF64ArrayAttr(ArrayRef< double > values)
Definition: Builders.cpp:340
IntegerType getI1Type()
Definition: Builders.cpp:97
FloatType getFloat6E2M3FNType()
Definition: Builders.cpp:41
DenseFPElementsAttr getF64VectorAttr(ArrayRef< double > values)
Definition: Builders.cpp:185
Location getUnknownLoc()
Definition: Builders.cpp:27
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
Definition: Builders.cpp:306
DenseBoolArrayAttr getDenseBoolArrayAttr(ArrayRef< bool > values)
Tensor-typed DenseArrayAttr getters.
Definition: Builders.cpp:191
FloatType getFloat8E4M3FNUZType()
Definition: Builders.cpp:65
ArrayAttr getI64ArrayAttr(ArrayRef< int64_t > values)
Definition: Builders.cpp:321
IndexType getIndexType()
Definition: Builders.cpp:95
IntegerType getI8Type()
Definition: Builders.cpp:103
FloatAttr getF32FloatAttr(float value)
Definition: Builders.cpp:286
DictionaryAttr getDictionaryAttr(ArrayRef< NamedAttribute > value)
Definition: Builders.cpp:144
NamedAttribute getNamedAttr(StringRef name, Attribute val)
Definition: Builders.cpp:134
IntegerAttr getUI32IntegerAttr(uint32_t value)
Definition: Builders.cpp:252
FloatType getFloat8E5M2FNUZType()
Definition: Builders.cpp:61
IntegerAttr getI8IntegerAttr(int8_t value)
Definition: Builders.cpp:261
ArrayAttr getF32ArrayAttr(ArrayRef< float > values)
Definition: Builders.cpp:334
FloatType getF64Type()
Definition: Builders.cpp:89
ArrayAttr getBoolArrayAttr(ArrayRef< bool > values)
Definition: Builders.cpp:310
ArrayAttr getStrArrayAttr(ArrayRef< StringRef > values)
Definition: Builders.cpp:346
DenseIntElementsAttr getIndexVectorAttr(ArrayRef< int64_t > values)
Definition: Builders.cpp:174
ArrayAttr getAffineMapArrayAttr(ArrayRef< AffineMap > values)
Definition: Builders.cpp:358
Attr getAttr(Args &&...args)
Get or construct an instance of the attribute Attr with provided arguments.
Definition: Builders.h:106
TypedAttr getOneAttr(Type type)
Definition: Builders.cpp:382
An attribute that represents a reference to a dense float vector or tensor object.
An attribute that represents a reference to a dense integer vector or tensor object.
This is a utility class for mapping one set of IR entities to another.
Definition: IRMapping.h:26
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:66
MLIRContext * getContext() const
Return the context this location is uniqued in.
Definition: Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:60
NamedAttribute represents a combination of a name and an Attribute value.
Definition: Attributes.h:207
This class represents a saved insertion point.
Definition: Builders.h:335
InsertPoint()=default
Creates a new insertion point which doesn't point to anything.
Block::iterator getPoint() const
Definition: Builders.h:348
bool isSet() const
Returns true if this insert point is set.
Definition: Builders.h:345
InsertPoint(Block *insertBlock, Block::iterator insertPt)
Creates a new insertion point at the given location.
Definition: Builders.h:341
Block * getBlock() const
Definition: Builders.h:347
RAII guard to reset the insertion point of the builder when destroyed.
Definition: Builders.h:356
InsertionGuard(OpBuilder &builder)
Definition: Builders.h:358
InsertionGuard(InsertionGuard &&other) noexcept
Implement the move constructor to clear the builder field of other.
Definition: Builders.h:372
InsertionGuard(const InsertionGuard &)=delete
InsertionGuard & operator=(InsertionGuard &&other)=delete
InsertionGuard & operator=(const InsertionGuard &)=delete
This class helps build Operations.
Definition: Builders.h:215
InsertPoint saveInsertionPoint() const
Return a saved insertion point.
Definition: Builders.h:393
static OpBuilder atBlockBegin(Block *block, Listener *listener=nullptr)
Create a builder and set the insertion point to before the first operation in the block but still ins...
Definition: Builders.h:248
OpBuilder(Region *region, Listener *listener=nullptr)
Create a builder and set the insertion point to the start of the region.
Definition: Builders.h:225
Block::iterator getInsertionPoint() const
Returns the current insertion point of the builder.
Definition: Builders.h:453
Operation * cloneWithoutRegions(Operation &op)
Definition: Builders.h:595
OpT cloneWithoutRegions(OpT op)
Definition: Builders.h:599
OpBuilder(MLIRContext *ctx, Listener *listener=nullptr)
Create a builder with the given context.
Definition: Builders.h:221
void clearInsertionPoint()
Reset the insertion point to no location.
Definition: Builders.h:387
static OpBuilder atBlockEnd(Block *block, Listener *listener=nullptr)
Create a builder and set the insertion point to after the last operation in the block but still insid...
Definition: Builders.h:254
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
Definition: Builders.cpp:588
void setListener(Listener *newListener)
Sets the listener of this builder to the one provided.
Definition: Builders.h:324
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition: Builders.h:439
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition: Builders.h:406
void setInsertionPoint(Operation *op)
Sets the insertion point to the specified operation, which will cause subsequent insertions to go rig...
Definition: Builders.h:414
static OpBuilder atBlockTerminator(Block *block, Listener *listener=nullptr)
Create a builder and set the insertion point to before the block terminator.
Definition: Builders.h:260
void setInsertionPointToEnd(Block *block)
Sets the insertion point to the end of the specified block.
Definition: Builders.h:444
void restoreInsertionPoint(InsertPoint ip)
Restore the insert point to a previously saved point.
Definition: Builders.h:398
Listener * getListener() const
Returns the current listener of this builder, or nullptr if this builder doesn't have a listener.
Definition: Builders.h:328
OpBuilder(Region &region, Listener *listener=nullptr)
Definition: Builders.h:230
void cloneRegionBefore(Region &region, Region &parent, Region::iterator before, IRMapping &mapping)
Clone the blocks that belong to "region" before the given position in another region "parent".
Definition: Builders.cpp:615
OpBuilder(Block *block, Block::iterator insertPoint, Listener *listener=nullptr)
Definition: Builders.h:240
OpTy create(Location location, Args &&...args)
Create an operation of specific op type at the current insertion point.
Definition: Builders.h:514
OpBuilder(Operation *op, Listener *listener=nullptr)
Create a builder and set insertion point to the given operation, which will cause subsequent insertio...
Definition: Builders.h:235
Listener * listener
The optional listener for events of this builder.
Definition: Builders.h:615
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes=std::nullopt, ArrayRef< Location > locs=std::nullopt)
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
Definition: Builders.cpp:470
std::enable_if_t< OpTy::template hasTrait< OpTrait::ZeroResults >), OpTy > createOrFold(Location location, Args &&...args)
Overload to create or fold a zero result operation.
Definition: Builders.h:565
void createOrFold(SmallVectorImpl< Value > &results, Location location, Args &&...args)
Create an operation of specific op type at the current insertion point, and immediately try to fold i...
Definition: Builders.h:528
std::enable_if_t< OpTy::template hasTrait< OpTrait::OneResult >), Value > createOrFold(Location location, Args &&...args)
Overload to create or fold a single result operation.
Definition: Builders.h:556
Block * getBlock() const
Returns the current block of the builder.
Definition: Builders.h:456
void setInsertionPointAfterValue(Value val)
Sets the insertion point to the node after the specified value.
Definition: Builders.h:429
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition: Builders.cpp:497
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Definition: Builders.h:420
LogicalResult tryFold(Operation *op, SmallVectorImpl< Value > &results)
Attempts to fold the given operation and places new results within results.
Definition: Builders.cpp:512
Operation * insert(Operation *op)
Insert the given operation at the current insertion point and return it.
Definition: Builders.cpp:461
Operation * cloneWithoutRegions(Operation &op, IRMapping &mapper)
Creates a deep copy of this operation but keep the operation regions empty.
Definition: Builders.h:592
Block * getInsertionBlock() const
Return the block the current insertion point belongs to.
Definition: Builders.h:450
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
static Operation * create(Location location, OperationName name, TypeRange resultTypes, ValueRange operands, NamedAttrList &&attributes, OpaqueProperties properties, BlockRange successors, unsigned numRegions)
Create a new Operation with the specific fields.
Definition: Operation.cpp:67
Block * getBlock()
Returns the operation block that contains this operation.
Definition: Operation.h:213
Operation * cloneWithoutRegions(IRMapping &mapper)
Create a partial copy of this operation without traversing into attached regions.
Definition: Operation.cpp:703
result_range getResults()
Definition: Operation.h:410
void erase()
Remove this operation from its parent block and delete it.
Definition: Operation.cpp:539
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition: Region.h:26
bool empty()
Definition: Region.h:60
Block & front()
Definition: Region.h:65
BlockListType::iterator iterator
Definition: Region.h:52
static std::optional< RegisteredOperationName > lookup(StringRef name, MLIRContext *ctx)
Lookup the registered operation information for the given operation.
This class implements the result iterators for the Operation class.
Definition: ValueRange.h:242
This class provides an abstraction over the various different ranges of value types.
Definition: TypeRange.h:36
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
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition: Value.cpp:20
Base class for DenseArrayAttr that is instantiated and specialized for each supported element type be...
@ Type
An inlay hint that for a type annotation.
Include the generated interface declarations.
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
Base class for listeners.
Definition: Builders.h:272
Kind
The kind of listener.
Definition: Builders.h:274
@ RewriterBaseListener
RewriterBase::Listener or user-derived class.
@ OpBuilderListener
OpBuilder::Listener or user-derived class.
This class represents a listener that may be used to hook into various actions within an OpBuilder.
Definition: Builders.h:293
virtual void notifyBlockInserted(Block *block, Region *previous, Region::iterator previousIt)
Notify the listener that the specified block was inserted.
Definition: Builders.h:316
virtual ~Listener()=default
virtual void notifyOperationInserted(Operation *op, InsertPoint previous)
Notify the listener that the specified operation was inserted.
Definition: Builders.h:306
This represents an operation in an abstracted form, suitable for use with the builder APIs.