9 #ifndef MLIR_IR_BUILDERS_H
10 #define MLIR_IR_BUILDERS_H
13 #include "llvm/Support/Compiler.h"
31 class RankedTensorType;
32 class UnrankedTensorType;
43 class DenseElementsAttr;
44 class DenseIntElementsAttr;
99 template <
typename Ty,
typename... Args>
106 template <
typename Attr,
typename... Args>
228 if (!region->
empty())
264 assert(terminator !=
nullptr &&
"the block has no terminator");
343 : block(insertBlock), point(insertPt) {}
346 bool isSet()
const {
return (block !=
nullptr); }
352 Block *block =
nullptr;
374 : builder(other.builder), ip(other.ip) {
375 other.builder =
nullptr;
389 this->block =
nullptr;
410 this->insertPoint = insertPoint;
434 auto blockArg = llvm::cast<BlockArgument>(val);
468 TypeRange argTypes = std::nullopt,
469 ArrayRef<Location> locs = std::nullopt);
475 Block *
createBlock(Block *insertBefore, TypeRange argTypes = std::nullopt,
476 ArrayRef<Location> locs = std::nullopt);
483 Operation *
insert(Operation *op);
486 Operation *
create(
const OperationState &state);
489 Operation *
create(Location loc, StringAttr opName, ValueRange operands,
490 TypeRange types = {},
491 ArrayRef<NamedAttribute> attributes = {},
492 BlockRange successors = {},
493 MutableArrayRef<std::unique_ptr<Region>> regions = {});
497 template <
typename OpT>
498 RegisteredOperationName getCheckRegisteredInfo(MLIRContext *ctx) {
499 std::optional<RegisteredOperationName> opName =
501 if (LLVM_UNLIKELY(!opName)) {
502 llvm::report_fatal_error(
503 "Building op `" + OpT::getOperationName() +
504 "` but it isn't known in this MLIRContext: the dialect may not "
505 "be loaded or this operation hasn't been added by the dialect. See "
506 "also https://mlir.llvm.org/getting_started/Faq/"
507 "#registered-loaded-dependent-whats-up-with-dialects-management");
514 template <
typename OpTy,
typename... Args>
517 getCheckRegisteredInfo<OpTy>(location.
getContext()));
518 OpTy::build(*
this, state, std::forward<Args>(args)...);
520 auto result = dyn_cast<OpTy>(op);
521 assert(result &&
"builder didn't return the right type");
528 template <
typename OpTy,
typename... Args>
534 getCheckRegisteredInfo<OpTy>(location.
getContext()));
535 OpTy::build(*
this, state, std::forward<Args>(args)...);
541 if (succeeded(
tryFold(op, results)) && !results.empty()) {
549 results.assign(opResults.begin(), opResults.end());
555 template <
typename OpTy,
typename... Args>
556 std::enable_if_t<OpTy::template hasTrait<OpTrait::OneResult>(),
Value>
559 createOrFold<OpTy>(results, location, std::forward<Args>(args)...);
560 return results.front();
564 template <
typename OpTy,
typename... Args>
565 std::enable_if_t<OpTy::template hasTrait<OpTrait::ZeroResults>(), OpTy>
567 auto op = create<OpTy>(location, std::forward<Args>(args)...);
569 (void)
tryFold(op.getOperation(), unused);
599 template <
typename OpT>
620 Block *block =
nullptr;
Base type for affine expression.
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Attributes are known-constant values of operations.
Block represents an ordered list of Operations.
OpListType::iterator iterator
Operation * getTerminator()
Get the terminator operation of this block.
OpListType & getOperations()
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,...
FloatType getFloat8E5M2Type()
IntegerAttr getIndexAttr(int64_t value)
AffineMap getSingleDimShiftAffineMap(int64_t shift)
Returns a map that shifts its (single) input dimension by 'shift'.
ArrayAttr getIndexArrayAttr(ArrayRef< int64_t > values)
DenseF64ArrayAttr getDenseF64ArrayAttr(ArrayRef< double > values)
DenseI8ArrayAttr getDenseI8ArrayAttr(ArrayRef< int8_t > values)
FloatType getFloat8E8M0FNUType()
IntegerAttr getI32IntegerAttr(int32_t value)
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
DenseIntElementsAttr getBoolVectorAttr(ArrayRef< bool > values)
Vector-typed DenseIntElementsAttr getters. values must not be empty.
TupleType getTupleType(TypeRange elementTypes)
IntegerAttr getIntegerAttr(Type type, int64_t value)
FloatAttr getF64FloatAttr(double value)
AffineMap getShiftedAffineMap(AffineMap map, int64_t shift)
Returns an affine map that is a translation (shift) of all result expressions in 'map' by 'shift'.
FloatType getFloat8E4M3B11FNUZType()
ArrayAttr getI32ArrayAttr(ArrayRef< int32_t > values)
DenseI64ArrayAttr getDenseI64ArrayAttr(ArrayRef< int64_t > values)
FloatAttr getF16FloatAttr(float value)
AffineMap getDimIdentityMap()
AffineMap getMultiDimIdentityMap(unsigned rank)
IntegerAttr getI16IntegerAttr(int16_t value)
DenseI16ArrayAttr getDenseI16ArrayAttr(ArrayRef< int16_t > values)
FloatType getFloat6E3M2FNType()
AffineExpr getAffineSymbolExpr(unsigned position)
DenseFPElementsAttr getF32VectorAttr(ArrayRef< float > values)
FloatAttr getFloatAttr(Type type, double value)
AffineExpr getAffineConstantExpr(int64_t constant)
DenseIntElementsAttr getI32TensorAttr(ArrayRef< int32_t > values)
Tensor-typed DenseIntElementsAttr getters.
FunctionType getFunctionType(TypeRange inputs, TypeRange results)
IntegerAttr getI64IntegerAttr(int64_t value)
IntegerType getIntegerType(unsigned width)
DenseIntElementsAttr getI64TensorAttr(ArrayRef< int64_t > values)
Ty getType(Args &&...args)
Get or construct an instance of the type Ty with provided arguments.
BoolAttr getBoolAttr(bool value)
StringAttr getStringAttr(const Twine &bytes)
Builder(MLIRContext *context)
AffineMap getEmptyAffineMap()
Returns a zero result affine map with no dimensions or symbols: () -> ().
FloatType getFloat8E3M4Type()
IntegerAttr getSI32IntegerAttr(int32_t value)
Signed and unsigned integer attribute getters.
FloatType getFloat8E4M3Type()
TypedAttr getZeroAttr(Type type)
Location getFusedLoc(ArrayRef< Location > locs, Attribute metadata=Attribute())
AffineExpr getAffineDimExpr(unsigned position)
DenseIntElementsAttr getIndexTensorAttr(ArrayRef< int64_t > values)
AffineMap getConstantAffineMap(int64_t val)
Returns a single constant result affine map with 0 dimensions and 0 symbols.
MLIRContext * getContext() const
ArrayAttr getTypeArrayAttr(TypeRange values)
DenseIntElementsAttr getI32VectorAttr(ArrayRef< int32_t > values)
DenseF32ArrayAttr getDenseF32ArrayAttr(ArrayRef< float > values)
FloatType getFloat4E2M1FNType()
FloatType getFloat8E4M3FNType()
DenseIntElementsAttr getI64VectorAttr(ArrayRef< int64_t > values)
AffineMap getSymbolIdentityMap()
ArrayAttr getF64ArrayAttr(ArrayRef< double > values)
FloatType getFloat6E2M3FNType()
DenseFPElementsAttr getF64VectorAttr(ArrayRef< double > values)
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
DenseBoolArrayAttr getDenseBoolArrayAttr(ArrayRef< bool > values)
Tensor-typed DenseArrayAttr getters.
FloatType getFloat8E4M3FNUZType()
ArrayAttr getI64ArrayAttr(ArrayRef< int64_t > values)
FloatAttr getF32FloatAttr(float value)
DictionaryAttr getDictionaryAttr(ArrayRef< NamedAttribute > value)
NamedAttribute getNamedAttr(StringRef name, Attribute val)
IntegerAttr getUI32IntegerAttr(uint32_t value)
FloatType getFloat8E5M2FNUZType()
IntegerAttr getI8IntegerAttr(int8_t value)
ArrayAttr getF32ArrayAttr(ArrayRef< float > values)
ArrayAttr getBoolArrayAttr(ArrayRef< bool > values)
ArrayAttr getStrArrayAttr(ArrayRef< StringRef > values)
DenseIntElementsAttr getIndexVectorAttr(ArrayRef< int64_t > values)
ArrayAttr getAffineMapArrayAttr(ArrayRef< AffineMap > values)
Attr getAttr(Args &&...args)
Get or construct an instance of the attribute Attr with provided arguments.
TypedAttr getOneAttr(Type type)
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.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext * getContext() const
Return the context this location is uniqued in.
MLIRContext is the top-level object for a collection of MLIR operations.
NamedAttribute represents a combination of a name and an Attribute value.
This class represents a saved insertion point.
InsertPoint()=default
Creates a new insertion point which doesn't point to anything.
Block::iterator getPoint() const
bool isSet() const
Returns true if this insert point is set.
InsertPoint(Block *insertBlock, Block::iterator insertPt)
Creates a new insertion point at the given location.
RAII guard to reset the insertion point of the builder when destroyed.
InsertionGuard(OpBuilder &builder)
InsertionGuard(InsertionGuard &&other) noexcept
Implement the move constructor to clear the builder field of other.
InsertionGuard(const InsertionGuard &)=delete
InsertionGuard & operator=(InsertionGuard &&other)=delete
InsertionGuard & operator=(const InsertionGuard &)=delete
This class helps build Operations.
InsertPoint saveInsertionPoint() const
Return a saved insertion point.
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...
OpBuilder(Region *region, Listener *listener=nullptr)
Create a builder and set the insertion point to the start of the region.
Block::iterator getInsertionPoint() const
Returns the current insertion point of the builder.
Operation * cloneWithoutRegions(Operation &op)
OpT cloneWithoutRegions(OpT op)
OpBuilder(MLIRContext *ctx, Listener *listener=nullptr)
Create a builder with the given context.
void clearInsertionPoint()
Reset the insertion point to no location.
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...
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
void setListener(Listener *newListener)
Sets the listener of this builder to the one provided.
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
void setInsertionPoint(Operation *op)
Sets the insertion point to the specified operation, which will cause subsequent insertions to go rig...
static OpBuilder atBlockTerminator(Block *block, Listener *listener=nullptr)
Create a builder and set the insertion point to before the block terminator.
void setInsertionPointToEnd(Block *block)
Sets the insertion point to the end of the specified block.
void restoreInsertionPoint(InsertPoint ip)
Restore the insert point to a previously saved point.
Listener * getListener() const
Returns the current listener of this builder, or nullptr if this builder doesn't have a listener.
OpBuilder(Region ®ion, Listener *listener=nullptr)
void cloneRegionBefore(Region ®ion, Region &parent, Region::iterator before, IRMapping &mapping)
Clone the blocks that belong to "region" before the given position in another region "parent".
OpBuilder(Block *block, Block::iterator insertPoint, Listener *listener=nullptr)
OpTy create(Location location, Args &&...args)
Create an operation of specific op type at the current insertion point.
OpBuilder(Operation *op, Listener *listener=nullptr)
Create a builder and set insertion point to the given operation, which will cause subsequent insertio...
Listener * listener
The optional listener for events of this builder.
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.
std::enable_if_t< OpTy::template hasTrait< OpTrait::ZeroResults >), OpTy > createOrFold(Location location, Args &&...args)
Overload to create or fold a zero result operation.
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...
std::enable_if_t< OpTy::template hasTrait< OpTrait::OneResult >), Value > createOrFold(Location location, Args &&...args)
Overload to create or fold a single result operation.
Block * getBlock() const
Returns the current block of the builder.
void setInsertionPointAfterValue(Value val)
Sets the insertion point to the node after the specified value.
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
LogicalResult tryFold(Operation *op, SmallVectorImpl< Value > &results)
Attempts to fold the given operation and places new results within results.
Operation * insert(Operation *op)
Insert the given operation at the current insertion point and return it.
Operation * cloneWithoutRegions(Operation &op, IRMapping &mapper)
Creates a deep copy of this operation but keep the operation regions empty.
Block * getInsertionBlock() const
Return the block the current insertion point belongs to.
Operation is the basic unit of execution within MLIR.
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.
Block * getBlock()
Returns the operation block that contains this operation.
Operation * cloneWithoutRegions(IRMapping &mapper)
Create a partial copy of this operation without traversing into attached regions.
result_range getResults()
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.
BlockListType::iterator iterator
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.
This class provides an abstraction over the various different ranges of value types.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
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.
Kind
The kind of listener.
@ 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.
virtual void notifyBlockInserted(Block *block, Region *previous, Region::iterator previousIt)
Notify the listener that the specified block was inserted.
virtual ~Listener()=default
virtual void notifyOperationInserted(Operation *op, InsertPoint previous)
Notify the listener that the specified operation was inserted.
This represents an operation in an abstracted form, suitable for use with the builder APIs.