MLIR 23.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
13#include "llvm/Support/Compiler.h"
14#include <optional>
15
16namespace mlir {
17
18class AffineExpr;
19class IRMapping;
20class UnknownLoc;
21class FileLineColLoc;
22class FileLineColRange;
23class Type;
24class IntegerType;
25class FloatType;
26class FunctionType;
27class GraphType;
28class IndexType;
29class MemRefType;
30class VectorType;
31class RankedTensorType;
32class UnrankedTensorType;
33class TupleType;
34class NoneType;
35class BoolAttr;
36class IntegerAttr;
37class FloatAttr;
38class StringAttr;
39class TypeAttr;
40class ArrayAttr;
41class SymbolRefAttr;
42class ElementsAttr;
45class AffineMapAttr;
46class AffineMap;
47class UnitAttr;
48
49/// This class is a general helper class for creating context-global objects
50/// like types, attributes, and affine expressions.
51class Builder {
52public:
54 explicit Builder(Operation *op) : Builder(op->getContext()) {}
55
56 MLIRContext *getContext() const { return context; }
57
58 // Locations.
61 Attribute metadata = Attribute());
62
63 // Types.
64 FloatType getF8E8M0Type();
65 FloatType getF8E4M3FNType();
66 FloatType getF8E5M2Type();
67 FloatType getBF16Type();
68 FloatType getF16Type();
69 FloatType getTF32Type();
70 FloatType getF32Type();
71 FloatType getF64Type();
72 FloatType getF80Type();
73 FloatType getF128Type();
74
75 IndexType getIndexType();
76
77 IntegerType getI1Type();
78 IntegerType getI2Type();
79 IntegerType getI4Type();
80 IntegerType getI8Type();
81 IntegerType getI16Type();
82 IntegerType getI32Type();
83 IntegerType getI64Type();
84 IntegerType getIntegerType(unsigned width);
85 IntegerType getIntegerType(unsigned width, bool isSigned);
86 FunctionType getFunctionType(TypeRange inputs, TypeRange results);
87 GraphType getGraphType(TypeRange inputs, TypeRange results);
88 TupleType getTupleType(TypeRange elementTypes);
89 NoneType getNoneType();
90
91 /// Get or construct an instance of the type `Ty` with provided arguments.
92 template <typename Ty, typename... Args>
93 Ty getType(Args &&...args) {
94 return Ty::get(context, std::forward<Args>(args)...);
95 }
96
97 /// Get or construct an instance of the attribute `Attr` with provided
98 /// arguments.
99 template <typename Attr, typename... Args>
100 Attr getAttr(Args &&...args) {
101 return Attr::get(context, std::forward<Args>(args)...);
102 }
103
104 // Attributes.
105 NamedAttribute getNamedAttr(StringRef name, Attribute val);
106
107 UnitAttr getUnitAttr();
108 BoolAttr getBoolAttr(bool value);
109 DictionaryAttr getDictionaryAttr(ArrayRef<NamedAttribute> value);
110 IntegerAttr getIntegerAttr(Type type, int64_t value);
111 IntegerAttr getIntegerAttr(Type type, const APInt &value);
112 FloatAttr getFloatAttr(Type type, double value);
113 FloatAttr getFloatAttr(Type type, const APFloat &value);
114 StringAttr getStringAttr(const Twine &bytes);
116
117 // Returns a 0-valued attribute of the given `type`. This function only
118 // supports boolean, integer, and 16-/32-/64-bit float types, and vector or
119 // ranked tensor of them. Returns null attribute otherwise.
120 TypedAttr getZeroAttr(Type type);
121 // Returns a 1-valued attribute of the given `type`.
122 // Type constraints are the same as `getZeroAttr`.
123 TypedAttr getOneAttr(Type type);
124
125 // Convenience methods for fixed types.
126 FloatAttr getF16FloatAttr(float value);
127 FloatAttr getF32FloatAttr(float value);
128 FloatAttr getF64FloatAttr(double value);
129
130 IntegerAttr getI8IntegerAttr(int8_t value);
131 IntegerAttr getI16IntegerAttr(int16_t value);
132 IntegerAttr getI32IntegerAttr(int32_t value);
133 IntegerAttr getI64IntegerAttr(int64_t value);
134 IntegerAttr getIndexAttr(int64_t value);
135
136 /// Signed and unsigned integer attribute getters.
137 IntegerAttr getSI32IntegerAttr(int32_t value);
138 IntegerAttr getUI32IntegerAttr(uint32_t value);
139
140 /// Vector-typed DenseIntElementsAttr getters. `values` must not be empty.
145
148
149 /// Tensor-typed DenseIntElementsAttr getters. `values` can be empty.
150 /// These are generally preferable for representing general lists of integers
151 /// as attributes.
155
156 /// Tensor-typed DenseArrayAttr getters.
164
174
175 // Affine expressions and affine maps.
176 AffineExpr getAffineDimExpr(unsigned position);
177 AffineExpr getAffineSymbolExpr(unsigned position);
179
180 // Special cases of affine maps and integer sets
181 /// Returns a zero result affine map with no dimensions or symbols: () -> ().
183 /// Returns a single constant result affine map with 0 dimensions and 0
184 /// symbols. One constant result: () -> (val).
186 // One dimension id identity map: (i) -> (i).
188 // Multi-dimensional identity map: (d0, d1, d2) -> (d0, d1, d2).
189 AffineMap getMultiDimIdentityMap(unsigned rank);
190 // One symbol identity map: ()[s] -> (s).
192
193 /// Returns a map that shifts its (single) input dimension by 'shift'.
194 /// (d0) -> (d0 + shift)
196
197 /// Returns an affine map that is a translation (shift) of all result
198 /// expressions in 'map' by 'shift'.
199 /// Eg: input: (d0, d1)[s0] -> (d0, d1 + s0), shift = 2
200 /// returns: (d0, d1)[s0] -> (d0 + 2, d1 + s0 + 2)
202
203protected:
205};
206
207/// This class helps build Operations. Operations that are created are
208/// automatically inserted at an insertion point. The builder is copyable.
209class OpBuilder : public Builder {
210public:
211 class InsertPoint;
212 struct Listener;
213
214 /// Create a builder with the given context.
215 explicit OpBuilder(MLIRContext *ctx, Listener *listener = nullptr)
216 : Builder(ctx), listener(listener) {}
217
218 /// Create a builder and set the insertion point to the start of the region.
219 explicit OpBuilder(Region *region, Listener *listener = nullptr)
220 : OpBuilder(region->getContext(), listener) {
221 if (!region->empty())
223 }
224 explicit OpBuilder(Region &region, Listener *listener = nullptr)
225 : OpBuilder(&region, listener) {}
226
227 /// Create a builder and set insertion point to the given operation, which
228 /// will cause subsequent insertions to go right before it.
229 explicit OpBuilder(Operation *op, Listener *listener = nullptr)
230 : OpBuilder(op->getContext(), listener) {
232 }
233
234 OpBuilder(Block *block, Block::iterator insertPoint,
235 Listener *listener = nullptr)
236 : OpBuilder(block->getParent()->getContext(), listener) {
237 setInsertionPoint(block, insertPoint);
238 }
239
240 /// Create a builder and set the insertion point to before the first operation
241 /// in the block but still inside the block.
242 static OpBuilder atBlockBegin(Block *block, Listener *listener = nullptr) {
243 return OpBuilder(block, block->begin(), listener);
244 }
245
246 /// Create a builder and set the insertion point to after the last operation
247 /// in the block but still inside the block.
248 static OpBuilder atBlockEnd(Block *block, Listener *listener = nullptr) {
249 return OpBuilder(block, block->end(), listener);
250 }
251
252 /// Create a builder and set the insertion point to before the block
253 /// terminator.
255 Listener *listener = nullptr) {
256 auto *terminator = block->getTerminator();
257 assert(terminator != nullptr && "the block has no terminator");
258 return OpBuilder(block, Block::iterator(terminator), listener);
259 }
260
261 //===--------------------------------------------------------------------===//
262 // Listeners
263 //===--------------------------------------------------------------------===//
264
265 /// Base class for listeners.
267 /// The kind of listener.
268 enum class Kind {
269 /// OpBuilder::Listener or user-derived class.
271
272 /// RewriterBase::Listener or user-derived class.
274 };
275
276 Kind getKind() const { return kind; }
277
278 protected:
279 ListenerBase(Kind kind) : kind(kind) {}
280
281 private:
282 const Kind kind;
283 };
284
285 /// This class represents a listener that may be used to hook into various
286 /// actions within an OpBuilder.
287 struct Listener : public ListenerBase {
289
290 virtual ~Listener() = default;
291
292 /// Notify the listener that the specified operation was inserted.
293 ///
294 /// * If the operation was moved, then `previous` is the previous location
295 /// of the op.
296 /// * If the operation was unlinked before it was inserted, then `previous`
297 /// is empty.
298 ///
299 /// Note: Creating an (unlinked) op does not trigger this notification.
300 virtual void notifyOperationInserted(Operation *op, InsertPoint previous) {}
301
302 /// Notify the listener that the specified block was inserted.
303 ///
304 /// * If the block was moved, then `previous` and `previousIt` are the
305 /// previous location of the block.
306 /// * If the block was unlinked before it was inserted, then `previous`
307 /// is "nullptr".
308 ///
309 /// Note: Creating an (unlinked) block does not trigger this notification.
310 virtual void notifyBlockInserted(Block *block, Region *previous,
311 Region::iterator previousIt) {}
312
313 protected:
314 Listener(Kind kind) : ListenerBase(kind) {}
315 };
316
317 /// Sets the listener of this builder to the one provided.
318 void setListener(Listener *newListener) { listener = newListener; }
319
320 /// Returns the current listener of this builder, or nullptr if this builder
321 /// doesn't have a listener.
322 Listener *getListener() const { return listener; }
323
324 //===--------------------------------------------------------------------===//
325 // Insertion Point Management
326 //===--------------------------------------------------------------------===//
327
328 /// This class represents a saved insertion point.
330 public:
331 /// Creates a new insertion point which doesn't point to anything.
332 InsertPoint() = default;
333
334 /// Creates a new insertion point at the given location.
335 InsertPoint(Block *insertBlock, Block::iterator insertPt)
336 : block(insertBlock), point(insertPt) {}
337
338 /// Returns true if this insert point is set.
339 bool isSet() const { return (block != nullptr); }
340
341 Block *getBlock() const { return block; }
342 Block::iterator getPoint() const { return point; }
343
344 private:
345 Block *block = nullptr;
346 Block::iterator point;
347 };
348
349 /// RAII guard to reset the insertion point of the builder when destroyed.
351 public:
353 : builder(&builder), ip(builder.saveInsertionPoint()) {}
354
356 if (builder)
357 builder->restoreInsertionPoint(ip);
358 }
359
362
363 /// Implement the move constructor to clear the builder field of `other`.
364 /// That way it does not restore the insertion point upon destruction as
365 /// that should be done exclusively by the just constructed InsertionGuard.
367 : builder(other.builder), ip(other.ip) {
368 other.builder = nullptr;
369 }
370
372
373 private:
374 OpBuilder *builder;
376 };
377
378 /// Reset the insertion point to no location. Creating an operation without a
379 /// set insertion point is an error, but this can still be useful when the
380 /// current insertion point a builder refers to is being removed.
382 this->block = nullptr;
383 insertPoint = Block::iterator();
384 }
385
386 /// Return a saved insertion point.
390
391 /// Restore the insert point to a previously saved point.
393 if (ip.isSet())
395 else
397 }
398
399 /// Set the insertion point to the specified location.
400 void setInsertionPoint(Block *block, Block::iterator insertPoint) {
401 // TODO: check that insertPoint is in this rather than some other block.
402 this->block = block;
403 this->insertPoint = insertPoint;
404 }
405
406 /// Sets the insertion point to the specified operation, which will cause
407 /// subsequent insertions to go right before it.
411
412 /// Sets the insertion point to the node after the specified operation, which
413 /// will cause subsequent insertions to go right after it.
417
418 /// Sets the insertion point to the node after the specified value. If value
419 /// has a defining operation, sets the insertion point to the node after such
420 /// defining operation. This will cause subsequent insertions to go right
421 /// after it. Otherwise, value is a BlockArgument. Sets the insertion point to
422 /// the start of its block.
424 if (Operation *op = val.getDefiningOp()) {
426 } else {
427 auto blockArg = llvm::cast<BlockArgument>(val);
428 setInsertionPointToStart(blockArg.getOwner());
429 }
430 }
431
432 /// Sets the insertion point to the start of the specified block.
434 setInsertionPoint(block, block->begin());
435 }
436
437 /// Sets the insertion point to the end of the specified block.
439 setInsertionPoint(block, block->end());
440 }
441
442 /// Return the block the current insertion point belongs to. Note that the
443 /// insertion point is not necessarily the end of the block.
444 Block *getInsertionBlock() const { return block; }
445
446 /// Returns the current insertion point of the builder.
447 Block::iterator getInsertionPoint() const { return insertPoint; }
448
449 /// Returns the current block of the builder.
450 Block *getBlock() const { return block; }
451
452 //===--------------------------------------------------------------------===//
453 // Block Creation
454 //===--------------------------------------------------------------------===//
455
456 /// Add new block with 'argTypes' arguments and set the insertion point to the
457 /// end of it. The block is inserted at the provided insertion point of
458 /// 'parent'. `locs` contains the locations of the inserted arguments, and
459 /// should match the size of `argTypes`.
460 Block *createBlock(Region *parent, Region::iterator insertPt = {},
461 TypeRange argTypes = {}, ArrayRef<Location> locs = {});
462
463 /// Add new block with 'argTypes' arguments and set the insertion point to the
464 /// end of it. The block is placed before 'insertBefore'. `locs` contains the
465 /// locations of the inserted arguments, and should match the size of
466 /// `argTypes`.
467 Block *createBlock(Block *insertBefore, TypeRange argTypes = {},
468 ArrayRef<Location> locs = {});
469
470 //===--------------------------------------------------------------------===//
471 // Operation Creation
472 //===--------------------------------------------------------------------===//
473
474 /// Insert the given operation at the current insertion point and return it.
475 Operation *insert(Operation *op);
476
477 /// Creates an operation given the fields represented as an OperationState.
478 Operation *create(const OperationState &state);
479
480 /// Creates an operation with the given fields.
481 Operation *create(Location loc, StringAttr opName, ValueRange operands,
482 TypeRange types = {},
483 ArrayRef<NamedAttribute> attributes = {},
484 BlockRange successors = {},
485 MutableArrayRef<std::unique_ptr<Region>> regions = {});
486
487private:
488 /// Helper for sanity checking preconditions for create* methods below.
489 template <typename OpT>
490 RegisteredOperationName getCheckRegisteredInfo(MLIRContext *ctx) {
491 std::optional<RegisteredOperationName> opName =
493 if (LLVM_UNLIKELY(!opName)) {
494 llvm::report_fatal_error(
495 "Building op `" + OpT::getOperationName() +
496 "` but it isn't known in this MLIRContext: the dialect may not "
497 "be loaded or this operation hasn't been added by the dialect. See "
498 "also https://mlir.llvm.org/getting_started/Faq/"
499 "#registered-loaded-dependent-whats-up-with-dialects-management");
500 }
501 return *opName;
502 }
503
504public:
505 /// Create an operation of specific op type at the current insertion point.
506 template <typename OpTy, typename... Args>
507 [[deprecated("Use OpTy::create instead")]]
508 OpTy create(Location location, Args &&...args) {
509 OperationState state(location,
510 getCheckRegisteredInfo<OpTy>(location.getContext()));
511 OpTy::build(*this, state, std::forward<Args>(args)...);
512 auto *op = create(state);
513 auto result = dyn_cast<OpTy>(op);
514 assert(result && "builder didn't return the right type");
515 return result;
516 }
517
518 /// Create an operation of specific op type at the current insertion point,
519 /// and immediately try to fold it. This functions populates 'results' with
520 /// the results of the operation.
521 ///
522 /// Note: This performs opportunistic eager folding during IR construction.
523 /// The folders are designed to operate efficiently on canonical IR, which
524 /// this API does not enforce. Complete folding isn't only expected in the
525 /// context of canonicalization which intertwine folders with pattern
526 /// rewrites until fixed-point.
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 = OpTy::create(*this, location, std::forward<Args>(args)...);
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. Optionally, newly
578 /// materialized constant operations can be returned to the caller.
579 ///
580 /// Note: This function does not erase the operation on a successful fold.
581 LogicalResult
583 SmallVectorImpl<Operation *> *materializedConstants = nullptr);
584
585 /// Creates a deep copy of the specified operation, remapping any operands
586 /// that use values outside of the operation using the map that is provided
587 /// ( leaving them alone if no entry is present). Replaces references to
588 /// cloned sub-operations to the corresponding operation that is copied,
589 /// and adds those mappings to the map.
590 Operation *clone(Operation &op, IRMapping &mapper);
592
593 /// Creates a deep copy of this operation but keep the operation regions
594 /// empty. Operands are remapped using `mapper` (if present), and `mapper` is
595 /// updated to contain the results.
597 return insert(op.cloneWithoutRegions(mapper));
598 }
602 template <typename OpT>
604 return cast<OpT>(cloneWithoutRegions(*op.getOperation()));
605 }
606
607 /// Clone the blocks that belong to "region" before the given position in
608 /// another region "parent". The two regions must be different. The caller is
609 /// responsible for creating or updating the operation transferring flow of
610 /// control to the region and passing it the correct block arguments.
611 void cloneRegionBefore(Region &region, Region &parent,
612 Region::iterator before, IRMapping &mapping);
613 void cloneRegionBefore(Region &region, Region &parent,
614 Region::iterator before);
615 void cloneRegionBefore(Region &region, Block *before);
616
617protected:
618 /// The optional listener for events of this builder.
620
621private:
622 /// The current block this builder is inserting into.
623 Block *block = nullptr;
624 /// The insertion point within the block that this builder is inserting
625 /// before.
626 Block::iterator insertPoint;
627};
628
629/// ImplicitLocOpBuilder maintains a 'current location', allowing use of the
630/// create<> method without specifying the location. It is otherwise the same
631/// as OpBuilder.
633public:
634 /// OpBuilder has a bunch of convenience constructors - we support them all
635 /// with the additional Location.
636 template <typename... T>
637 ImplicitLocOpBuilder(Location loc, T &&...operands)
638 : OpBuilder(std::forward<T>(operands)...), curLoc(loc) {}
639
640 /// Create a builder and set the insertion point to before the first operation
641 /// in the block but still inside the block.
643 Listener *listener = nullptr) {
644 return ImplicitLocOpBuilder(loc, block, block->begin(), listener);
645 }
646
647 /// Create a builder and set the insertion point to after the last operation
648 /// in the block but still inside the block.
650 Listener *listener = nullptr) {
651 return ImplicitLocOpBuilder(loc, block, block->end(), listener);
652 }
653
654 /// Create a builder and set the insertion point to before the block
655 /// terminator.
657 Listener *listener = nullptr) {
658 auto *terminator = block->getTerminator();
659 assert(terminator != nullptr && "the block has no terminator");
660 return ImplicitLocOpBuilder(loc, block, Block::iterator(terminator),
661 listener);
662 }
663
664 /// Accessors for the implied location.
665 Location getLoc() const { return curLoc; }
666 void setLoc(Location loc) { curLoc = loc; }
667
668 // We allow clients to use the explicit-loc version of create as well.
669 using OpBuilder::create;
671
672 /// Create an operation of specific op type at the current insertion point and
673 /// location.
674 template <typename OpTy, typename... Args>
675 OpTy create(Args &&...args) {
676 return OpTy::create(*this, curLoc, std::forward<Args>(args)...);
677 }
678
679 /// Create an operation of specific op type at the current insertion point,
680 /// and immediately try to fold it. This functions populates 'results' with
681 /// the results after folding the operation.
682 template <typename OpTy, typename... Args>
683 void createOrFold(llvm::SmallVectorImpl<Value> &results, Args &&...args) {
684 OpBuilder::createOrFold<OpTy>(results, curLoc, std::forward<Args>(args)...);
685 }
686
687 /// Overload to create or fold a single result operation.
688 template <typename OpTy, typename... Args>
689 std::enable_if_t<OpTy::template hasTrait<mlir::OpTrait::OneResult>(), Value>
690 createOrFold(Args &&...args) {
691 return OpBuilder::createOrFold<OpTy>(curLoc, std::forward<Args>(args)...);
692 }
693
694 /// Overload to create or fold a zero result operation.
695 template <typename OpTy, typename... Args>
696 std::enable_if_t<OpTy::template hasTrait<mlir::OpTrait::ZeroResults>(), OpTy>
697 createOrFold(Args &&...args) {
698 return OpBuilder::createOrFold<OpTy>(curLoc, std::forward<Args>(args)...);
699 }
700
701 /// This builder can also be used to emit diagnostics to the current location.
703 emitError(const llvm::Twine &message = llvm::Twine()) {
704 return mlir::emitError(curLoc, message);
705 }
707 emitWarning(const llvm::Twine &message = llvm::Twine()) {
708 return mlir::emitWarning(curLoc, message);
709 }
711 emitRemark(const llvm::Twine &message = llvm::Twine()) {
712 return mlir::emitRemark(curLoc, message);
713 }
714
715private:
716 Location curLoc;
717};
718
719} // namespace mlir
720
721#endif
ArrayAttr()
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:150
Special case of IntegerAttr to represent boolean integers, i.e., signless i1 integers.
IntegerAttr getIndexAttr(int64_t value)
Definition Builders.cpp:112
AffineMap getSingleDimShiftAffineMap(int64_t shift)
Returns a map that shifts its (single) input dimension by 'shift'.
Definition Builders.cpp:405
IntegerType getI16Type()
Definition Builders.cpp:65
UnitAttr getUnitAttr()
Definition Builders.cpp:102
ArrayAttr getIndexArrayAttr(ArrayRef< int64_t > values)
Definition Builders.cpp:291
DenseF64ArrayAttr getDenseF64ArrayAttr(ArrayRef< double > values)
Definition Builders.cpp:179
IntegerType getI2Type()
Definition Builders.cpp:59
FloatType getF80Type()
Definition Builders.cpp:51
FloatType getF128Type()
Definition Builders.cpp:53
DenseI8ArrayAttr getDenseI8ArrayAttr(ArrayRef< int8_t > values)
Definition Builders.cpp:159
IntegerAttr getI32IntegerAttr(int32_t value)
Definition Builders.cpp:204
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
Definition Builders.cpp:167
DenseIntElementsAttr getBoolVectorAttr(ArrayRef< bool > values)
Vector-typed DenseIntElementsAttr getters. values must not be empty.
Definition Builders.cpp:120
FloatType getF32Type()
Definition Builders.cpp:47
FloatType getTF32Type()
Definition Builders.cpp:45
TupleType getTupleType(TypeRange elementTypes)
Definition Builders.cpp:88
IntegerAttr getIntegerAttr(Type type, int64_t value)
Definition Builders.cpp:232
FloatAttr getF64FloatAttr(double value)
Definition Builders.cpp:246
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:411
ArrayAttr getI32ArrayAttr(ArrayRef< int32_t > values)
Definition Builders.cpp:280
DenseI64ArrayAttr getDenseI64ArrayAttr(ArrayRef< int64_t > values)
Definition Builders.cpp:171
FloatAttr getF16FloatAttr(float value)
Definition Builders.cpp:254
FloatType getF8E5M2Type()
Definition Builders.cpp:39
AffineMap getDimIdentityMap()
Definition Builders.cpp:387
AffineMap getMultiDimIdentityMap(unsigned rank)
Definition Builders.cpp:391
IntegerAttr getI16IntegerAttr(int16_t value)
Definition Builders.cpp:221
DenseI16ArrayAttr getDenseI16ArrayAttr(ArrayRef< int16_t > values)
Definition Builders.cpp:163
AffineExpr getAffineSymbolExpr(unsigned position)
Definition Builders.cpp:372
DenseFPElementsAttr getF32VectorAttr(ArrayRef< float > values)
Definition Builders.cpp:144
FloatAttr getFloatAttr(Type type, double value)
Definition Builders.cpp:258
AffineExpr getAffineConstantExpr(int64_t constant)
Definition Builders.cpp:376
DenseIntElementsAttr getI32TensorAttr(ArrayRef< int32_t > values)
Tensor-typed DenseIntElementsAttr getters.
Definition Builders.cpp:183
FunctionType getFunctionType(TypeRange inputs, TypeRange results)
Definition Builders.cpp:80
IntegerType getI64Type()
Definition Builders.cpp:69
IntegerType getI32Type()
Definition Builders.cpp:67
IntegerAttr getI64IntegerAttr(int64_t value)
Definition Builders.cpp:116
IntegerType getIntegerType(unsigned width)
Definition Builders.cpp:71
NoneType getNoneType()
Definition Builders.cpp:92
DenseIntElementsAttr getI64TensorAttr(ArrayRef< int64_t > values)
Definition Builders.cpp:190
Ty getType(Args &&...args)
Get or construct an instance of the type Ty with provided arguments.
Definition Builders.h:93
BoolAttr getBoolAttr(bool value)
Definition Builders.cpp:104
IntegerType getI4Type()
Definition Builders.cpp:61
StringAttr getStringAttr(const Twine &bytes)
Definition Builders.cpp:266
MLIRContext * context
Definition Builders.h:204
Builder(MLIRContext *context)
Definition Builders.h:53
AffineMap getEmptyAffineMap()
Returns a zero result affine map with no dimensions or symbols: () -> ().
Definition Builders.cpp:380
Builder(Operation *op)
Definition Builders.h:54
IntegerAttr getSI32IntegerAttr(int32_t value)
Signed and unsigned integer attribute getters.
Definition Builders.cpp:211
GraphType getGraphType(TypeRange inputs, TypeRange results)
Definition Builders.cpp:84
TypedAttr getZeroAttr(Type type)
Definition Builders.cpp:328
FloatType getF16Type()
Definition Builders.cpp:43
Location getFusedLoc(ArrayRef< Location > locs, Attribute metadata=Attribute())
Definition Builders.cpp:27
FloatType getBF16Type()
Definition Builders.cpp:41
AffineExpr getAffineDimExpr(unsigned position)
Definition Builders.cpp:368
DenseIntElementsAttr getIndexTensorAttr(ArrayRef< int64_t > values)
Definition Builders.cpp:197
AffineMap getConstantAffineMap(int64_t val)
Returns a single constant result affine map with 0 dimensions and 0 symbols.
Definition Builders.cpp:382
ArrayAttr getTypeArrayAttr(TypeRange values)
Definition Builders.cpp:316
FloatType getF8E8M0Type()
Definition Builders.cpp:35
DenseIntElementsAttr getI32VectorAttr(ArrayRef< int32_t > values)
Definition Builders.cpp:126
DenseF32ArrayAttr getDenseF32ArrayAttr(ArrayRef< float > values)
Definition Builders.cpp:175
DenseIntElementsAttr getI64VectorAttr(ArrayRef< int64_t > values)
Definition Builders.cpp:132
AffineMap getSymbolIdentityMap()
Definition Builders.cpp:400
ArrayAttr getF64ArrayAttr(ArrayRef< double > values)
Definition Builders.cpp:304
IntegerType getI1Type()
Definition Builders.cpp:57
DenseFPElementsAttr getF64VectorAttr(ArrayRef< double > values)
Definition Builders.cpp:149
Location getUnknownLoc()
Definition Builders.cpp:25
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
Definition Builders.cpp:270
MLIRContext * getContext() const
Definition Builders.h:56
DenseBoolArrayAttr getDenseBoolArrayAttr(ArrayRef< bool > values)
Tensor-typed DenseArrayAttr getters.
Definition Builders.cpp:155
ArrayAttr getI64ArrayAttr(ArrayRef< int64_t > values)
Definition Builders.cpp:285
IndexType getIndexType()
Definition Builders.cpp:55
IntegerType getI8Type()
Definition Builders.cpp:63
FloatAttr getF32FloatAttr(float value)
Definition Builders.cpp:250
DictionaryAttr getDictionaryAttr(ArrayRef< NamedAttribute > value)
Definition Builders.cpp:108
FloatType getF8E4M3FNType()
Definition Builders.cpp:37
NamedAttribute getNamedAttr(StringRef name, Attribute val)
Definition Builders.cpp:98
IntegerAttr getUI32IntegerAttr(uint32_t value)
Definition Builders.cpp:216
IntegerAttr getI8IntegerAttr(int8_t value)
Definition Builders.cpp:225
ArrayAttr getF32ArrayAttr(ArrayRef< float > values)
Definition Builders.cpp:298
FloatType getF64Type()
Definition Builders.cpp:49
ArrayAttr getBoolArrayAttr(ArrayRef< bool > values)
Definition Builders.cpp:274
ArrayAttr getStrArrayAttr(ArrayRef< StringRef > values)
Definition Builders.cpp:310
DenseIntElementsAttr getIndexVectorAttr(ArrayRef< int64_t > values)
Definition Builders.cpp:138
ArrayAttr getAffineMapArrayAttr(ArrayRef< AffineMap > values)
Definition Builders.cpp:322
Attr getAttr(Args &&...args)
Get or construct an instance of the attribute Attr with provided arguments.
Definition Builders.h:100
TypedAttr getOneAttr(Type type)
Definition Builders.cpp:346
An attribute that represents a reference to a dense vector or tensor object.
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.
An instance of this location represents a tuple of file, line number, and column number.
Definition Location.h:174
This is a utility class for mapping one set of IR entities to another.
Definition IRMapping.h:26
std::enable_if_t< OpTy::template hasTrait< mlir::OpTrait::OneResult >(), Value > createOrFold(Args &&...args)
Overload to create or fold a single result operation.
Definition Builders.h:690
void setLoc(Location loc)
Definition Builders.h:666
Location getLoc() const
Accessors for the implied location.
Definition Builders.h:665
mlir::InFlightDiagnostic emitWarning(const llvm::Twine &message=llvm::Twine())
Definition Builders.h:707
static ImplicitLocOpBuilder atBlockTerminator(Location loc, Block *block, Listener *listener=nullptr)
Create a builder and set the insertion point to before the block terminator.
Definition Builders.h:656
ImplicitLocOpBuilder(Location loc, T &&...operands)
OpBuilder has a bunch of convenience constructors - we support them all with the additional Location.
Definition Builders.h:637
static ImplicitLocOpBuilder atBlockBegin(Location loc, 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:642
std::enable_if_t< OpTy::template hasTrait< mlir::OpTrait::ZeroResults >(), OpTy > createOrFold(Args &&...args)
Overload to create or fold a zero result operation.
Definition Builders.h:697
mlir::InFlightDiagnostic emitError(const llvm::Twine &message=llvm::Twine())
This builder can also be used to emit diagnostics to the current location.
Definition Builders.h:703
mlir::InFlightDiagnostic emitRemark(const llvm::Twine &message=llvm::Twine())
Definition Builders.h:711
OpTy create(Args &&...args)
Create an operation of specific op type at the current insertion point and location.
Definition Builders.h:675
void createOrFold(llvm::SmallVectorImpl< Value > &results, Args &&...args)
Create an operation of specific op type at the current insertion point, and immediately try to fold i...
Definition Builders.h:683
static ImplicitLocOpBuilder atBlockEnd(Location loc, 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:649
This class represents a diagnostic that is inflight and set to be reported.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
MLIRContext * getContext() const
Return the context this location is uniqued in.
Definition Location.h:86
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:63
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:164
This class represents a saved insertion point.
Definition Builders.h:329
InsertPoint()=default
Creates a new insertion point which doesn't point to anything.
Block::iterator getPoint() const
Definition Builders.h:342
bool isSet() const
Returns true if this insert point is set.
Definition Builders.h:339
InsertPoint(Block *insertBlock, Block::iterator insertPt)
Creates a new insertion point at the given location.
Definition Builders.h:335
Block * getBlock() const
Definition Builders.h:341
InsertionGuard & operator=(const InsertionGuard &)=delete
InsertionGuard(OpBuilder &builder)
Definition Builders.h:352
InsertionGuard(InsertionGuard &&other) noexcept
Implement the move constructor to clear the builder field of other.
Definition Builders.h:366
InsertionGuard(const InsertionGuard &)=delete
InsertionGuard & operator=(InsertionGuard &&other)=delete
This class helps build Operations.
Definition Builders.h:209
InsertPoint saveInsertionPoint() const
Return a saved insertion point.
Definition Builders.h:387
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:242
OpBuilder(Region *region, Listener *listener=nullptr)
Create a builder and set the insertion point to the start of the region.
Definition Builders.h:219
Block::iterator getInsertionPoint() const
Returns the current insertion point of the builder.
Definition Builders.h:447
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
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes={}, ArrayRef< Location > locs={})
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
Definition Builders.cpp:434
Operation * cloneWithoutRegions(Operation &op)
Definition Builders.h:599
OpT cloneWithoutRegions(OpT op)
Definition Builders.h:603
OpBuilder(MLIRContext *ctx, Listener *listener=nullptr)
Create a builder with the given context.
Definition Builders.h:215
void clearInsertionPoint()
Reset the insertion point to no location.
Definition Builders.h:381
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:248
Block * getBlock() const
Returns the current block of the builder.
Definition Builders.h:450
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:566
void setListener(Listener *newListener)
Sets the listener of this builder to the one provided.
Definition Builders.h:318
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition Builders.h:433
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:400
void setInsertionPoint(Operation *op)
Sets the insertion point to the specified operation, which will cause subsequent insertions to go rig...
Definition Builders.h:408
Listener * getListener() const
Returns the current listener of this builder, or nullptr if this builder doesn't have a listener.
Definition Builders.h:322
static OpBuilder atBlockTerminator(Block *block, Listener *listener=nullptr)
Create a builder and set the insertion point to before the block terminator.
Definition Builders.h:254
void setInsertionPointToEnd(Block *block)
Sets the insertion point to the end of the specified block.
Definition Builders.h:438
void restoreInsertionPoint(InsertPoint ip)
Restore the insert point to a previously saved point.
Definition Builders.h:392
OpBuilder(Region &region, Listener *listener=nullptr)
Definition Builders.h:224
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:593
OpBuilder(Block *block, Block::iterator insertPoint, Listener *listener=nullptr)
Definition Builders.h:234
OpTy create(Location location, Args &&...args)
Create an operation of specific op type at the current insertion point.
Definition Builders.h:508
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:229
Block * getInsertionBlock() const
Return the block the current insertion point belongs to.
Definition Builders.h:444
LogicalResult tryFold(Operation *op, SmallVectorImpl< Value > &results, SmallVectorImpl< Operation * > *materializedConstants=nullptr)
Attempts to fold the given operation and places new results within results.
Definition Builders.cpp:477
Listener * listener
The optional listener for events of this builder.
Definition Builders.h:619
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
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
void setInsertionPointAfterValue(Value val)
Sets the insertion point to the node after the specified value.
Definition Builders.h:423
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition Builders.cpp:461
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Definition Builders.h:414
Operation * cloneWithoutRegions(Operation &op, IRMapping &mapper)
Creates a deep copy of this operation but keep the operation regions empty.
Definition Builders.h:596
Operation * insert(Operation *op)
Insert the given operation at the current insertion point and return it.
Definition Builders.cpp:425
Operation is the basic unit of execution within MLIR.
Definition Operation.h:88
Block * getBlock()
Returns the operation block that contains this operation.
Definition Operation.h:213
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
Operation * cloneWithoutRegions(IRMapping &mapper)
Create a partial copy of this operation without traversing into attached regions.
result_range getResults()
Definition Operation.h:415
void erase()
Remove this operation from its parent block and delete it.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
Block & front()
Definition Region.h:65
bool empty()
Definition Region.h:60
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:247
static TypeID get()
Construct a type info object for the given type T.
Definition TypeID.h:245
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:37
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:18
Include the generated interface declarations.
InFlightDiagnostic emitWarning(Location loc)
Utility method to emit a warning message using this location.
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
detail::DenseArrayAttrImpl< int8_t > DenseI8ArrayAttr
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
detail::DenseArrayAttrImpl< int32_t > DenseI32ArrayAttr
InFlightDiagnostic emitRemark(Location loc)
Utility method to emit a remark message using this location.
detail::DenseArrayAttrImpl< double > DenseF64ArrayAttr
detail::DenseArrayAttrImpl< bool > DenseBoolArrayAttr
detail::DenseArrayAttrImpl< float > DenseF32ArrayAttr
detail::DenseArrayAttrImpl< int16_t > DenseI16ArrayAttr
Kind
The kind of listener.
Definition Builders.h:268
@ RewriterBaseListener
RewriterBase::Listener or user-derived class.
Definition Builders.h:273
@ OpBuilderListener
OpBuilder::Listener or user-derived class.
Definition Builders.h:270
This class represents a listener that may be used to hook into various actions within an OpBuilder.
Definition Builders.h:287
virtual void notifyBlockInserted(Block *block, Region *previous, Region::iterator previousIt)
Notify the listener that the specified block was inserted.
Definition Builders.h:310
virtual ~Listener()=default
virtual void notifyOperationInserted(Operation *op, InsertPoint previous)
Notify the listener that the specified operation was inserted.
Definition Builders.h:300
This represents an operation in an abstracted form, suitable for use with the builder APIs.