17#include "llvm/ADT/TypeSwitch.h"
18#include "llvm/Support/CommandLine.h"
19#include "llvm/Support/StringSaver.h"
28int64_t GPUBlockMappingAttr::getMappingId()
const {
29 return static_cast<int64_t>(getBlock());
32bool GPUBlockMappingAttr::isLinearMapping()
const {
33 return getMappingId() >=
static_cast<int64_t>(MappingId::LinearDim0);
36int64_t GPUBlockMappingAttr::getRelativeIndex()
const {
37 return isLinearMapping()
38 ? getMappingId() -
static_cast<int64_t>(MappingId::LinearDim0)
42int64_t GPUWarpgroupMappingAttr::getMappingId()
const {
43 return static_cast<int64_t>(getWarpgroup());
46bool GPUWarpgroupMappingAttr::isLinearMapping()
const {
47 return getMappingId() >=
static_cast<int64_t>(MappingId::LinearDim0);
50int64_t GPUWarpgroupMappingAttr::getRelativeIndex()
const {
51 return isLinearMapping()
52 ? getMappingId() -
static_cast<int64_t>(MappingId::LinearDim0)
56int64_t GPUWarpMappingAttr::getMappingId()
const {
57 return static_cast<int64_t>(getWarp());
60bool GPUWarpMappingAttr::isLinearMapping()
const {
61 return getMappingId() >=
static_cast<int64_t>(MappingId::LinearDim0);
64int64_t GPUWarpMappingAttr::getRelativeIndex()
const {
65 return isLinearMapping()
66 ? getMappingId() -
static_cast<int64_t>(MappingId::LinearDim0)
70int64_t GPUThreadMappingAttr::getMappingId()
const {
71 return static_cast<int64_t>(getThread());
74bool GPUThreadMappingAttr::isLinearMapping()
const {
75 return getMappingId() >=
static_cast<int64_t>(MappingId::LinearDim0);
78int64_t GPUThreadMappingAttr::getRelativeIndex()
const {
79 return isLinearMapping()
80 ? getMappingId() -
static_cast<int64_t>(MappingId::LinearDim0)
84int64_t GPULaneMappingAttr::getMappingId()
const {
85 return static_cast<int64_t>(getLane());
88bool GPULaneMappingAttr::isLinearMapping()
const {
89 return getMappingId() >=
static_cast<int64_t>(MappingId::LinearDim0);
92int64_t GPULaneMappingAttr::getRelativeIndex()
const {
93 return isLinearMapping()
94 ? getMappingId() -
static_cast<int64_t>(MappingId::LinearDim0)
98int64_t GPUMemorySpaceMappingAttr::getMappingId()
const {
99 return static_cast<int64_t>(getAddressSpace());
102bool GPUMemorySpaceMappingAttr::isLinearMapping()
const {
103 llvm_unreachable(
"GPUMemorySpaceMappingAttr does not support linear mapping");
106int64_t GPUMemorySpaceMappingAttr::getRelativeIndex()
const {
107 llvm_unreachable(
"GPUMemorySpaceMappingAttr does not support relative index");
124 elementType, operand);
138 return elementType.
isF16() || elementType.
isF32() || elementType.
isF64() ||
147 if (operand !=
"AOp" && operand !=
"BOp" && operand !=
"COp")
148 return emitError() <<
"operand expected to be one of AOp, BOp or COp";
150 if (
shape.size() != 2)
151 return emitError() <<
"MMAMatrixType must have exactly two dimensions";
155 <<
"MMAMatrixType elements must be SI8, UI8, I32, F16, F32, or F64";
164bool GPUDialect::isWorkgroupMemoryAddressSpace(
Attribute memorySpace) {
167 if (
auto gpuAttr = llvm::dyn_cast<gpu::AddressSpaceAttr>(memorySpace))
168 return gpuAttr.getValue() == getWorkgroupAddressSpace();
172bool GPUDialect::hasWorkgroupMemoryAddressSpace(MemRefType type) {
173 Attribute memorySpace = type.getMemorySpace();
174 return isWorkgroupMemoryAddressSpace(memorySpace);
177bool GPUDialect::isConstantMemoryAddressSpace(
Attribute memorySpace) {
180 if (
auto gpuAttr = llvm::dyn_cast<gpu::AddressSpaceAttr>(memorySpace))
181 return gpuAttr.getValue() == getConstantAddressSpace();
185bool GPUDialect::hasConstantMemoryAddressSpace(MemRefType type) {
186 Attribute memorySpace = type.getMemorySpace();
187 return isConstantMemoryAddressSpace(memorySpace);
195 Attribute
target, CompilationTarget format,
196 StringAttr
object, DictionaryAttr properties,
197 KernelTableAttr kernels) {
199 return emitError() <<
"the target attribute cannot be null";
200 if (
target.hasPromiseOrImplementsInterface<TargetAttrInterface>())
202 return emitError() <<
"the target attribute must implement or promise the "
203 "`gpu::TargetAttrInterface`";
207ParseResult parseObject(AsmParser &odsParser, CompilationTarget &format,
208 StringAttr &
object) {
209 std::optional<CompilationTarget> formatResult;
210 StringRef enumKeyword;
213 formatResult = CompilationTarget::Fatbin;
216 gpu::symbolizeEnum<gpu::CompilationTarget>(enumKeyword)) &&
218 return odsParser.
emitError(loc,
"expected an equal sign");
220 return odsParser.
emitError(loc,
"expected keyword for GPU object format");
221 FailureOr<StringAttr> objectResult =
222 FieldParser<StringAttr>::parse(odsParser);
225 "failed to parse GPU_ObjectAttr parameter "
226 "'object' which is to be a `StringAttr`");
227 format = *formatResult;
228 object = *objectResult;
232void printObject(AsmPrinter &odsParser, CompilationTarget format,
234 if (format != CompilationTarget::Fatbin)
235 odsParser << stringifyEnum(format) <<
" = ";
249 if (
auto intAttr = mlir::dyn_cast<IntegerAttr>(
target)) {
250 if (intAttr.getInt() < 0) {
251 return emitError() <<
"the object index must be positive";
253 }
else if (!
target.hasPromiseOrImplementsInterface<TargetAttrInterface>()) {
255 <<
"the target attribute must be a GPU Target attribute";
265KernelMetadataAttr KernelMetadataAttr::get(FunctionOpInterface kernel,
266 DictionaryAttr metadata) {
267 assert(kernel &&
"invalid kernel");
268 return get(kernel.getNameAttr(), kernel.getFunctionType(),
269 kernel.getAllArgAttrs(), metadata);
274 FunctionOpInterface kernel,
275 DictionaryAttr metadata) {
276 assert(kernel &&
"invalid kernel");
278 kernel.getAllArgAttrs(), metadata);
282KernelMetadataAttr::appendMetadata(ArrayRef<NamedAttribute> attrs)
const {
285 NamedAttrList attrList;
286 if (DictionaryAttr dict = getMetadata())
289 return KernelMetadataAttr::get(getName(), getFunctionType(),
getArgAttrs(),
295 StringAttr name, Type functionType,
296 ArrayAttr argAttrs, DictionaryAttr metadata) {
298 return emitError() <<
"the kernel name can't be empty";
300 if (llvm::any_of(argAttrs, [](Attribute attr) {
301 return !llvm::isa<DictionaryAttr>(attr);
304 <<
"all attributes in the array must be a dictionary attribute";
313KernelTableAttr KernelTableAttr::get(MLIRContext *context,
314 ArrayRef<KernelMetadataAttr> kernels,
317 assert((!isSorted || llvm::is_sorted(kernels)) &&
318 "expected a sorted kernel array");
320 if (isSorted || llvm::is_sorted(kernels))
321 return Base::get(context, kernels);
323 SmallVector<KernelMetadataAttr> kernelsTmp(kernels);
324 llvm::array_pod_sort(kernelsTmp.begin(), kernelsTmp.end());
325 return Base::get(context, kernelsTmp);
328KernelTableAttr KernelTableAttr::getChecked(
330 ArrayRef<KernelMetadataAttr> kernels,
bool isSorted) {
332 assert((!isSorted || llvm::is_sorted(kernels)) &&
333 "expected a sorted kernel array");
335 if (isSorted || llvm::is_sorted(kernels))
336 return Base::getChecked(
emitError, context, kernels);
338 SmallVector<KernelMetadataAttr> kernelsTmp(kernels);
339 llvm::array_pod_sort(kernelsTmp.begin(), kernelsTmp.end());
340 return Base::getChecked(
emitError, context, kernelsTmp);
345 ArrayRef<KernelMetadataAttr> kernels) {
346 if (kernels.size() < 2)
349 if (std::adjacent_find(kernels.begin(), kernels.end(),
350 [](KernelMetadataAttr l, KernelMetadataAttr r) {
351 return l.getName() == r.getName();
352 }) != kernels.end()) {
353 return emitError() <<
"expected all kernels to be uniquely named";
358KernelMetadataAttr KernelTableAttr::lookup(StringRef key)
const {
360 return found ? *iterator : KernelMetadataAttr();
363KernelMetadataAttr KernelTableAttr::lookup(StringAttr key)
const {
365 return found ? *iterator : KernelMetadataAttr();
445 return CompilationTarget::Fatbin;
448std::pair<llvm::BumpPtrAllocator, SmallVector<const char *>>
450 std::pair<llvm::BumpPtrAllocator, SmallVector<const char *>>
options;
451 llvm::StringSaver stringSaver(
options.first);
457 if (!opts.empty() && opts.front() ==
'"' && opts.back() ==
'"')
458 opts.consume_front(
"\""), opts.consume_back(
"\"");
459 if (!opts.empty() && opts.front() ==
'\'' && opts.back() ==
'\'')
460 opts.consume_front(
"'"), opts.consume_back(
"'");
462 llvm::cl::TokenizeWindowsCommandLine(opts, stringSaver,
options.second,
465 llvm::cl::TokenizeGNUCommandLine(opts, stringSaver,
options.second,
471std::pair<llvm::BumpPtrAllocator, SmallVector<const char *>>
476std::pair<llvm::BumpPtrAllocator, SmallVector<const char *>>
478 size_t startPos =
cmdOptions.find(startsWith);
479 if (startPos == std::string::npos)
490#include "mlir/Dialect/GPU/IR/GPUOpsEnums.cpp.inc"
492#define GET_ATTRDEF_CLASSES
493#include "mlir/Dialect/GPU/IR/GPUOpsAttributes.cpp.inc"
496template <
typename... Attrs>
497void registerAttributeStorageImpl(
MLIRContext *context) {
503 registerAttributeStorageImpl<
504#define GET_ATTRDEF_LIST
505#include "mlir/Dialect/GPU/IR/GPUOpsAttributes.cpp.inc"
509#include "mlir/Dialect/GPU/IR/CompilationAttrInterfaces.cpp.inc"
static llvm::ManagedStatic< PassManagerOptions > options
#define MLIR_DEFINE_EXPLICIT_TYPE_ID(CLASS_NAME)
virtual ParseResult parseOptionalKeyword(StringRef keyword)=0
Parse the given keyword if present.
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
virtual ParseResult parseEqual()=0
Parse a = token.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
Attributes are known-constant values of operations.
This class represents a diagnostic that is inflight and set to be reported.
MLIRContext is the top-level object for a collection of MLIR operations.
DictionaryAttr getDictionary(MLIRContext *context) const
Return a dictionary attribute for the underlying dictionary.
void append(StringRef name, Attribute attr)
Add an attribute with the specified name.
This class allows for representing and managing the symbol table used by operations with the 'SymbolT...
This class provides an efficient unique identifier for a specific C++ type.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
bool isSignedInteger() const
Return true if this is a signed integer type (with the specified width).
bool isUnsignedInteger() const
Return true if this is an unsigned integer type (with the specified width).
bool isInteger() const
Return true if this is an integer type (with the specified width).
static void registerAttribute(MLIRContext *ctx)
Register an attribute instance T with the uniquer.
static ConcreteType get(MLIRContext *ctx, Args &&...args)
static ConcreteType getChecked(const Location &loc, Args &&...args)
ImplType * getImpl() const
MMAMatrix represents a matrix held by a subgroup for matrix-matrix multiply accumulate operations.
ArrayRef< int64_t > getShape() const
Get shape of the matrix.
static MMAMatrixType get(ArrayRef< int64_t > shape, Type elementType, StringRef operand)
Get MMAMatrixType and verify construction Invariants.
Type getElementType() const
Get elementType of a single element.
static bool isValidElementType(Type elementType)
Check if a type is valid a MMAMatrixType elementType.
static LogicalResult verifyInvariants(function_ref< InFlightDiagnostic()> emitError, ArrayRef< int64_t > shape, Type elementType, StringRef operand)
Verify that shape and elementType are actually allowed for the MMAMatrixType.
StringRef getOperand() const
The general form of operation this type supports is given by the equation C += A*B.
static MMAMatrixType getChecked(function_ref< InFlightDiagnostic()> emitError, ArrayRef< int64_t > shape, Type elementType, StringRef operand)
Get MMAMatrixType at a particular location and verify construction Invariants.
unsigned getNumDims() const
Get number of dims.
This class serves as an opaque interface for passing options to the TargetAttrInterface methods.
function_ref< void(llvm::Module &)> optimizedLlvmIRCallback
Callback invoked with LLVM IR for the device module after LLVM optimizations but before codegen.
function_ref< void(StringRef)> getISACallback() const
Returns the callback invoked with the target ISA for the device, for example PTX assembly.
TypeID getTypeID() const
Returns the typeID.
std::string toolkitPath
Path to the target toolkit.
SymbolTable * getSymbolTable() const
Returns the result of the getSymbolTableCallback callback or a nullptr if no callback was provided.
StringRef getELFSection() const
Returns the ELF section.
StringRef getCmdOptions() const
Returns the command line options.
std::string cmdOptions
An optional set of command line options to be used by the compilation process.
function_ref< void(StringRef)> isaCallback
Callback invoked with the target ISA for the device, for example PTX assembly.
CompilationTarget compilationTarget
Compilation process target format.
std::pair< llvm::BumpPtrAllocator, SmallVector< const char * > > tokenizeCmdOptions() const
Returns a tokenization of the command line options.
function_ref< void(llvm::Module &)> initialLlvmIRCallback
Callback invoked with the initial LLVM IR for the device module.
ArrayRef< Attribute > getLibrariesToLink() const
Returns the LLVM libraries to link to.
TargetOptions(StringRef toolkitPath={}, ArrayRef< Attribute > librariesToLink={}, StringRef cmdOptions={}, StringRef elfSection={}, CompilationTarget compilationTarget=getDefaultCompilationTarget(), function_ref< SymbolTable *()> getSymbolTableCallback={}, function_ref< void(llvm::Module &)> initialLlvmIRCallback={}, function_ref< void(llvm::Module &)> linkedLlvmIRCallback={}, function_ref< void(llvm::Module &)> optimizedLlvmIRCallback={}, function_ref< void(StringRef)> isaCallback={})
Constructor initializing the toolkit path, the list of files to link to, extra command line options,...
function_ref< void(llvm::Module &)> getOptimizedLlvmIRCallback() const
Returns the callback invoked with LLVM IR for the device module after LLVM optimizations but before c...
std::pair< llvm::BumpPtrAllocator, SmallVector< const char * > > tokenizeAndRemoveSuffixCmdOptions(llvm::StringRef startsWith)
Returns a tokenization of the substr of the command line options that starts with startsWith and ends...
StringRef getToolkitPath() const
Returns the toolkit path.
SmallVector< Attribute > librariesToLink
List of files to link with the LLVM module.
function_ref< void(llvm::Module &)> linkedLlvmIRCallback
Callback invoked with LLVM IR for the device module after linking the device libraries.
function_ref< void(llvm::Module &)> getInitialLlvmIRCallback() const
Returns the callback invoked with the initial LLVM IR for the device module.
function_ref< SymbolTable *()> getSymbolTableCallback
Callback for obtaining the parent symbol table of all the GPU modules being serialized.
static CompilationTarget getDefaultCompilationTarget()
Returns the default compilation target: CompilationTarget::Fatbin.
function_ref< void(llvm::Module &)> getLinkedLlvmIRCallback() const
Returns the callback invoked with LLVM IR for the device module after linking the device libraries.
std::string elfSection
ELF Section where the binary needs to be located.
CompilationTarget getCompilationTarget() const
Returns the compilation target.
ArrayRef< NamedAttribute > getArgAttrs(FunctionOpInterface op, unsigned index)
Return all of the attributes for the argument at 'index'.
void registerAttributeStorage(MLIRContext *context)
Register storage whose definitions are private to MLIRGPUBase.
std::pair< IteratorT, bool > findAttrSorted(IteratorT first, IteratorT last, StringRef name)
Using llvm::lower_bound requires an extra string comparison to check whether the returned iterator po...
Include the generated interface declarations.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
auto getChecked(function_ref< InFlightDiagnostic()> emitError, MLIRContext *context, Ts &&...params)
Helper method analogous to get, but uses getChecked when available to allow graceful failure on inval...
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
llvm::function_ref< Fn > function_ref