21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/Sequence.h"
23#include "llvm/ADT/StringExtras.h"
24#include "llvm/ADT/TypeSwitch.h"
25#include "llvm/ADT/bit.h"
26#include "llvm/Support/Debug.h"
30#define DEBUG_TYPE "spirv-serialization"
37 if (
auto selectionOp = dyn_cast<spirv::SelectionOp>(op))
38 return selectionOp.getMergeBlock();
39 if (
auto loopOp = dyn_cast<spirv::LoopOp>(op))
40 return loopOp.getMergeBlock();
51 if (
auto loopOp = dyn_cast<spirv::LoopOp>(block->
getParentOp())) {
55 while ((op = op->getPrevNode()) !=
nullptr)
74 if (
auto floatAttr = dyn_cast<FloatAttr>(attr)) {
75 return floatAttr.getValue().isZero();
77 if (
auto boolAttr = dyn_cast<BoolAttr>(attr)) {
78 return !boolAttr.getValue();
80 if (
auto intAttr = dyn_cast<IntegerAttr>(attr)) {
81 return intAttr.getValue().isZero();
83 if (
auto splatElemAttr = dyn_cast<SplatElementsAttr>(attr)) {
86 if (
auto denseElemAttr = dyn_cast<DenseElementsAttr>(attr)) {
102 for (
Operation &op : llvm::drop_begin(ops))
103 if (
auto funcOp = dyn_cast<spirv::FuncOp>(op))
104 if (funcOp.getBody().empty())
115 uint32_t wordCount = 1 + operands.size();
117 binary.append(operands.begin(), operands.end());
122 : moduleOp(moduleOp), mlirBuilder(moduleOp.
getContext()), options(options) {
126 LLVM_DEBUG(llvm::dbgs() <<
"+++ starting serialization +++\n");
128 if (failed(moduleOp.verifyInvariants()))
133 if (failed(processExtension())) {
136 processMemoryModel();
143 for (
auto &op : *moduleOp.getBody()) {
144 if (failed(processOperation(&op))) {
149 LLVM_DEBUG(llvm::dbgs() <<
"+++ completed serialization +++\n");
155 extensions.size() + extendedSets.size() +
156 memoryModel.size() + entryPoints.size() +
157 executionModes.size() + decorations.size() +
158 typesGlobalValues.size() + functions.size() + graphs.size();
161 binary.reserve(moduleSize);
165 binary.append(capabilities.begin(), capabilities.end());
166 binary.append(extensions.begin(), extensions.end());
167 binary.append(extendedSets.begin(), extendedSets.end());
168 binary.append(memoryModel.begin(), memoryModel.end());
169 binary.append(entryPoints.begin(), entryPoints.end());
170 binary.append(executionModes.begin(), executionModes.end());
171 binary.append(debug.begin(), debug.end());
172 binary.append(names.begin(), names.end());
173 binary.append(decorations.begin(), decorations.end());
174 binary.append(typesGlobalValues.begin(), typesGlobalValues.end());
175 binary.append(functions.begin(), functions.end());
176 binary.append(graphs.begin(), graphs.end());
177 binary.append(graphsDebugInfo.begin(), graphsDebugInfo.end());
182 os <<
"\n= Value <id> Map =\n\n";
183 for (
auto valueIDPair : valueIDMap) {
184 Value val = valueIDPair.first;
185 os <<
" " << val <<
" "
186 <<
"id = " << valueIDPair.second <<
' ';
188 os <<
"from op '" << op->getName() <<
"'";
189 }
else if (
auto arg = dyn_cast<BlockArgument>(val)) {
190 Block *block = arg.getOwner();
191 os <<
"from argument of block " << block <<
' ';
203uint32_t Serializer::getOrCreateFunctionID(StringRef fnName) {
204 auto funcID = funcIDMap.lookup(fnName);
206 funcID = getNextID();
207 funcIDMap[fnName] = funcID;
212void Serializer::processCapability() {
213 for (
auto cap : moduleOp.getVceTriple()->getCapabilities())
215 {
static_cast<uint32_t
>(cap)});
218void Serializer::addLongCompositesCapability() {
219 if (longCompositesEmitted)
221 longCompositesEmitted =
true;
222 auto vceTriple = moduleOp.getVceTriple();
223 if (!llvm::is_contained(vceTriple->getCapabilities(),
224 spirv::Capability::LongCompositesINTEL))
226 capabilities, spirv::Opcode::OpCapability,
227 {
static_cast<uint32_t
>(spirv::Capability::LongCompositesINTEL)});
228 if (!llvm::is_contained(vceTriple->getExtensions(),
229 spirv::Extension::SPV_INTEL_long_composites)) {
230 SmallVector<uint32_t, 8> extName;
233 spirv::stringifyExtension(spirv::Extension::SPV_INTEL_long_composites));
238void Serializer::encodeInstructionWithContinuationInto(
239 SmallVectorImpl<uint32_t> &binary, spirv::Opcode op,
240 ArrayRef<uint32_t> operands) {
246 std::optional<spirv::Opcode> continuationOp =
248 assert(continuationOp &&
"op is not a splittable composite/struct opcode");
252 for (ArrayRef<uint32_t> rest = operands.drop_front(chunk); !rest.empty();
253 rest = rest.drop_front(std::min<size_t>(rest.size(), chunk))) {
257 addLongCompositesCapability();
260void Serializer::processDebugInfo() {
261 if (!options.emitDebugInfo)
263 auto fileLoc = dyn_cast<FileLineColLoc>(moduleOp.getLoc());
264 auto fileName = fileLoc ? fileLoc.getFilename().strref() :
"<unknown>";
265 fileID = getNextID();
266 SmallVector<uint32_t, 16> operands;
267 operands.push_back(fileID);
273LogicalResult Serializer::processExtension() {
274 llvm::SmallVector<uint32_t, 16> extName;
275 llvm::SmallSet<Extension, 4> deducedExts(
276 llvm::from_range, moduleOp.getVceTriple()->getExtensions());
277 auto nonSemanticInfoExt = spirv::Extension::SPV_KHR_non_semantic_info;
278 if (options.emitDebugInfo && !deducedExts.contains(nonSemanticInfoExt)) {
280 if (!is_contained(targetEnvAttr.getExtensions(), nonSemanticInfoExt))
281 return moduleOp.emitError(
282 "SPV_KHR_non_semantic_info extension not available");
283 deducedExts.insert(nonSemanticInfoExt);
285 for (spirv::Extension ext : deducedExts) {
293void Serializer::processMemoryModel() {
294 auto mm =
static_cast<uint32_t
>(moduleOp.getMemoryModel());
295 auto am =
static_cast<uint32_t
>(moduleOp.getAddressingModel());
303 if (attrName ==
"fp_fast_math_mode")
304 return "FPFastMathMode";
306 if (attrName ==
"fp_rounding_mode")
307 return "FPRoundingMode";
309 if (attrName ==
"cache_control_load_intel")
310 return "CacheControlLoadINTEL";
311 if (attrName ==
"cache_control_store_intel")
312 return "CacheControlStoreINTEL";
314 return llvm::convertToCamelFromSnakeCase(attrName,
true);
317template <
typename AttrTy,
typename EmitF>
320 StringRef attrName, EmitF emitter) {
321 auto arrayAttr = dyn_cast<ArrayAttr>(attrList);
323 return emitError(loc,
"expecting array attribute of ")
324 << attrName <<
" for " << stringifyDecoration(decoration);
326 if (arrayAttr.empty()) {
327 return emitError(loc,
"expecting non-empty array attribute of ")
328 << attrName <<
" for " << stringifyDecoration(decoration);
330 for (
Attribute attr : arrayAttr.getValue()) {
331 auto cacheControlAttr = dyn_cast<AttrTy>(attr);
332 if (!cacheControlAttr) {
333 return emitError(loc,
"expecting array attribute of ")
334 << attrName <<
" for " << stringifyDecoration(decoration);
338 if (failed(emitter(cacheControlAttr)))
344LogicalResult Serializer::processDecorationAttr(
Location loc, uint32_t resultID,
345 Decoration decoration,
348 switch (decoration) {
349 case spirv::Decoration::LinkageAttributes: {
352 auto linkageAttr = dyn_cast<spirv::LinkageAttributesAttr>(attr);
353 auto linkageName = linkageAttr.getLinkageName();
354 auto linkageType = linkageAttr.getLinkageType().getValue();
358 args.push_back(
static_cast<uint32_t
>(linkageType));
361 case spirv::Decoration::FPFastMathMode:
362 if (
auto intAttr = dyn_cast<FPFastMathModeAttr>(attr)) {
363 args.push_back(
static_cast<uint32_t
>(intAttr.getValue()));
366 return emitError(loc,
"expected FPFastMathModeAttr attribute for ")
367 << stringifyDecoration(decoration);
368 case spirv::Decoration::FPRoundingMode:
369 if (
auto intAttr = dyn_cast<FPRoundingModeAttr>(attr)) {
370 args.push_back(
static_cast<uint32_t
>(intAttr.getValue()));
373 return emitError(loc,
"expected FPRoundingModeAttr attribute for ")
374 << stringifyDecoration(decoration);
375 case spirv::Decoration::FuncParamAttr:
377 loc, decoration, attr,
"FunctionParameterAttribute",
378 [&](FunctionParameterAttributeAttr attr) {
379 return emitDecoration(resultID, decoration,
380 {
static_cast<uint32_t
>(attr.getValue())});
382 case spirv::Decoration::Alignment:
383 case spirv::Decoration::MaxByteOffset:
384 case spirv::Decoration::Binding:
385 case spirv::Decoration::DescriptorSet:
386 case spirv::Decoration::Location:
387 case spirv::Decoration::Index:
388 case spirv::Decoration::Offset:
389 case spirv::Decoration::XfbBuffer:
390 case spirv::Decoration::XfbStride:
391 if (
auto intAttr = dyn_cast<IntegerAttr>(attr)) {
392 args.push_back(intAttr.getValue().getZExtValue());
395 return emitError(loc,
"expected integer attribute for ")
396 << stringifyDecoration(decoration);
397 case spirv::Decoration::BuiltIn:
398 if (
auto strAttr = dyn_cast<StringAttr>(attr)) {
399 auto enumVal = spirv::symbolizeBuiltIn(strAttr.getValue());
401 args.push_back(
static_cast<uint32_t
>(*enumVal));
405 << stringifyDecoration(decoration) <<
" decoration attribute "
406 << strAttr.getValue();
408 return emitError(loc,
"expected string attribute for ")
409 << stringifyDecoration(decoration);
410 case spirv::Decoration::Aliased:
411 case spirv::Decoration::AliasedPointer:
412 case spirv::Decoration::Flat:
413 case spirv::Decoration::NonReadable:
414 case spirv::Decoration::NonWritable:
415 case spirv::Decoration::NoPerspective:
416 case spirv::Decoration::NoSignedWrap:
417 case spirv::Decoration::NoUnsignedWrap:
418 case spirv::Decoration::RelaxedPrecision:
419 case spirv::Decoration::Restrict:
420 case spirv::Decoration::RestrictPointer:
421 case spirv::Decoration::NoContraction:
422 case spirv::Decoration::Constant:
423 case spirv::Decoration::Block:
424 case spirv::Decoration::BufferBlock:
425 case spirv::Decoration::CPacked:
426 case spirv::Decoration::Invariant:
427 case spirv::Decoration::Patch:
428 case spirv::Decoration::Coherent:
429 case spirv::Decoration::Volatile:
430 case spirv::Decoration::SaturatedConversion:
433 if (isa<UnitAttr, DecorationAttr>(attr))
436 "expected unit attribute or decoration attribute for ")
437 << stringifyDecoration(decoration);
438 case spirv::Decoration::CacheControlLoadINTEL:
440 loc, decoration, attr,
"CacheControlLoadINTEL",
441 [&](CacheControlLoadINTELAttr attr) {
442 unsigned cacheLevel = attr.getCacheLevel();
443 LoadCacheControl loadCacheControl = attr.getLoadCacheControl();
444 return emitDecoration(
445 resultID, decoration,
446 {cacheLevel,
static_cast<uint32_t
>(loadCacheControl)});
448 case spirv::Decoration::CacheControlStoreINTEL:
450 loc, decoration, attr,
"CacheControlStoreINTEL",
451 [&](CacheControlStoreINTELAttr attr) {
452 unsigned cacheLevel = attr.getCacheLevel();
453 StoreCacheControl storeCacheControl = attr.getStoreCacheControl();
454 return emitDecoration(
455 resultID, decoration,
456 {cacheLevel,
static_cast<uint32_t
>(storeCacheControl)});
458 case spirv::Decoration::AlignmentId:
459 case spirv::Decoration::MaxByteOffsetId:
460 case spirv::Decoration::CounterBuffer: {
461 auto symRef = dyn_cast<FlatSymbolRefAttr>(attr);
463 return emitError(loc,
"expected symbol reference for ")
464 << stringifyDecoration(decoration);
465 StringRef symName = symRef.getValue();
466 uint32_t operandID = getVariableID(symName);
468 operandID = getSpecConstID(symName);
470 return emitError(loc,
"could not find <id> for symbol '")
471 << symName <<
"' referenced by "
472 << stringifyDecoration(decoration);
473 return emitDecorationId(resultID, decoration, {operandID});
476 return emitError(loc,
"unhandled decoration ")
477 << stringifyDecoration(decoration);
479 return emitDecoration(resultID, decoration, args);
482LogicalResult Serializer::processDecoration(Location loc, uint32_t resultID,
483 NamedAttribute attr) {
484 StringRef attrName = attr.
getName().strref();
486 std::optional<Decoration> decoration =
487 spirv::symbolizeDecoration(decorationName);
490 loc,
"non-argument attributes expected to have snake-case-ified "
491 "decoration name, unhandled attribute with name : ")
494 return processDecorationAttr(loc, resultID, *decoration, attr.
getValue());
497LogicalResult Serializer::processName(uint32_t resultID, StringRef name) {
498 assert(!name.empty() &&
"unexpected empty string for OpName");
499 if (!options.emitSymbolName)
502 SmallVector<uint32_t, 4> nameOperands;
503 nameOperands.push_back(resultID);
510LogicalResult Serializer::processTypeDecoration<spirv::ArrayType>(
514 return emitDecoration(resultID, spirv::Decoration::ArrayStride, {stride});
520LogicalResult Serializer::processTypeDecoration<spirv::RuntimeArrayType>(
524 return emitDecoration(resultID, spirv::Decoration::ArrayStride, {stride});
529LogicalResult Serializer::processMemberDecoration(
534 static_cast<uint32_t
>(memberDecoration.
decoration)});
550bool Serializer::isInterfaceStructPtrType(Type type)
const {
551 if (
auto ptrType = dyn_cast<spirv::PointerType>(type)) {
552 switch (ptrType.getStorageClass()) {
553 case spirv::StorageClass::PhysicalStorageBuffer:
554 case spirv::StorageClass::PushConstant:
555 case spirv::StorageClass::StorageBuffer:
556 case spirv::StorageClass::Uniform:
557 return isa<spirv::StructType>(ptrType.getPointeeType());
565LogicalResult Serializer::processType(Location loc, Type type,
570 return processTypeImpl(loc, type, typeID, serializationCtx);
574Serializer::processTypeImpl(Location loc, Type type, uint32_t &typeID,
586 IntegerType::SignednessSemantics::Signless);
589 typeID = getTypeID(type);
593 typeID = getNextID();
594 SmallVector<uint32_t, 4> operands;
596 operands.push_back(typeID);
597 auto typeEnum = spirv::Opcode::OpTypeVoid;
598 bool deferSerialization =
false;
600 if ((isa<FunctionType>(type) &&
601 succeeded(prepareFunctionType(loc, cast<FunctionType>(type), typeEnum,
603 (isa<GraphType>(type) &&
605 prepareGraphType(loc, cast<GraphType>(type), typeEnum, operands))) ||
606 succeeded(prepareBasicType(loc, type, typeID, typeEnum, operands,
607 deferSerialization, serializationCtx))) {
608 if (deferSerialization)
611 typeIDMap[type] = typeID;
613 if (typeEnum == spirv::Opcode::OpTypeStruct)
614 encodeInstructionWithContinuationInto(typesGlobalValues, typeEnum,
619 if (recursiveStructInfos.count(type) != 0) {
622 for (
auto &ptrInfo : recursiveStructInfos[type]) {
625 SmallVector<uint32_t, 4> ptrOperands;
626 ptrOperands.push_back(ptrInfo.pointerTypeID);
627 ptrOperands.push_back(
static_cast<uint32_t
>(ptrInfo.storageClass));
628 ptrOperands.push_back(typeIDMap[type]);
634 recursiveStructInfos[type].clear();
640 return emitError(loc,
"failed to process type: ") << type;
643LogicalResult Serializer::prepareBasicType(
644 Location loc, Type type, uint32_t resultID, spirv::Opcode &typeEnum,
645 SmallVectorImpl<uint32_t> &operands,
bool &deferSerialization,
647 deferSerialization =
false;
649 if (isVoidType(type)) {
650 typeEnum = spirv::Opcode::OpTypeVoid;
654 if (
auto intType = dyn_cast<IntegerType>(type)) {
655 if (intType.getWidth() == 1) {
656 typeEnum = spirv::Opcode::OpTypeBool;
660 typeEnum = spirv::Opcode::OpTypeInt;
661 operands.push_back(intType.getWidth());
666 operands.push_back(intType.isSigned() ? 1 : 0);
670 if (
auto floatType = dyn_cast<FloatType>(type)) {
671 typeEnum = spirv::Opcode::OpTypeFloat;
672 operands.push_back(floatType.getWidth());
673 if (floatType.isBF16()) {
674 operands.push_back(
static_cast<uint32_t
>(spirv::FPEncoding::BFloat16KHR));
676 if (floatType.isF8E4M3FN()) {
678 static_cast<uint32_t
>(spirv::FPEncoding::Float8E4M3EXT));
680 if (floatType.isF8E5M2()) {
682 static_cast<uint32_t
>(spirv::FPEncoding::Float8E5M2EXT));
684 if (isa<Float4E2M1FNType>(floatType))
686 static_cast<uint32_t
>(spirv::FPEncoding::Float4E2M1EXT));
687 if (isa<Float6E2M3FNType>(floatType))
689 static_cast<uint32_t
>(spirv::FPEncoding::Float6E2M3EXT));
690 if (isa<Float6E3M2FNType>(floatType))
692 static_cast<uint32_t
>(spirv::FPEncoding::Float6E3M2EXT));
693 if (isa<Float8E8M0FNUType>(floatType))
695 static_cast<uint32_t
>(spirv::FPEncoding::Float8UnsignedE8M0EXT));
700 if (
auto vectorType = dyn_cast<VectorType>(type)) {
701 uint32_t elementTypeID = 0;
702 if (
failed(processTypeImpl(loc, vectorType.getElementType(), elementTypeID,
703 serializationCtx))) {
706 typeEnum = spirv::Opcode::OpTypeVector;
707 operands.push_back(elementTypeID);
708 operands.push_back(vectorType.getNumElements());
712 if (
auto imageType = dyn_cast<spirv::ImageType>(type)) {
713 typeEnum = spirv::Opcode::OpTypeImage;
714 uint32_t sampledTypeID = 0;
715 if (
failed(processType(loc, imageType.getElementType(), sampledTypeID)))
718 llvm::append_values(operands, sampledTypeID,
719 static_cast<uint32_t
>(imageType.getDim()),
720 static_cast<uint32_t
>(imageType.getDepthInfo()),
721 static_cast<uint32_t
>(imageType.getArrayedInfo()),
722 static_cast<uint32_t
>(imageType.getSamplingInfo()),
723 static_cast<uint32_t
>(imageType.getSamplerUseInfo()),
724 static_cast<uint32_t
>(imageType.getImageFormat()));
728 if (
auto arrayType = dyn_cast<spirv::ArrayType>(type)) {
729 typeEnum = spirv::Opcode::OpTypeArray;
730 uint32_t elementTypeID = 0;
731 if (
failed(processTypeImpl(loc, arrayType.getElementType(), elementTypeID,
732 serializationCtx))) {
735 operands.push_back(elementTypeID);
736 if (
auto elementCountID = prepareConstantInt(
737 loc, mlirBuilder.getI32IntegerAttr(arrayType.getNumElements()))) {
738 operands.push_back(elementCountID);
740 return processTypeDecoration(loc, arrayType, resultID);
743 if (
auto ptrType = dyn_cast<spirv::PointerType>(type)) {
744 uint32_t pointeeTypeID = 0;
745 spirv::StructType pointeeStruct =
746 dyn_cast<spirv::StructType>(ptrType.getPointeeType());
749 serializationCtx.count(pointeeStruct.
getIdentifier()) != 0) {
754 SmallVector<uint32_t, 2> forwardPtrOperands;
755 forwardPtrOperands.push_back(resultID);
756 forwardPtrOperands.push_back(
757 static_cast<uint32_t
>(ptrType.getStorageClass()));
760 spirv::Opcode::OpTypeForwardPointer,
772 deferSerialization =
true;
776 recursiveStructInfos[structType].push_back(
777 {resultID, ptrType.getStorageClass()});
779 if (
failed(processTypeImpl(loc, ptrType.getPointeeType(), pointeeTypeID,
784 typeEnum = spirv::Opcode::OpTypePointer;
785 operands.push_back(
static_cast<uint32_t
>(ptrType.getStorageClass()));
786 operands.push_back(pointeeTypeID);
791 if (isInterfaceStructPtrType(ptrType)) {
792 auto structType = cast<spirv::StructType>(ptrType.getPointeeType());
793 if (!structType.hasDecoration(spirv::Decoration::Block) &&
794 !structType.hasDecoration(spirv::Decoration::BufferBlock))
795 if (
failed(emitDecoration(getTypeID(pointeeStruct),
796 spirv::Decoration::Block)))
797 return emitError(loc,
"cannot decorate ")
798 << pointeeStruct <<
" with Block decoration";
804 if (
auto runtimeArrayType = dyn_cast<spirv::RuntimeArrayType>(type)) {
805 uint32_t elementTypeID = 0;
806 if (
failed(processTypeImpl(loc, runtimeArrayType.getElementType(),
807 elementTypeID, serializationCtx))) {
810 typeEnum = spirv::Opcode::OpTypeRuntimeArray;
811 operands.push_back(elementTypeID);
812 return processTypeDecoration(loc, runtimeArrayType, resultID);
815 if (isa<spirv::SamplerType>(type)) {
816 typeEnum = spirv::Opcode::OpTypeSampler;
820 if (isa<spirv::NamedBarrierType>(type)) {
821 typeEnum = spirv::Opcode::OpTypeNamedBarrier;
825 if (
auto untypedPtrType = dyn_cast<spirv::UntypedPointerType>(type)) {
826 typeEnum = spirv::Opcode::OpTypeUntypedPointerKHR;
827 operands.push_back(
static_cast<uint32_t
>(untypedPtrType.getStorageClass()));
831 if (
auto sampledImageType = dyn_cast<spirv::SampledImageType>(type)) {
832 typeEnum = spirv::Opcode::OpTypeSampledImage;
833 uint32_t imageTypeID = 0;
835 processType(loc, sampledImageType.getImageType(), imageTypeID))) {
838 operands.push_back(imageTypeID);
842 if (
auto structType = dyn_cast<spirv::StructType>(type)) {
843 if (structType.isIdentified()) {
844 if (
failed(processName(resultID, structType.getIdentifier())))
846 serializationCtx.insert(structType.getIdentifier());
849 bool hasOffset = structType.hasOffset();
850 for (
auto elementIndex :
851 llvm::seq<uint32_t>(0, structType.getNumElements())) {
852 uint32_t elementTypeID = 0;
853 if (
failed(processTypeImpl(loc, structType.getElementType(elementIndex),
854 elementTypeID, serializationCtx))) {
857 operands.push_back(elementTypeID);
859 auto intType = IntegerType::get(structType.getContext(), 32);
861 spirv::StructType::MemberDecorationInfo offsetDecoration{
862 elementIndex, spirv::Decoration::Offset,
863 IntegerAttr::get(intType,
864 structType.getMemberOffset(elementIndex))};
865 if (
failed(processMemberDecoration(resultID, offsetDecoration))) {
866 return emitError(loc,
"cannot decorate ")
867 << elementIndex <<
"-th member of " << structType
868 <<
" with its offset";
872 SmallVector<spirv::StructType::MemberDecorationInfo, 4> memberDecorations;
873 structType.getMemberDecorations(memberDecorations);
875 for (
auto &memberDecoration : memberDecorations) {
876 if (
failed(processMemberDecoration(resultID, memberDecoration))) {
877 return emitError(loc,
"cannot decorate ")
878 <<
static_cast<uint32_t
>(memberDecoration.
memberIndex)
879 <<
"-th member of " << structType <<
" with "
880 << stringifyDecoration(memberDecoration.
decoration);
884 SmallVector<spirv::StructType::StructDecorationInfo, 1> structDecorations;
885 structType.getStructDecorations(structDecorations);
887 for (spirv::StructType::StructDecorationInfo &structDecoration :
889 if (
failed(processDecorationAttr(loc, resultID,
890 structDecoration.decoration,
891 structDecoration.decorationValue))) {
892 return emitError(loc,
"cannot decorate struct ")
893 << structType <<
" with "
894 << stringifyDecoration(structDecoration.decoration);
898 typeEnum = spirv::Opcode::OpTypeStruct;
900 if (structType.isIdentified())
901 serializationCtx.remove(structType.getIdentifier());
906 if (
auto cooperativeMatrixType =
907 dyn_cast<spirv::CooperativeMatrixType>(type)) {
908 uint32_t elementTypeID = 0;
909 if (
failed(processTypeImpl(loc, cooperativeMatrixType.getElementType(),
910 elementTypeID, serializationCtx))) {
913 typeEnum = spirv::Opcode::OpTypeCooperativeMatrixKHR;
914 auto getConstantOp = [&](uint32_t id) {
915 auto attr = IntegerAttr::get(IntegerType::get(type.
getContext(), 32),
id);
916 return prepareConstantInt(loc, attr);
919 operands, elementTypeID,
920 getConstantOp(
static_cast<uint32_t
>(cooperativeMatrixType.getScope())),
921 getConstantOp(cooperativeMatrixType.getRows()),
922 getConstantOp(cooperativeMatrixType.getColumns()),
923 getConstantOp(
static_cast<uint32_t
>(cooperativeMatrixType.getUse())));
927 if (
auto matrixType = dyn_cast<spirv::MatrixType>(type)) {
928 uint32_t elementTypeID = 0;
929 if (
failed(processTypeImpl(loc, matrixType.getColumnType(), elementTypeID,
930 serializationCtx))) {
933 typeEnum = spirv::Opcode::OpTypeMatrix;
934 llvm::append_values(operands, elementTypeID, matrixType.getNumColumns());
938 if (
auto tensorArmType = dyn_cast<TensorArmType>(type)) {
939 uint32_t elementTypeID = 0;
941 uint32_t shapeID = 0;
943 if (
failed(processTypeImpl(loc, tensorArmType.getElementType(),
944 elementTypeID, serializationCtx))) {
947 if (tensorArmType.hasRank()) {
948 ArrayRef<int64_t> dims = tensorArmType.getShape();
950 rankID = prepareConstantInt(loc, mlirBuilder.getI32IntegerAttr(rank));
955 bool shaped = llvm::all_of(dims, [](
const auto &dim) {
return dim > 0; });
956 if (rank > 0 && shaped) {
957 auto I32Type = IntegerType::get(type.
getContext(), 32);
960 SmallVector<uint64_t, 1> index(rank);
961 shapeID = prepareDenseElementsConstant(
963 mlirBuilder.getI32TensorAttr(SmallVector<int32_t>(dims)), 0,
966 shapeID = prepareArrayConstant(
968 mlirBuilder.getI32ArrayAttr(SmallVector<int32_t>(dims)));
975 typeEnum = spirv::Opcode::OpTypeTensorARM;
976 operands.push_back(elementTypeID);
979 operands.push_back(rankID);
982 operands.push_back(shapeID);
987 return emitError(loc,
"unhandled type in serialization: ") << type;
991Serializer::prepareFunctionType(Location loc, FunctionType type,
992 spirv::Opcode &typeEnum,
993 SmallVectorImpl<uint32_t> &operands) {
994 typeEnum = spirv::Opcode::OpTypeFunction;
995 assert(type.getNumResults() <= 1 &&
996 "serialization supports only a single return value");
997 uint32_t resultID = 0;
999 loc, type.getNumResults() == 1 ? type.getResult(0) : getVoidType(),
1003 operands.push_back(resultID);
1004 for (
auto &res : type.getInputs()) {
1005 uint32_t argTypeID = 0;
1006 if (
failed(processType(loc, res, argTypeID))) {
1009 operands.push_back(argTypeID);
1015Serializer::prepareGraphType(Location loc, GraphType type,
1016 spirv::Opcode &typeEnum,
1017 SmallVectorImpl<uint32_t> &operands) {
1018 typeEnum = spirv::Opcode::OpTypeGraphARM;
1019 assert(type.getNumResults() >= 1 &&
1020 "serialization requires at least a return value");
1022 operands.push_back(type.getNumInputs());
1024 for (Type argType : type.getInputs()) {
1025 uint32_t argTypeID = 0;
1026 if (
failed(processType(loc, argType, argTypeID)))
1028 operands.push_back(argTypeID);
1031 for (Type resType : type.getResults()) {
1032 uint32_t resTypeID = 0;
1033 if (
failed(processType(loc, resType, resTypeID)))
1035 operands.push_back(resTypeID);
1045uint32_t Serializer::prepareConstant(Location loc, Type constType,
1046 Attribute valueAttr) {
1047 if (
auto id = prepareConstantScalar(loc, valueAttr)) {
1054 if (
auto id = getConstantID(valueAttr)) {
1058 uint32_t typeID = 0;
1059 if (
failed(processType(loc, constType, typeID))) {
1063 uint32_t resultID = 0;
1064 if (
auto attr = dyn_cast<DenseElementsAttr>(valueAttr)) {
1065 int rank = dyn_cast<ShapedType>(attr.getType()).getRank();
1066 SmallVector<uint64_t, 4> index(rank);
1067 resultID = prepareDenseElementsConstant(loc, constType, attr,
1069 }
else if (
auto arrayAttr = dyn_cast<ArrayAttr>(valueAttr)) {
1070 resultID = prepareArrayConstant(loc, constType, arrayAttr);
1071 }
else if (isa<spirv::NullAttr>(valueAttr)) {
1072 resultID = getNextID();
1074 {typeID, resultID});
1077 if (resultID == 0) {
1078 emitError(loc,
"cannot serialize attribute: ") << valueAttr;
1082 constIDMap[valueAttr] = resultID;
1086uint32_t Serializer::prepareArrayConstant(Location loc, Type constType,
1088 uint32_t typeID = 0;
1089 if (
failed(processType(loc, constType, typeID))) {
1093 uint32_t resultID = getNextID();
1094 SmallVector<uint32_t, 4> operands = {typeID, resultID};
1095 operands.reserve(attr.size() + 2);
1096 spirv::CompositeType compositeType = cast<spirv::CompositeType>(constType);
1097 for (
auto [idx, elementAttr] : llvm::enumerate(attr)) {
1098 if (uint32_t elementID = prepareConstant(
1100 operands.push_back(elementID);
1105 encodeInstructionWithContinuationInto(
1106 typesGlobalValues, spirv::Opcode::OpConstantComposite, operands);
1114Serializer::prepareDenseElementsConstant(Location loc, Type constType,
1115 DenseElementsAttr valueAttr,
int dim,
1116 MutableArrayRef<uint64_t> index) {
1117 auto shapedType = dyn_cast<ShapedType>(valueAttr.
getType());
1118 assert(dim <= shapedType.getRank());
1119 if (shapedType.getRank() == dim) {
1120 if (
auto attr = dyn_cast<DenseIntElementsAttr>(valueAttr)) {
1121 return attr.getType().getElementType().isInteger(1)
1122 ? prepareConstantBool(loc, attr.getValues<BoolAttr>()[index])
1123 : prepareConstantInt(loc,
1124 attr.getValues<IntegerAttr>()[index]);
1126 if (
auto attr = dyn_cast<DenseFPElementsAttr>(valueAttr)) {
1127 return prepareConstantFp(loc, attr.getValues<FloatAttr>()[index]);
1132 uint32_t typeID = 0;
1133 if (
failed(processType(loc, constType, typeID))) {
1137 int64_t numberOfConstituents = shapedType.getDimSize(dim);
1138 uint32_t resultID = getNextID();
1139 SmallVector<uint32_t, 4> operands = {typeID, resultID};
1140 auto elementType = cast<spirv::CompositeType>(constType).getElementType(0);
1141 if (
auto tensorArmType = dyn_cast<spirv::TensorArmType>(constType)) {
1142 ArrayRef<int64_t> innerShape = tensorArmType.getShape().drop_front();
1143 if (!innerShape.empty())
1151 if (isa<spirv::CooperativeMatrixType>(constType)) {
1155 "cannot serialize a non-splat value for a cooperative matrix type");
1160 operands.reserve(3);
1163 if (
auto elementID = prepareDenseElementsConstant(
1164 loc, elementType, valueAttr, shapedType.getRank(), index)) {
1165 operands.push_back(elementID);
1169 }
else if (isa<spirv::TensorArmType>(constType) &&
isZeroValue(valueAttr)) {
1171 {typeID, resultID});
1174 operands.reserve(numberOfConstituents + 2);
1175 for (
int i = 0; i < numberOfConstituents; ++i) {
1177 if (
auto elementID = prepareDenseElementsConstant(
1178 loc, elementType, valueAttr, dim + 1, index)) {
1179 operands.push_back(elementID);
1185 encodeInstructionWithContinuationInto(
1186 typesGlobalValues, spirv::Opcode::OpConstantComposite, operands);
1191uint32_t Serializer::prepareConstantScalar(Location loc, Attribute valueAttr,
1193 if (
auto floatAttr = dyn_cast<FloatAttr>(valueAttr)) {
1194 return prepareConstantFp(loc, floatAttr, isSpec);
1196 if (
auto boolAttr = dyn_cast<BoolAttr>(valueAttr)) {
1197 return prepareConstantBool(loc, boolAttr, isSpec);
1199 if (
auto intAttr = dyn_cast<IntegerAttr>(valueAttr)) {
1200 return prepareConstantInt(loc, intAttr, isSpec);
1206uint32_t Serializer::prepareConstantBool(Location loc, BoolAttr boolAttr,
1210 if (
auto id = getConstantID(boolAttr)) {
1216 uint32_t typeID = 0;
1217 if (
failed(processType(loc, cast<IntegerAttr>(boolAttr).
getType(), typeID))) {
1221 auto resultID = getNextID();
1223 ? (isSpec ? spirv::Opcode::OpSpecConstantTrue
1224 : spirv::Opcode::OpConstantTrue)
1225 : (isSpec ? spirv::Opcode::OpSpecConstantFalse
1226 : spirv::Opcode::OpConstantFalse);
1230 constIDMap[boolAttr] = resultID;
1235uint32_t Serializer::prepareConstantInt(Location loc, IntegerAttr intAttr,
1239 if (
auto id = getConstantID(intAttr)) {
1245 uint32_t typeID = 0;
1246 if (
failed(processType(loc, intAttr.getType(), typeID))) {
1250 auto resultID = getNextID();
1251 APInt value = intAttr.getValue();
1252 unsigned bitwidth = value.getBitWidth();
1253 bool isSigned = intAttr.getType().isSignedInteger();
1255 isSpec ? spirv::Opcode::OpSpecConstant : spirv::Opcode::OpConstant;
1268 word =
static_cast<int32_t
>(value.getSExtValue());
1270 word =
static_cast<uint32_t
>(value.getZExtValue());
1282 words = llvm::bit_cast<DoubleWord>(value.getSExtValue());
1284 words = llvm::bit_cast<DoubleWord>(value.getZExtValue());
1287 {typeID, resultID, words.word1, words.word2});
1290 std::string valueStr;
1291 llvm::raw_string_ostream rss(valueStr);
1292 value.print(rss,
false);
1295 << bitwidth <<
"-bit integer literal: " << valueStr;
1301 constIDMap[intAttr] = resultID;
1306uint32_t Serializer::prepareGraphConstantId(Location loc, Type graphConstType,
1307 IntegerAttr intAttr) {
1309 if (uint32_t
id = getGraphConstantARMId(intAttr)) {
1314 uint32_t typeID = 0;
1315 if (
failed(processType(loc, graphConstType, typeID))) {
1319 uint32_t resultID = getNextID();
1320 APInt value = intAttr.getValue();
1321 unsigned bitwidth = value.getBitWidth();
1322 if (bitwidth > 32) {
1323 emitError(loc,
"Too wide attribute for OpGraphConstantARM: ")
1324 << bitwidth <<
" bits";
1327 bool isSigned = value.isSignedIntN(bitwidth);
1331 word =
static_cast<int32_t
>(value.getSExtValue());
1333 word =
static_cast<uint32_t
>(value.getZExtValue());
1336 {typeID, resultID, word});
1337 graphConstIDMap[intAttr] = resultID;
1341uint32_t Serializer::prepareConstantFp(Location loc, FloatAttr floatAttr,
1345 if (
auto id = getConstantID(floatAttr)) {
1351 uint32_t typeID = 0;
1352 if (
failed(processType(loc, floatAttr.getType(), typeID))) {
1356 auto resultID = getNextID();
1357 APFloat value = floatAttr.getValue();
1358 const llvm::fltSemantics *semantics = &value.getSemantics();
1361 isSpec ? spirv::Opcode::OpSpecConstant : spirv::Opcode::OpConstant;
1363 if (semantics == &APFloat::IEEEsingle()) {
1364 uint32_t word = llvm::bit_cast<uint32_t>(value.convertToFloat());
1366 }
else if (semantics == &APFloat::IEEEdouble()) {
1370 } words = llvm::bit_cast<DoubleWord>(value.convertToDouble());
1372 {typeID, resultID, words.word1, words.word2});
1373 }
else if (llvm::is_contained(
1374 {&APFloat::IEEEhalf(), &APFloat::BFloat(),
1375 &APFloat::Float8E4M3FN(), &APFloat::Float8E5M2(),
1376 &APFloat::Float4E2M1FN(), &APFloat::Float6E2M3FN(),
1377 &APFloat::Float6E3M2FN(), &APFloat::Float8E8M0FNU()},
1380 static_cast<uint32_t
>(value.bitcastToAPInt().getZExtValue());
1383 std::string valueStr;
1384 llvm::raw_string_ostream rss(valueStr);
1388 << floatAttr.getType() <<
"-typed float literal: " << valueStr;
1393 constIDMap[floatAttr] = resultID;
1402 if (
auto typedAttr = dyn_cast<TypedAttr>(attr)) {
1403 return typedAttr.getType();
1406 if (
auto arrayAttr = dyn_cast<ArrayAttr>(attr)) {
1413uint32_t Serializer::prepareConstantCompositeReplicate(
Location loc,
1416 std::pair<Attribute, Type> valueTypePair{valueAttr, resultType};
1417 if (uint32_t
id = getConstantCompositeReplicateID(valueTypePair)) {
1421 uint32_t typeID = 0;
1422 if (
failed(processType(loc, resultType, typeID))) {
1430 auto compositeType = dyn_cast<CompositeType>(resultType);
1435 uint32_t constandID;
1436 if (elementType == valueType) {
1437 constandID = prepareConstant(loc, elementType, valueAttr);
1439 constandID = prepareConstantCompositeReplicate(loc, elementType, valueAttr);
1442 uint32_t resultID = getNextID();
1443 if (dyn_cast<spirv::TensorArmType>(resultType) &&
isZeroValue(valueAttr)) {
1445 {typeID, resultID});
1448 spirv::Opcode::OpConstantCompositeReplicateEXT,
1449 {typeID, resultID, constandID});
1452 constCompositeReplicateIDMap[valueTypePair] = resultID;
1460uint32_t Serializer::getOrCreateBlockID(
Block *block) {
1461 if (uint32_t
id = getBlockID(block))
1463 return blockIDMap[block] = getNextID();
1467void Serializer::printBlock(
Block *block, raw_ostream &os) {
1468 os <<
"block " << block <<
" (id = ";
1469 if (uint32_t
id = getBlockID(block))
1478Serializer::processBlock(
Block *block,
bool omitLabel,
1480 LLVM_DEBUG(llvm::dbgs() <<
"processing block " << block <<
":\n");
1481 LLVM_DEBUG(block->
print(llvm::dbgs()));
1482 LLVM_DEBUG(llvm::dbgs() <<
'\n');
1484 uint32_t blockID = getOrCreateBlockID(block);
1485 LLVM_DEBUG(printBlock(block, llvm::dbgs()));
1492 if (
failed(emitPhiForBlockArguments(block)))
1502 llvm::IsaPred<spirv::LoopOp, spirv::SelectionOp>)) {
1505 emitMerge =
nullptr;
1508 uint32_t blockID = getNextID();
1514 for (Operation &op : llvm::drop_end(*block)) {
1515 if (
failed(processOperation(&op)))
1523 if (
failed(processOperation(&block->
back())))
1529LogicalResult Serializer::emitPhiForBlockArguments(
Block *block) {
1535 LLVM_DEBUG(llvm::dbgs() <<
"emitting phi instructions..\n");
1542 SmallVector<std::pair<Block *, OperandRange>, 4> predecessors;
1544 auto *terminator = mlirPredecessor->getTerminator();
1545 LLVM_DEBUG(llvm::dbgs() <<
" mlir predecessor ");
1546 LLVM_DEBUG(printBlock(mlirPredecessor, llvm::dbgs()));
1547 LLVM_DEBUG(llvm::dbgs() <<
" terminator: " << *terminator <<
"\n");
1556 LLVM_DEBUG(llvm::dbgs() <<
" spirv predecessor ");
1557 LLVM_DEBUG(printBlock(spirvPredecessor, llvm::dbgs()));
1558 if (
auto branchOp = dyn_cast<spirv::BranchOp>(terminator)) {
1559 predecessors.emplace_back(spirvPredecessor, branchOp.getOperands());
1560 }
else if (
auto branchCondOp =
1561 dyn_cast<spirv::BranchConditionalOp>(terminator)) {
1562 std::optional<OperandRange> blockOperands;
1563 if (branchCondOp.getTrueTarget() == block) {
1564 blockOperands = branchCondOp.getTrueTargetOperands();
1566 assert(branchCondOp.getFalseTarget() == block);
1567 blockOperands = branchCondOp.getFalseTargetOperands();
1569 assert(!blockOperands->empty() &&
1570 "expected non-empty block operand range");
1571 predecessors.emplace_back(spirvPredecessor, *blockOperands);
1572 }
else if (
auto switchOp = dyn_cast<spirv::SwitchOp>(terminator)) {
1573 std::optional<OperandRange> blockOperands;
1574 if (block == switchOp.getDefaultTarget()) {
1575 blockOperands = switchOp.getDefaultOperands();
1577 SuccessorRange targets = switchOp.getTargets();
1578 auto it = llvm::find(targets, block);
1579 assert(it != targets.end());
1580 size_t index = std::distance(targets.begin(), it);
1581 blockOperands = switchOp.getTargetOperands(index);
1583 assert(!blockOperands->empty() &&
1584 "expected non-empty block operand range");
1585 predecessors.emplace_back(spirvPredecessor, *blockOperands);
1587 return terminator->emitError(
"unimplemented terminator for Phi creation");
1590 llvm::dbgs() <<
" block arguments:\n";
1591 for (Value v : predecessors.back().second)
1592 llvm::dbgs() <<
" " << v <<
"\n";
1597 for (
auto argIndex : llvm::seq<unsigned>(0, block->
getNumArguments())) {
1601 uint32_t phiTypeID = 0;
1604 uint32_t phiID = getNextID();
1606 LLVM_DEBUG(llvm::dbgs() <<
"[phi] for block argument #" << argIndex <<
' '
1607 << arg <<
" (id = " << phiID <<
")\n");
1610 SmallVector<uint32_t, 8> phiArgs;
1611 phiArgs.push_back(phiTypeID);
1612 phiArgs.push_back(phiID);
1614 for (
auto predIndex : llvm::seq<unsigned>(0, predecessors.size())) {
1615 Value value = predecessors[predIndex].second[argIndex];
1616 uint32_t predBlockId = getOrCreateBlockID(predecessors[predIndex].first);
1617 LLVM_DEBUG(llvm::dbgs() <<
"[phi] use predecessor (id = " << predBlockId
1618 <<
") value " << value <<
' ');
1620 uint32_t valueId = getValueID(value);
1624 LLVM_DEBUG(llvm::dbgs() <<
"(need to fix)\n");
1625 deferredPhiValues[value].push_back(functionBody.size() + 1 +
1628 LLVM_DEBUG(llvm::dbgs() <<
"(id = " << valueId <<
")\n");
1630 phiArgs.push_back(valueId);
1632 phiArgs.push_back(predBlockId);
1636 valueIDMap[arg] = phiID;
1646LogicalResult Serializer::encodeExtensionInstruction(
1647 Operation *op, StringRef extensionSetName, uint32_t extensionOpcode,
1648 ArrayRef<uint32_t> operands, SmallVectorImpl<uint32_t> &binary) {
1650 auto &setID = extendedInstSetIDMap[extensionSetName];
1652 setID = getNextID();
1653 SmallVector<uint32_t, 16> importOperands;
1654 importOperands.push_back(setID);
1662 if (operands.size() < 2) {
1663 return op->
emitError(
"extended instructions must have a result encoding");
1665 SmallVector<uint32_t, 8> extInstOperands;
1666 extInstOperands.reserve(operands.size() + 2);
1667 extInstOperands.append(operands.begin(), std::next(operands.begin(), 2));
1668 extInstOperands.push_back(setID);
1669 extInstOperands.push_back(extensionOpcode);
1670 extInstOperands.append(std::next(operands.begin(), 2), operands.end());
1675LogicalResult Serializer::encodeExtensionInstruction(
1676 Operation *op, StringRef extensionSetName, uint32_t extensionOpcode,
1677 ArrayRef<uint32_t> operands) {
1678 if (
failed(encodeExtensionInstruction(op, extensionSetName, extensionOpcode,
1679 operands, functionBody)))
1682 if (extensionSetName ==
extTosa)
1683 updateTosaOpsMap(op);
1688LogicalResult Serializer::processOperation(Operation *opInst) {
1689 LLVM_DEBUG(llvm::dbgs() <<
"[op] '" << opInst->
getName() <<
"'\n");
1694 .Case([&](spirv::AddressOfOp op) {
return processAddressOfOp(op); })
1695 .Case([&](spirv::BranchOp op) {
return processBranchOp(op); })
1696 .Case([&](spirv::BranchConditionalOp op) {
1697 return processBranchConditionalOp(op);
1699 .Case([&](spirv::ConstantOp op) {
return processConstantOp(op); })
1700 .Case([&](spirv::CompositeConstructOp op) {
1701 return processCompositeConstructOp(op);
1703 .Case([&](spirv::EXTConstantCompositeReplicateOp op) {
1704 return processConstantCompositeReplicateOp(op);
1706 .Case([&](spirv::FuncOp op) {
return processFuncOp(op); })
1707 .Case([&](spirv::GraphARMOp op) {
return processGraphARMOp(op); })
1708 .Case([&](spirv::GraphEntryPointARMOp op) {
1709 return processGraphEntryPointARMOp(op);
1711 .Case([&](spirv::GraphOutputsARMOp op) {
1712 return processGraphOutputsARMOp(op);
1714 .Case([&](spirv::GlobalVariableOp op) {
1715 return processGlobalVariableOp(op);
1717 .Case([&](spirv::GraphConstantARMOp op) {
1718 return processGraphConstantARMOp(op);
1720 .Case([&](spirv::LoopOp op) {
return processLoopOp(op); })
1721 .Case([&](spirv::ReferenceOfOp op) {
return processReferenceOfOp(op); })
1722 .Case([&](spirv::SelectionOp op) {
return processSelectionOp(op); })
1723 .Case([&](spirv::SpecConstantOp op) {
return processSpecConstantOp(op); })
1724 .Case([&](spirv::SpecConstantCompositeOp op) {
1725 return processSpecConstantCompositeOp(op);
1727 .Case([&](spirv::EXTSpecConstantCompositeReplicateOp op) {
1728 return processSpecConstantCompositeReplicateOp(op);
1730 .Case([&](spirv::SpecConstantOperationOp op) {
1731 return processSpecConstantOperationOp(op);
1733 .Case([&](spirv::SwitchOp op) {
return processSwitchOp(op); })
1734 .Case([&](spirv::UndefOp op) {
return processUndefOp(op); })
1735 .Case([&](spirv::VariableOp op) {
return processVariableOp(op); })
1740 [&](Operation *op) {
return dispatchToAutogenSerialization(op); });
1744Serializer::processCompositeConstructOp(spirv::CompositeConstructOp op) {
1745 Location loc = op.getLoc();
1747 uint32_t resultTypeID = 0;
1748 if (
failed(processType(loc, op.getType(), resultTypeID)))
1751 uint32_t resultID = getNextID();
1752 valueIDMap[op.getResult()] = resultID;
1754 SmallVector<uint32_t, 8> operands;
1755 operands.reserve(2 + op.getConstituents().size());
1756 operands.push_back(resultTypeID);
1757 operands.push_back(resultID);
1758 for (Value constituent : op.getConstituents()) {
1759 uint32_t
id = getValueID(constituent);
1760 assert(
id &&
"use before def!");
1761 operands.push_back(
id);
1764 if (
failed(emitDebugLine(functionBody, loc)))
1767 encodeInstructionWithContinuationInto(
1768 functionBody, spirv::Opcode::OpCompositeConstruct, operands);
1770 for (
auto attr : op->getDiscardableAttrDictionary().getValue()) {
1771 if (
failed(processDecoration(loc, resultID, attr)))
1778LogicalResult Serializer::processOpWithoutGrammarAttr(Operation *op,
1779 StringRef extInstSet,
1781 SmallVector<uint32_t, 4> operands;
1782 Location loc = op->
getLoc();
1784 uint32_t resultID = 0;
1786 uint32_t resultTypeID = 0;
1789 operands.push_back(resultTypeID);
1791 resultID = getNextID();
1792 operands.push_back(resultID);
1793 valueIDMap[op->
getResult(0)] = resultID;
1797 operands.push_back(getValueID(operand));
1801 if (
failed(emitDebugLine(functionBody, loc)))
1804 if (extInstSet.empty()) {
1808 if (
failed(encodeExtensionInstruction(op, extInstSet, opcode, operands)))
1814 if (
failed(processDecoration(loc, resultID, attr)))
1822void Serializer::updateTosaOpsMap(Operation *op) {
1823 if (!options.emitDebugInfo)
1826 if (
auto graphOp = dyn_cast<spirv::GraphARMOp>(op->
getParentOp())) {
1827 if (uint32_t graphID = getFunctionID(graphOp.getName()))
1828 tosaOpsMap[graphID][op->
getLoc()].insert(op);
1832LogicalResult Serializer::emitDecoration(uint32_t
target,
1833 spirv::Decoration decoration,
1834 ArrayRef<uint32_t> params) {
1835 uint32_t wordCount = 3 + params.size();
1836 llvm::append_values(
1839 static_cast<uint32_t
>(decoration));
1840 llvm::append_range(decorations, params);
1844LogicalResult Serializer::emitDecorationId(uint32_t
target,
1845 spirv::Decoration decoration,
1846 ArrayRef<uint32_t> operandIds) {
1847 uint32_t wordCount = 3 + operandIds.size();
1848 llvm::append_values(
1851 static_cast<uint32_t
>(decoration));
1852 llvm::append_range(decorations, operandIds);
1856LogicalResult Serializer::emitDebugLine(SmallVectorImpl<uint32_t> &binary,
1858 if (!options.emitDebugInfo)
1861 if (lastProcessedWasMergeInst) {
1862 lastProcessedWasMergeInst =
false;
1866 auto fileLoc = dyn_cast<FileLineColLoc>(loc);
1869 {fileID, fileLoc.getLine(), fileLoc.getColumn()});
static Block * getStructuredControlFlowOpMergeBlock(Operation *op)
Returns the merge block if the given op is a structured control flow op.
static Block * getPhiIncomingBlock(Block *block)
Given a predecessor block for a block with arguments, returns the block that should be used as the pa...
static bool isZeroValue(Attribute attr)
static void moveFuncDeclarationsToTop(spirv::ModuleOp moduleOp)
Move all functions declaration before functions definitions.
Attributes are known-constant values of operations.
MLIRContext * getContext() const
Return the context this attribute belongs to.
Location getLoc() const
Return the location for this argument.
Block represents an ordered list of Operations.
BlockArgument getArgument(unsigned i)
unsigned getNumArguments()
iterator_range< pred_iterator > getPredecessors()
OpListType & getOperations()
void print(raw_ostream &os)
bool isEntryBlock()
Return if this block is the entry block in the parent region.
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
llvm::iplist< Operation > OpListType
This is the list of operations in the block.
bool getValue() const
Return the boolean value of this attribute.
bool isSplat() const
Returns true if this attribute corresponds to a splat, i.e.
ShapedType getType() const
Return the type of this ElementsAttr, guaranteed to be a vector or tensor with static shape.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
StringAttr getName() const
Return the name of the attribute.
Attribute getValue() const
Return the value of the attribute.
Operation is the basic unit of execution within MLIR.
Block * getBlock()
Returns the operation block that contains this operation.
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Location getLoc()
The source location the operation was defined or derived from.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
OperationName getName()
The name of an operation is the key identifier for it.
DictionaryAttr getDiscardableAttrDictionary()
Return all of the discardable attributes on this operation as a DictionaryAttr.
operand_range getOperands()
Returns an iterator on the underlying Value's.
void moveBefore(Operation *existingOp)
Unlink this operation from its current block and insert it right before existingOp which may be in th...
unsigned getNumResults()
Return the number of results held by this operation.
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 isUnsignedInteger() const
Return true if this is an unsigned integer type (with the specified width).
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
unsigned getArrayStride() const
Returns the array stride in bytes.
static ArrayType get(Type elementType, unsigned elementCount)
Type getElementType(unsigned) const
unsigned getArrayStride() const
Returns the array stride in bytes.
void printValueIDMap(raw_ostream &os)
(For debugging) prints each value and its corresponding result <id>.
LogicalResult serialize()
Serializes the remembered SPIR-V module.
Serializer(spirv::ModuleOp moduleOp, const SerializationOptions &options)
Creates a serializer for the given SPIR-V moduleOp.
void collect(SmallVectorImpl< uint32_t > &binary)
Collects the final SPIR-V binary.
static StructType getIdentified(MLIRContext *context, StringRef identifier)
Construct an identified StructType.
bool isIdentified() const
Returns true if the StructType is identified.
StringRef getIdentifier() const
For literal structs, return an empty string.
static TensorArmType get(ArrayRef< int64_t > shape, Type elementType)
static Type getValueType(Attribute attr)
void encodeStringLiteralInto(SmallVectorImpl< uint32_t > &binary, StringRef literal)
Encodes an SPIR-V literal string into the given binary vector.
TargetEnvAttr lookupTargetEnvOrDefault(Operation *op)
Queries the target environment recursively from enclosing symbol table ops containing the given op or...
std::optional< spirv::Opcode > getContinuationOpcode(spirv::Opcode parent)
Returns the SPV_INTEL_long_composites continuation opcode that may follow parent, or std::nullopt if ...
uint32_t getPrefixedOpcode(uint32_t wordCount, spirv::Opcode opcode)
Returns the word-count-prefixed opcode for an SPIR-V instruction.
void encodeInstructionInto(SmallVectorImpl< uint32_t > &binary, spirv::Opcode op, ArrayRef< uint32_t > operands)
Encodes an SPIR-V instruction with the given opcode and operands into the given binary vector.
constexpr uint32_t kMaxWordCount
Max number of words https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#_universal_limits.
void appendModuleHeader(SmallVectorImpl< uint32_t > &header, spirv::Version version, uint32_t idBound)
Appends a SPRI-V module header to header with the given version and idBound.
constexpr unsigned kHeaderWordCount
SPIR-V binary header word count.
constexpr llvm::StringLiteral extTosa
Extension set name for TOSA ops.
static LogicalResult processDecorationList(Location loc, Decoration decoration, Attribute attrList, StringRef attrName, EmitF emitter)
static std::string getDecorationName(StringRef attrName)
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
llvm::SetVector< T, Vector, Set, N > SetVector
llvm::TypeSwitch< T, ResultT > TypeSwitch
llvm::function_ref< Fn > function_ref
Attribute decorationValue