MLIR 24.0.0git
Serializer.cpp
Go to the documentation of this file.
1//===- Serializer.cpp - MLIR SPIR-V Serializer ----------------------------===//
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// This file defines the MLIR SPIR-V module to SPIR-V binary serializer.
10//
11//===----------------------------------------------------------------------===//
12
13#include "Serializer.h"
14
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"
27#include <cstdint>
28#include <optional>
29
30#define DEBUG_TYPE "spirv-serialization"
31
32using namespace mlir;
33
34/// Returns the merge block if the given `op` is a structured control flow op.
35/// Otherwise returns nullptr.
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();
41 return nullptr;
42}
43
44/// Given a predecessor `block` for a block with arguments, returns the block
45/// that should be used as the parent block for SPIR-V OpPhi instructions
46/// corresponding to the block arguments.
48 // If the predecessor block in question is the entry block for a
49 // spirv.mlir.loop, we jump to this spirv.mlir.loop from its enclosing block.
50 if (block->isEntryBlock()) {
51 if (auto loopOp = dyn_cast<spirv::LoopOp>(block->getParentOp())) {
52 // Then the incoming parent block for OpPhi should be the merge block of
53 // the structured control flow op before this loop.
54 Operation *op = loopOp.getOperation();
55 while ((op = op->getPrevNode()) != nullptr)
56 if (Block *incomingBlock = getStructuredControlFlowOpMergeBlock(op))
57 return incomingBlock;
58 // Or the enclosing block itself if no structured control flow ops
59 // exists before this loop.
60 return loopOp->getBlock();
61 }
62 }
63
64 // Otherwise, we jump from the given predecessor block. Try to see if there is
65 // a structured control flow op inside it.
66 for (Operation &op : llvm::reverse(block->getOperations())) {
67 if (Block *incomingBlock = getStructuredControlFlowOpMergeBlock(&op))
68 return incomingBlock;
69 }
70 return block;
71}
72
73static bool isZeroValue(Attribute attr) {
74 if (auto floatAttr = dyn_cast<FloatAttr>(attr)) {
75 return floatAttr.getValue().isZero();
76 }
77 if (auto boolAttr = dyn_cast<BoolAttr>(attr)) {
78 return !boolAttr.getValue();
79 }
80 if (auto intAttr = dyn_cast<IntegerAttr>(attr)) {
81 return intAttr.getValue().isZero();
82 }
83 if (auto splatElemAttr = dyn_cast<SplatElementsAttr>(attr)) {
84 return isZeroValue(splatElemAttr.getSplatValue<Attribute>());
85 }
86 if (auto denseElemAttr = dyn_cast<DenseElementsAttr>(attr)) {
87 return all_of(denseElemAttr.getValues<Attribute>(), isZeroValue);
88 }
89 return false;
90}
91
92/// Move all functions declaration before functions definitions. In SPIR-V
93/// "declarations" are functions without a body and "definitions" functions
94/// with a body. This is stronger than necessary. It should be sufficient to
95/// ensure any declarations precede their uses and not all definitions, however
96/// this allows to avoid analysing every function in the module this way.
97static void moveFuncDeclarationsToTop(spirv::ModuleOp moduleOp) {
98 Block::OpListType &ops = moduleOp.getBody()->getOperations();
99 if (ops.empty())
100 return;
101 Operation &firstOp = ops.front();
102 for (Operation &op : llvm::drop_begin(ops))
103 if (auto funcOp = dyn_cast<spirv::FuncOp>(op))
104 if (funcOp.getBody().empty())
105 funcOp->moveBefore(&firstOp);
106}
107
108namespace mlir {
109namespace spirv {
110
111/// Encodes an SPIR-V instruction with the given `opcode` and `operands` into
112/// the given `binary` vector.
114 ArrayRef<uint32_t> operands) {
115 uint32_t wordCount = 1 + operands.size();
116 binary.push_back(spirv::getPrefixedOpcode(wordCount, op));
117 binary.append(operands.begin(), operands.end());
118}
119
120Serializer::Serializer(spirv::ModuleOp moduleOp,
121 const SerializationOptions &options)
122 : moduleOp(moduleOp), mlirBuilder(moduleOp.getContext()), options(options) {
123}
124
125LogicalResult Serializer::serialize() {
126 LLVM_DEBUG(llvm::dbgs() << "+++ starting serialization +++\n");
127
128 if (failed(moduleOp.verifyInvariants()))
129 return failure();
130
131 // TODO: handle the other sections
132 processCapability();
133 if (failed(processExtension())) {
134 return failure();
135 }
136 processMemoryModel();
137 processDebugInfo();
138
140
141 // Iterate over the module body to serialize it. Assumptions are that there is
142 // only one basic block in the moduleOp
143 for (auto &op : *moduleOp.getBody()) {
144 if (failed(processOperation(&op))) {
145 return failure();
146 }
147 }
148
149 LLVM_DEBUG(llvm::dbgs() << "+++ completed serialization +++\n");
150 return success();
151}
152
154 auto moduleSize = spirv::kHeaderWordCount + capabilities.size() +
155 extensions.size() + extendedSets.size() +
156 memoryModel.size() + entryPoints.size() +
157 executionModes.size() + decorations.size() +
158 typesGlobalValues.size() + functions.size() + graphs.size();
159
160 binary.clear();
161 binary.reserve(moduleSize);
162
163 spirv::appendModuleHeader(binary, moduleOp.getVceTriple()->getVersion(),
164 nextID);
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());
178}
179
180#ifndef NDEBUG
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 << ' ';
187 if (auto *op = val.getDefiningOp()) {
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 << ' ';
192 os << " in op '" << block->getParentOp()->getName() << "'";
193 }
194 os << '\n';
195 }
196}
197#endif
198
199//===----------------------------------------------------------------------===//
200// Module structure
201//===----------------------------------------------------------------------===//
202
203uint32_t Serializer::getOrCreateFunctionID(StringRef fnName) {
204 auto funcID = funcIDMap.lookup(fnName);
205 if (!funcID) {
206 funcID = getNextID();
207 funcIDMap[fnName] = funcID;
208 }
209 return funcID;
210}
211
212void Serializer::processCapability() {
213 for (auto cap : moduleOp.getVceTriple()->getCapabilities())
214 encodeInstructionInto(capabilities, spirv::Opcode::OpCapability,
215 {static_cast<uint32_t>(cap)});
216}
217
218void Serializer::addLongCompositesCapability() {
219 if (longCompositesEmitted)
220 return;
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;
232 extName,
233 spirv::stringifyExtension(spirv::Extension::SPV_INTEL_long_composites));
234 encodeInstructionInto(extensions, spirv::Opcode::OpExtension, extName);
235 }
236}
237
238void Serializer::encodeInstructionWithContinuationInto(
239 SmallVectorImpl<uint32_t> &binary, spirv::Opcode op,
240 ArrayRef<uint32_t> operands) {
241 if (1 + operands.size() <= spirv::kMaxWordCount) {
242 encodeInstructionInto(binary, op, operands);
243 return;
244 }
245
246 std::optional<spirv::Opcode> continuationOp =
248 assert(continuationOp && "op is not a splittable composite/struct opcode");
249
250 const unsigned chunk = spirv::kMaxWordCount - 1;
251 encodeInstructionInto(binary, op, operands.take_front(chunk));
252 for (ArrayRef<uint32_t> rest = operands.drop_front(chunk); !rest.empty();
253 rest = rest.drop_front(std::min<size_t>(rest.size(), chunk))) {
254 encodeInstructionInto(binary, *continuationOp, rest.take_front(chunk));
255 }
256
257 addLongCompositesCapability();
258}
259
260void Serializer::processDebugInfo() {
261 if (!options.emitDebugInfo)
262 return;
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);
268 spirv::encodeStringLiteralInto(operands, fileName);
269 encodeInstructionInto(debug, spirv::Opcode::OpString, operands);
270 // TODO: Encode more debug instructions.
271}
272
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)) {
279 TargetEnvAttr targetEnvAttr = lookupTargetEnvOrDefault(moduleOp);
280 if (!is_contained(targetEnvAttr.getExtensions(), nonSemanticInfoExt))
281 return moduleOp.emitError(
282 "SPV_KHR_non_semantic_info extension not available");
283 deducedExts.insert(nonSemanticInfoExt);
284 }
285 for (spirv::Extension ext : deducedExts) {
286 extName.clear();
287 spirv::encodeStringLiteralInto(extName, spirv::stringifyExtension(ext));
288 encodeInstructionInto(extensions, spirv::Opcode::OpExtension, extName);
289 }
290 return success();
291}
292
293void Serializer::processMemoryModel() {
294 auto mm = static_cast<uint32_t>(moduleOp.getMemoryModel());
295 auto am = static_cast<uint32_t>(moduleOp.getAddressingModel());
296
297 encodeInstructionInto(memoryModel, spirv::Opcode::OpMemoryModel, {am, mm});
298}
299
300static std::string getDecorationName(StringRef attrName) {
301 // convertToCamelFromSnakeCase will convert this to FpFastMathMode instead of
302 // expected FPFastMathMode.
303 if (attrName == "fp_fast_math_mode")
304 return "FPFastMathMode";
305 // similar here
306 if (attrName == "fp_rounding_mode")
307 return "FPRoundingMode";
308 // convertToCamelFromSnakeCase will not capitalize "INTEL".
309 if (attrName == "cache_control_load_intel")
310 return "CacheControlLoadINTEL";
311 if (attrName == "cache_control_store_intel")
312 return "CacheControlStoreINTEL";
313
314 return llvm::convertToCamelFromSnakeCase(attrName, /*capitalizeFirst=*/true);
315}
316
317template <typename AttrTy, typename EmitF>
318static LogicalResult processDecorationList(Location loc, Decoration decoration,
319 Attribute attrList,
320 StringRef attrName, EmitF emitter) {
321 auto arrayAttr = dyn_cast<ArrayAttr>(attrList);
322 if (!arrayAttr) {
323 return emitError(loc, "expecting array attribute of ")
324 << attrName << " for " << stringifyDecoration(decoration);
325 }
326 if (arrayAttr.empty()) {
327 return emitError(loc, "expecting non-empty array attribute of ")
328 << attrName << " for " << stringifyDecoration(decoration);
329 }
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);
335 }
336 // This named attribute encodes several decorations. Emit one per
337 // element in the array.
338 if (failed(emitter(cacheControlAttr)))
339 return failure();
340 }
341 return success();
342}
343
344LogicalResult Serializer::processDecorationAttr(Location loc, uint32_t resultID,
345 Decoration decoration,
346 Attribute attr) {
348 switch (decoration) {
349 case spirv::Decoration::LinkageAttributes: {
350 // Get the value of the Linkage Attributes
351 // e.g., LinkageAttributes=["linkageName", linkageType].
352 auto linkageAttr = dyn_cast<spirv::LinkageAttributesAttr>(attr);
353 auto linkageName = linkageAttr.getLinkageName();
354 auto linkageType = linkageAttr.getLinkageType().getValue();
355 // Encode the Linkage Name (string literal to uint32_t).
356 spirv::encodeStringLiteralInto(args, linkageName);
357 // Encode LinkageType & Add the Linkagetype to the args.
358 args.push_back(static_cast<uint32_t>(linkageType));
359 break;
360 }
361 case spirv::Decoration::FPFastMathMode:
362 if (auto intAttr = dyn_cast<FPFastMathModeAttr>(attr)) {
363 args.push_back(static_cast<uint32_t>(intAttr.getValue()));
364 break;
365 }
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()));
371 break;
372 }
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())});
381 });
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());
393 break;
394 }
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());
400 if (enumVal) {
401 args.push_back(static_cast<uint32_t>(*enumVal));
402 break;
403 }
404 return emitError(loc, "invalid ")
405 << stringifyDecoration(decoration) << " decoration attribute "
406 << strAttr.getValue();
407 }
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:
431 // For unit attributes and decoration attributes, the args list
432 // has no values so we do nothing.
433 if (isa<UnitAttr, DecorationAttr>(attr))
434 break;
435 return emitError(loc,
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)});
447 });
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)});
457 });
458 case spirv::Decoration::AlignmentId:
459 case spirv::Decoration::MaxByteOffsetId:
460 case spirv::Decoration::CounterBuffer: {
461 auto symRef = dyn_cast<FlatSymbolRefAttr>(attr);
462 if (!symRef)
463 return emitError(loc, "expected symbol reference for ")
464 << stringifyDecoration(decoration);
465 StringRef symName = symRef.getValue();
466 uint32_t operandID = getVariableID(symName);
467 if (!operandID)
468 operandID = getSpecConstID(symName);
469 if (!operandID)
470 return emitError(loc, "could not find <id> for symbol '")
471 << symName << "' referenced by "
472 << stringifyDecoration(decoration);
473 return emitDecorationId(resultID, decoration, {operandID});
474 }
475 default:
476 return emitError(loc, "unhandled decoration ")
477 << stringifyDecoration(decoration);
478 }
479 return emitDecoration(resultID, decoration, args);
480}
481
482LogicalResult Serializer::processDecoration(Location loc, uint32_t resultID,
483 NamedAttribute attr) {
484 StringRef attrName = attr.getName().strref();
485 std::string decorationName = getDecorationName(attrName);
486 std::optional<Decoration> decoration =
487 spirv::symbolizeDecoration(decorationName);
488 if (!decoration) {
489 return emitError(
490 loc, "non-argument attributes expected to have snake-case-ified "
491 "decoration name, unhandled attribute with name : ")
492 << attrName;
493 }
494 return processDecorationAttr(loc, resultID, *decoration, attr.getValue());
495}
496
497LogicalResult Serializer::processName(uint32_t resultID, StringRef name) {
498 assert(!name.empty() && "unexpected empty string for OpName");
499 if (!options.emitSymbolName)
500 return success();
501
502 SmallVector<uint32_t, 4> nameOperands;
503 nameOperands.push_back(resultID);
504 spirv::encodeStringLiteralInto(nameOperands, name);
505 encodeInstructionInto(names, spirv::Opcode::OpName, nameOperands);
506 return success();
507}
508
509template <>
510LogicalResult Serializer::processTypeDecoration<spirv::ArrayType>(
511 Location loc, spirv::ArrayType type, uint32_t resultID) {
512 if (unsigned stride = type.getArrayStride()) {
513 // OpDecorate %arrayTypeSSA ArrayStride strideLiteral
514 return emitDecoration(resultID, spirv::Decoration::ArrayStride, {stride});
515 }
516 return success();
517}
518
519template <>
520LogicalResult Serializer::processTypeDecoration<spirv::RuntimeArrayType>(
521 Location loc, spirv::RuntimeArrayType type, uint32_t resultID) {
522 if (unsigned stride = type.getArrayStride()) {
523 // OpDecorate %arrayTypeSSA ArrayStride strideLiteral
524 return emitDecoration(resultID, spirv::Decoration::ArrayStride, {stride});
525 }
526 return success();
527}
528
529LogicalResult Serializer::processMemberDecoration(
530 uint32_t structID,
531 const spirv::StructType::MemberDecorationInfo &memberDecoration) {
533 {structID, memberDecoration.memberIndex,
534 static_cast<uint32_t>(memberDecoration.decoration)});
535 if (memberDecoration.hasValue()) {
536 args.push_back(
537 cast<IntegerAttr>(memberDecoration.decorationValue).getInt());
538 }
539 encodeInstructionInto(decorations, spirv::Opcode::OpMemberDecorate, args);
540 return success();
541}
542
543//===----------------------------------------------------------------------===//
544// Type
545//===----------------------------------------------------------------------===//
546
547// According to the SPIR-V spec "Validation Rules for Shader Capabilities":
548// "Composite objects in the StorageBuffer, PhysicalStorageBuffer, Uniform, and
549// PushConstant Storage Classes must be explicitly laid out."
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());
558 default:
559 break;
560 }
561 }
562 return false;
563}
564
565LogicalResult Serializer::processType(Location loc, Type type,
566 uint32_t &typeID) {
567 // Maintains a set of names for nested identified struct types. This is used
568 // to properly serialize recursive references.
569 SetVector<StringRef> serializationCtx;
570 return processTypeImpl(loc, type, typeID, serializationCtx);
571}
572
573LogicalResult
574Serializer::processTypeImpl(Location loc, Type type, uint32_t &typeID,
575 SetVector<StringRef> &serializationCtx) {
576
577 // Map unsigned integer types to singless integer types.
578 // This is needed otherwise the generated spirv assembly will contain
579 // twice a type declaration (like OpTypeInt 32 0) which is no permitted and
580 // such module fails validation. Indeed at MLIR level the two types are
581 // different and lookup in the cache below misses.
582 // Note: This conversion needs to happen here before the type is looked up in
583 // the cache.
584 if (type.isUnsignedInteger()) {
585 type = IntegerType::get(loc->getContext(), type.getIntOrFloatBitWidth(),
586 IntegerType::SignednessSemantics::Signless);
587 }
588
589 typeID = getTypeID(type);
590 if (typeID)
591 return success();
592
593 typeID = getNextID();
594 SmallVector<uint32_t, 4> operands;
595
596 operands.push_back(typeID);
597 auto typeEnum = spirv::Opcode::OpTypeVoid;
598 bool deferSerialization = false;
599
600 if ((isa<FunctionType>(type) &&
601 succeeded(prepareFunctionType(loc, cast<FunctionType>(type), typeEnum,
602 operands))) ||
603 (isa<GraphType>(type) &&
604 succeeded(
605 prepareGraphType(loc, cast<GraphType>(type), typeEnum, operands))) ||
606 succeeded(prepareBasicType(loc, type, typeID, typeEnum, operands,
607 deferSerialization, serializationCtx))) {
608 if (deferSerialization)
609 return success();
610
611 typeIDMap[type] = typeID;
612
613 if (typeEnum == spirv::Opcode::OpTypeStruct)
614 encodeInstructionWithContinuationInto(typesGlobalValues, typeEnum,
615 operands);
616 else
617 encodeInstructionInto(typesGlobalValues, typeEnum, operands);
618
619 if (recursiveStructInfos.count(type) != 0) {
620 // This recursive struct type is emitted already, now the OpTypePointer
621 // instructions referring to recursive references are emitted as well.
622 for (auto &ptrInfo : recursiveStructInfos[type]) {
623 // TODO: This might not work if more than 1 recursive reference is
624 // present in the struct.
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]);
629
630 encodeInstructionInto(typesGlobalValues, spirv::Opcode::OpTypePointer,
631 ptrOperands);
632 }
633
634 recursiveStructInfos[type].clear();
635 }
636
637 return success();
638 }
639
640 return emitError(loc, "failed to process type: ") << type;
641}
642
643LogicalResult Serializer::prepareBasicType(
644 Location loc, Type type, uint32_t resultID, spirv::Opcode &typeEnum,
645 SmallVectorImpl<uint32_t> &operands, bool &deferSerialization,
646 SetVector<StringRef> &serializationCtx) {
647 deferSerialization = false;
648
649 if (isVoidType(type)) {
650 typeEnum = spirv::Opcode::OpTypeVoid;
651 return success();
652 }
653
654 if (auto intType = dyn_cast<IntegerType>(type)) {
655 if (intType.getWidth() == 1) {
656 typeEnum = spirv::Opcode::OpTypeBool;
657 return success();
658 }
659
660 typeEnum = spirv::Opcode::OpTypeInt;
661 operands.push_back(intType.getWidth());
662 // SPIR-V OpTypeInt "Signedness specifies whether there are signed semantics
663 // to preserve or validate.
664 // 0 indicates unsigned, or no signedness semantics
665 // 1 indicates signed semantics."
666 operands.push_back(intType.isSigned() ? 1 : 0);
667 return success();
668 }
669
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));
675 }
676 if (floatType.isF8E4M3FN()) {
677 operands.push_back(
678 static_cast<uint32_t>(spirv::FPEncoding::Float8E4M3EXT));
679 }
680 if (floatType.isF8E5M2()) {
681 operands.push_back(
682 static_cast<uint32_t>(spirv::FPEncoding::Float8E5M2EXT));
683 }
684 if (isa<Float4E2M1FNType>(floatType))
685 operands.push_back(
686 static_cast<uint32_t>(spirv::FPEncoding::Float4E2M1EXT));
687 if (isa<Float6E2M3FNType>(floatType))
688 operands.push_back(
689 static_cast<uint32_t>(spirv::FPEncoding::Float6E2M3EXT));
690 if (isa<Float6E3M2FNType>(floatType))
691 operands.push_back(
692 static_cast<uint32_t>(spirv::FPEncoding::Float6E3M2EXT));
693 if (isa<Float8E8M0FNUType>(floatType))
694 operands.push_back(
695 static_cast<uint32_t>(spirv::FPEncoding::Float8UnsignedE8M0EXT));
696
697 return success();
698 }
699
700 if (auto vectorType = dyn_cast<VectorType>(type)) {
701 uint32_t elementTypeID = 0;
702 if (failed(processTypeImpl(loc, vectorType.getElementType(), elementTypeID,
703 serializationCtx))) {
704 return failure();
705 }
706 typeEnum = spirv::Opcode::OpTypeVector;
707 operands.push_back(elementTypeID);
708 operands.push_back(vectorType.getNumElements());
709 return success();
710 }
711
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)))
716 return failure();
717
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()));
725 return success();
726 }
727
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))) {
733 return failure();
734 }
735 operands.push_back(elementTypeID);
736 if (auto elementCountID = prepareConstantInt(
737 loc, mlirBuilder.getI32IntegerAttr(arrayType.getNumElements()))) {
738 operands.push_back(elementCountID);
739 }
740 return processTypeDecoration(loc, arrayType, resultID);
741 }
742
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());
747
748 if (pointeeStruct && pointeeStruct.isIdentified() &&
749 serializationCtx.count(pointeeStruct.getIdentifier()) != 0) {
750 // A recursive reference to an enclosing struct is found.
751 //
752 // 1. Prepare an OpTypeForwardPointer with resultID and the ptr storage
753 // class as operands.
754 SmallVector<uint32_t, 2> forwardPtrOperands;
755 forwardPtrOperands.push_back(resultID);
756 forwardPtrOperands.push_back(
757 static_cast<uint32_t>(ptrType.getStorageClass()));
758
759 encodeInstructionInto(typesGlobalValues,
760 spirv::Opcode::OpTypeForwardPointer,
761 forwardPtrOperands);
762
763 // 2. Find the pointee (enclosing) struct.
764 auto structType = spirv::StructType::getIdentified(
765 moduleOp.getContext(), pointeeStruct.getIdentifier());
766
767 if (!structType)
768 return failure();
769
770 // 3. Mark the OpTypePointer that is supposed to be emitted by this call
771 // as deferred.
772 deferSerialization = true;
773
774 // 4. Record the info needed to emit the deferred OpTypePointer
775 // instruction when the enclosing struct is completely serialized.
776 recursiveStructInfos[structType].push_back(
777 {resultID, ptrType.getStorageClass()});
778 } else {
779 if (failed(processTypeImpl(loc, ptrType.getPointeeType(), pointeeTypeID,
780 serializationCtx)))
781 return failure();
782 }
783
784 typeEnum = spirv::Opcode::OpTypePointer;
785 operands.push_back(static_cast<uint32_t>(ptrType.getStorageClass()));
786 operands.push_back(pointeeTypeID);
787
788 // TODO: Now struct decorations are supported this code may not be
789 // necessary. However, it is left to support backwards compatibility.
790 // Ideally, Block decorations should be inserted when converting to SPIR-V.
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";
799 }
800
801 return success();
802 }
803
804 if (auto runtimeArrayType = dyn_cast<spirv::RuntimeArrayType>(type)) {
805 uint32_t elementTypeID = 0;
806 if (failed(processTypeImpl(loc, runtimeArrayType.getElementType(),
807 elementTypeID, serializationCtx))) {
808 return failure();
809 }
810 typeEnum = spirv::Opcode::OpTypeRuntimeArray;
811 operands.push_back(elementTypeID);
812 return processTypeDecoration(loc, runtimeArrayType, resultID);
813 }
814
815 if (isa<spirv::SamplerType>(type)) {
816 typeEnum = spirv::Opcode::OpTypeSampler;
817 return success();
818 }
819
820 if (isa<spirv::NamedBarrierType>(type)) {
821 typeEnum = spirv::Opcode::OpTypeNamedBarrier;
822 return success();
823 }
824
825 if (auto untypedPtrType = dyn_cast<spirv::UntypedPointerType>(type)) {
826 typeEnum = spirv::Opcode::OpTypeUntypedPointerKHR;
827 operands.push_back(static_cast<uint32_t>(untypedPtrType.getStorageClass()));
828 return success();
829 }
830
831 if (auto sampledImageType = dyn_cast<spirv::SampledImageType>(type)) {
832 typeEnum = spirv::Opcode::OpTypeSampledImage;
833 uint32_t imageTypeID = 0;
834 if (failed(
835 processType(loc, sampledImageType.getImageType(), imageTypeID))) {
836 return failure();
837 }
838 operands.push_back(imageTypeID);
839 return success();
840 }
841
842 if (auto structType = dyn_cast<spirv::StructType>(type)) {
843 if (structType.isIdentified()) {
844 if (failed(processName(resultID, structType.getIdentifier())))
845 return failure();
846 serializationCtx.insert(structType.getIdentifier());
847 }
848
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))) {
855 return failure();
856 }
857 operands.push_back(elementTypeID);
858 if (hasOffset) {
859 auto intType = IntegerType::get(structType.getContext(), 32);
860 // Decorate each struct member with an offset
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";
869 }
870 }
871 }
872 SmallVector<spirv::StructType::MemberDecorationInfo, 4> memberDecorations;
873 structType.getMemberDecorations(memberDecorations);
874
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);
881 }
882 }
883
884 SmallVector<spirv::StructType::StructDecorationInfo, 1> structDecorations;
885 structType.getStructDecorations(structDecorations);
886
887 for (spirv::StructType::StructDecorationInfo &structDecoration :
888 structDecorations) {
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);
895 }
896 }
897
898 typeEnum = spirv::Opcode::OpTypeStruct;
899
900 if (structType.isIdentified())
901 serializationCtx.remove(structType.getIdentifier());
902
903 return success();
904 }
905
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))) {
911 return failure();
912 }
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);
917 };
918 llvm::append_values(
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())));
924 return success();
925 }
926
927 if (auto matrixType = dyn_cast<spirv::MatrixType>(type)) {
928 uint32_t elementTypeID = 0;
929 if (failed(processTypeImpl(loc, matrixType.getColumnType(), elementTypeID,
930 serializationCtx))) {
931 return failure();
932 }
933 typeEnum = spirv::Opcode::OpTypeMatrix;
934 llvm::append_values(operands, elementTypeID, matrixType.getNumColumns());
935 return success();
936 }
937
938 if (auto tensorArmType = dyn_cast<TensorArmType>(type)) {
939 uint32_t elementTypeID = 0;
940 uint32_t rank = 0;
941 uint32_t shapeID = 0;
942 uint32_t rankID = 0;
943 if (failed(processTypeImpl(loc, tensorArmType.getElementType(),
944 elementTypeID, serializationCtx))) {
945 return failure();
946 }
947 if (tensorArmType.hasRank()) {
948 ArrayRef<int64_t> dims = tensorArmType.getShape();
949 rank = dims.size();
950 rankID = prepareConstantInt(loc, mlirBuilder.getI32IntegerAttr(rank));
951 if (rankID == 0) {
952 return failure();
953 }
954
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);
958 auto shapeType = ArrayType::get(I32Type, rank);
959 if (rank == 1) {
960 SmallVector<uint64_t, 1> index(rank);
961 shapeID = prepareDenseElementsConstant(
962 loc, shapeType,
963 mlirBuilder.getI32TensorAttr(SmallVector<int32_t>(dims)), 0,
964 index);
965 } else {
966 shapeID = prepareArrayConstant(
967 loc, shapeType,
968 mlirBuilder.getI32ArrayAttr(SmallVector<int32_t>(dims)));
969 }
970 if (shapeID == 0) {
971 return failure();
972 }
973 }
974 }
975 typeEnum = spirv::Opcode::OpTypeTensorARM;
976 operands.push_back(elementTypeID);
977 if (rankID == 0)
978 return success();
979 operands.push_back(rankID);
980 if (shapeID == 0)
981 return success();
982 operands.push_back(shapeID);
983 return success();
984 }
985
986 // TODO: Handle other types.
987 return emitError(loc, "unhandled type in serialization: ") << type;
988}
989
990LogicalResult
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;
998 if (failed(processType(
999 loc, type.getNumResults() == 1 ? type.getResult(0) : getVoidType(),
1000 resultID))) {
1001 return failure();
1002 }
1003 operands.push_back(resultID);
1004 for (auto &res : type.getInputs()) {
1005 uint32_t argTypeID = 0;
1006 if (failed(processType(loc, res, argTypeID))) {
1007 return failure();
1008 }
1009 operands.push_back(argTypeID);
1010 }
1011 return success();
1012}
1013
1014LogicalResult
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");
1021
1022 operands.push_back(type.getNumInputs());
1023
1024 for (Type argType : type.getInputs()) {
1025 uint32_t argTypeID = 0;
1026 if (failed(processType(loc, argType, argTypeID)))
1027 return failure();
1028 operands.push_back(argTypeID);
1029 }
1030
1031 for (Type resType : type.getResults()) {
1032 uint32_t resTypeID = 0;
1033 if (failed(processType(loc, resType, resTypeID)))
1034 return failure();
1035 operands.push_back(resTypeID);
1036 }
1037
1038 return success();
1039}
1040
1041//===----------------------------------------------------------------------===//
1042// Constant
1043//===----------------------------------------------------------------------===//
1044
1045uint32_t Serializer::prepareConstant(Location loc, Type constType,
1046 Attribute valueAttr) {
1047 if (auto id = prepareConstantScalar(loc, valueAttr)) {
1048 return id;
1049 }
1050
1051 // This is a composite literal. We need to handle each component separately
1052 // and then emit an OpConstantComposite for the whole.
1053
1054 if (auto id = getConstantID(valueAttr)) {
1055 return id;
1056 }
1057
1058 uint32_t typeID = 0;
1059 if (failed(processType(loc, constType, typeID))) {
1060 return 0;
1061 }
1062
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,
1068 /*dim=*/0, index);
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();
1073 encodeInstructionInto(typesGlobalValues, spirv::Opcode::OpConstantNull,
1074 {typeID, resultID});
1075 }
1076
1077 if (resultID == 0) {
1078 emitError(loc, "cannot serialize attribute: ") << valueAttr;
1079 return 0;
1080 }
1081
1082 constIDMap[valueAttr] = resultID;
1083 return resultID;
1084}
1085
1086uint32_t Serializer::prepareArrayConstant(Location loc, Type constType,
1087 ArrayAttr attr) {
1088 uint32_t typeID = 0;
1089 if (failed(processType(loc, constType, typeID))) {
1090 return 0;
1091 }
1092
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(
1099 loc, compositeType.getElementType(idx), elementAttr)) {
1100 operands.push_back(elementID);
1101 } else {
1102 return 0;
1103 }
1104 }
1105 encodeInstructionWithContinuationInto(
1106 typesGlobalValues, spirv::Opcode::OpConstantComposite, operands);
1107
1108 return resultID;
1109}
1110
1111// TODO: Turn the below function into iterative function, instead of
1112// recursive function.
1113uint32_t
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]);
1125 }
1126 if (auto attr = dyn_cast<DenseFPElementsAttr>(valueAttr)) {
1127 return prepareConstantFp(loc, attr.getValues<FloatAttr>()[index]);
1128 }
1129 return 0;
1130 }
1131
1132 uint32_t typeID = 0;
1133 if (failed(processType(loc, constType, typeID))) {
1134 return 0;
1135 }
1136
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())
1144 elementType = spirv::TensorArmType::get(innerShape, elementType);
1145 }
1146
1147 // "If the Result Type is a cooperative matrix type, then there must be only
1148 // one Constituent, with scalar type matching the cooperative matrix Component
1149 // Type, and all components of the matrix are initialized to that value."
1150 // (https://github.khronos.org/SPIRV-Registry/extensions/KHR/SPV_KHR_cooperative_matrix.html)
1151 if (isa<spirv::CooperativeMatrixType>(constType)) {
1152 if (!valueAttr.isSplat()) {
1153 emitError(
1154 loc,
1155 "cannot serialize a non-splat value for a cooperative matrix type");
1156 return 0;
1157 }
1158 // numberOfConstituents is 1, so we only need one more elements in the
1159 // SmallVector, so the total is 3 (1 + 2).
1160 operands.reserve(3);
1161 // We set dim directly to `shapedType.getRank()` so the recursive call
1162 // directly returns the scalar type.
1163 if (auto elementID = prepareDenseElementsConstant(
1164 loc, elementType, valueAttr, /*dim=*/shapedType.getRank(), index)) {
1165 operands.push_back(elementID);
1166 } else {
1167 return 0;
1168 }
1169 } else if (isa<spirv::TensorArmType>(constType) && isZeroValue(valueAttr)) {
1170 encodeInstructionInto(typesGlobalValues, spirv::Opcode::OpConstantNull,
1171 {typeID, resultID});
1172 return resultID;
1173 } else {
1174 operands.reserve(numberOfConstituents + 2);
1175 for (int i = 0; i < numberOfConstituents; ++i) {
1176 index[dim] = i;
1177 if (auto elementID = prepareDenseElementsConstant(
1178 loc, elementType, valueAttr, dim + 1, index)) {
1179 operands.push_back(elementID);
1180 } else {
1181 return 0;
1182 }
1183 }
1184 }
1185 encodeInstructionWithContinuationInto(
1186 typesGlobalValues, spirv::Opcode::OpConstantComposite, operands);
1187
1188 return resultID;
1189}
1190
1191uint32_t Serializer::prepareConstantScalar(Location loc, Attribute valueAttr,
1192 bool isSpec) {
1193 if (auto floatAttr = dyn_cast<FloatAttr>(valueAttr)) {
1194 return prepareConstantFp(loc, floatAttr, isSpec);
1195 }
1196 if (auto boolAttr = dyn_cast<BoolAttr>(valueAttr)) {
1197 return prepareConstantBool(loc, boolAttr, isSpec);
1198 }
1199 if (auto intAttr = dyn_cast<IntegerAttr>(valueAttr)) {
1200 return prepareConstantInt(loc, intAttr, isSpec);
1201 }
1202
1203 return 0;
1204}
1205
1206uint32_t Serializer::prepareConstantBool(Location loc, BoolAttr boolAttr,
1207 bool isSpec) {
1208 if (!isSpec) {
1209 // We can de-duplicate normal constants, but not specialization constants.
1210 if (auto id = getConstantID(boolAttr)) {
1211 return id;
1212 }
1213 }
1214
1215 // Process the type for this bool literal
1216 uint32_t typeID = 0;
1217 if (failed(processType(loc, cast<IntegerAttr>(boolAttr).getType(), typeID))) {
1218 return 0;
1219 }
1220
1221 auto resultID = getNextID();
1222 auto opcode = boolAttr.getValue()
1223 ? (isSpec ? spirv::Opcode::OpSpecConstantTrue
1224 : spirv::Opcode::OpConstantTrue)
1225 : (isSpec ? spirv::Opcode::OpSpecConstantFalse
1226 : spirv::Opcode::OpConstantFalse);
1227 encodeInstructionInto(typesGlobalValues, opcode, {typeID, resultID});
1228
1229 if (!isSpec) {
1230 constIDMap[boolAttr] = resultID;
1231 }
1232 return resultID;
1233}
1234
1235uint32_t Serializer::prepareConstantInt(Location loc, IntegerAttr intAttr,
1236 bool isSpec) {
1237 if (!isSpec) {
1238 // We can de-duplicate normal constants, but not specialization constants.
1239 if (auto id = getConstantID(intAttr)) {
1240 return id;
1241 }
1242 }
1243
1244 // Process the type for this integer literal
1245 uint32_t typeID = 0;
1246 if (failed(processType(loc, intAttr.getType(), typeID))) {
1247 return 0;
1248 }
1249
1250 auto resultID = getNextID();
1251 APInt value = intAttr.getValue();
1252 unsigned bitwidth = value.getBitWidth();
1253 bool isSigned = intAttr.getType().isSignedInteger();
1254 auto opcode =
1255 isSpec ? spirv::Opcode::OpSpecConstant : spirv::Opcode::OpConstant;
1256
1257 switch (bitwidth) {
1258 // According to SPIR-V spec, "When the type's bit width is less than
1259 // 32-bits, the literal's value appears in the low-order bits of the word,
1260 // and the high-order bits must be 0 for a floating-point type, or 0 for an
1261 // integer type with Signedness of 0, or sign extended when Signedness
1262 // is 1."
1263 case 32:
1264 case 16:
1265 case 8: {
1266 uint32_t word = 0;
1267 if (isSigned) {
1268 word = static_cast<int32_t>(value.getSExtValue());
1269 } else {
1270 word = static_cast<uint32_t>(value.getZExtValue());
1271 }
1272 encodeInstructionInto(typesGlobalValues, opcode, {typeID, resultID, word});
1273 } break;
1274 // According to SPIR-V spec: "When the type's bit width is larger than one
1275 // word, the literal’s low-order words appear first."
1276 case 64: {
1277 struct DoubleWord {
1278 uint32_t word1;
1279 uint32_t word2;
1280 } words;
1281 if (isSigned) {
1282 words = llvm::bit_cast<DoubleWord>(value.getSExtValue());
1283 } else {
1284 words = llvm::bit_cast<DoubleWord>(value.getZExtValue());
1285 }
1286 encodeInstructionInto(typesGlobalValues, opcode,
1287 {typeID, resultID, words.word1, words.word2});
1288 } break;
1289 default: {
1290 std::string valueStr;
1291 llvm::raw_string_ostream rss(valueStr);
1292 value.print(rss, /*isSigned=*/false);
1293
1294 emitError(loc, "cannot serialize ")
1295 << bitwidth << "-bit integer literal: " << valueStr;
1296 return 0;
1297 }
1298 }
1299
1300 if (!isSpec) {
1301 constIDMap[intAttr] = resultID;
1302 }
1303 return resultID;
1304}
1305
1306uint32_t Serializer::prepareGraphConstantId(Location loc, Type graphConstType,
1307 IntegerAttr intAttr) {
1308 // De-duplicate graph constants.
1309 if (uint32_t id = getGraphConstantARMId(intAttr)) {
1310 return id;
1311 }
1312
1313 // Process the type for this graph constant.
1314 uint32_t typeID = 0;
1315 if (failed(processType(loc, graphConstType, typeID))) {
1316 return 0;
1317 }
1318
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";
1325 return 0;
1326 }
1327 bool isSigned = value.isSignedIntN(bitwidth);
1328
1329 uint32_t word = 0;
1330 if (isSigned) {
1331 word = static_cast<int32_t>(value.getSExtValue());
1332 } else {
1333 word = static_cast<uint32_t>(value.getZExtValue());
1334 }
1335 encodeInstructionInto(typesGlobalValues, spirv::Opcode::OpGraphConstantARM,
1336 {typeID, resultID, word});
1337 graphConstIDMap[intAttr] = resultID;
1338 return resultID;
1339}
1340
1341uint32_t Serializer::prepareConstantFp(Location loc, FloatAttr floatAttr,
1342 bool isSpec) {
1343 if (!isSpec) {
1344 // We can de-duplicate normal constants, but not specialization constants.
1345 if (auto id = getConstantID(floatAttr)) {
1346 return id;
1347 }
1348 }
1349
1350 // Process the type for this float literal
1351 uint32_t typeID = 0;
1352 if (failed(processType(loc, floatAttr.getType(), typeID))) {
1353 return 0;
1354 }
1355
1356 auto resultID = getNextID();
1357 APFloat value = floatAttr.getValue();
1358 const llvm::fltSemantics *semantics = &value.getSemantics();
1359
1360 auto opcode =
1361 isSpec ? spirv::Opcode::OpSpecConstant : spirv::Opcode::OpConstant;
1362
1363 if (semantics == &APFloat::IEEEsingle()) {
1364 uint32_t word = llvm::bit_cast<uint32_t>(value.convertToFloat());
1365 encodeInstructionInto(typesGlobalValues, opcode, {typeID, resultID, word});
1366 } else if (semantics == &APFloat::IEEEdouble()) {
1367 struct DoubleWord {
1368 uint32_t word1;
1369 uint32_t word2;
1370 } words = llvm::bit_cast<DoubleWord>(value.convertToDouble());
1371 encodeInstructionInto(typesGlobalValues, opcode,
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()},
1378 semantics)) {
1379 uint32_t word =
1380 static_cast<uint32_t>(value.bitcastToAPInt().getZExtValue());
1381 encodeInstructionInto(typesGlobalValues, opcode, {typeID, resultID, word});
1382 } else {
1383 std::string valueStr;
1384 llvm::raw_string_ostream rss(valueStr);
1385 value.print(rss);
1386
1387 emitError(loc, "cannot serialize ")
1388 << floatAttr.getType() << "-typed float literal: " << valueStr;
1389 return 0;
1390 }
1391
1392 if (!isSpec) {
1393 constIDMap[floatAttr] = resultID;
1394 }
1395 return resultID;
1396}
1397
1398// Returns type of attribute. In case of a TypedAttr this will simply return
1399// the type. But for an ArrayAttr which is untyped and can be multidimensional
1400// it creates the ArrayType recursively.
1402 if (auto typedAttr = dyn_cast<TypedAttr>(attr)) {
1403 return typedAttr.getType();
1404 }
1405
1406 if (auto arrayAttr = dyn_cast<ArrayAttr>(attr)) {
1407 return spirv::ArrayType::get(getValueType(arrayAttr[0]), arrayAttr.size());
1408 }
1409
1410 return nullptr;
1411}
1412
1413uint32_t Serializer::prepareConstantCompositeReplicate(Location loc,
1414 Type resultType,
1415 Attribute valueAttr) {
1416 std::pair<Attribute, Type> valueTypePair{valueAttr, resultType};
1417 if (uint32_t id = getConstantCompositeReplicateID(valueTypePair)) {
1418 return id;
1419 }
1420
1421 uint32_t typeID = 0;
1422 if (failed(processType(loc, resultType, typeID))) {
1423 return 0;
1424 }
1425
1426 Type valueType = getValueType(valueAttr);
1427 if (!valueAttr)
1428 return 0;
1429
1430 auto compositeType = dyn_cast<CompositeType>(resultType);
1431 if (!compositeType)
1432 return 0;
1433 Type elementType = compositeType.getElementType(0);
1434
1435 uint32_t constandID;
1436 if (elementType == valueType) {
1437 constandID = prepareConstant(loc, elementType, valueAttr);
1438 } else {
1439 constandID = prepareConstantCompositeReplicate(loc, elementType, valueAttr);
1440 }
1441
1442 uint32_t resultID = getNextID();
1443 if (dyn_cast<spirv::TensorArmType>(resultType) && isZeroValue(valueAttr)) {
1444 encodeInstructionInto(typesGlobalValues, spirv::Opcode::OpConstantNull,
1445 {typeID, resultID});
1446 } else {
1447 encodeInstructionInto(typesGlobalValues,
1448 spirv::Opcode::OpConstantCompositeReplicateEXT,
1449 {typeID, resultID, constandID});
1450 }
1451
1452 constCompositeReplicateIDMap[valueTypePair] = resultID;
1453 return resultID;
1454}
1455
1456//===----------------------------------------------------------------------===//
1457// Control flow
1458//===----------------------------------------------------------------------===//
1459
1460uint32_t Serializer::getOrCreateBlockID(Block *block) {
1461 if (uint32_t id = getBlockID(block))
1462 return id;
1463 return blockIDMap[block] = getNextID();
1464}
1465
1466#ifndef NDEBUG
1467void Serializer::printBlock(Block *block, raw_ostream &os) {
1468 os << "block " << block << " (id = ";
1469 if (uint32_t id = getBlockID(block))
1470 os << id;
1471 else
1472 os << "unknown";
1473 os << ")\n";
1474}
1475#endif
1476
1477LogicalResult
1478Serializer::processBlock(Block *block, bool omitLabel,
1479 function_ref<LogicalResult()> emitMerge) {
1480 LLVM_DEBUG(llvm::dbgs() << "processing block " << block << ":\n");
1481 LLVM_DEBUG(block->print(llvm::dbgs()));
1482 LLVM_DEBUG(llvm::dbgs() << '\n');
1483 if (!omitLabel) {
1484 uint32_t blockID = getOrCreateBlockID(block);
1485 LLVM_DEBUG(printBlock(block, llvm::dbgs()));
1486
1487 // Emit OpLabel for this block.
1488 encodeInstructionInto(functionBody, spirv::Opcode::OpLabel, {blockID});
1489 }
1490
1491 // Emit OpPhi instructions for block arguments, if any.
1492 if (failed(emitPhiForBlockArguments(block)))
1493 return failure();
1494
1495 // If we need to emit merge instructions, it must happen in this block. Check
1496 // whether we have other structured control flow ops, which will be expanded
1497 // into multiple basic blocks. If that's the case, we need to emit the merge
1498 // right now and then create new blocks for further serialization of the ops
1499 // in this block.
1500 if (emitMerge &&
1501 llvm::any_of(block->getOperations(),
1502 llvm::IsaPred<spirv::LoopOp, spirv::SelectionOp>)) {
1503 if (failed(emitMerge()))
1504 return failure();
1505 emitMerge = nullptr;
1506
1507 // Start a new block for further serialization.
1508 uint32_t blockID = getNextID();
1509 encodeInstructionInto(functionBody, spirv::Opcode::OpBranch, {blockID});
1510 encodeInstructionInto(functionBody, spirv::Opcode::OpLabel, {blockID});
1511 }
1512
1513 // Process each op in this block except the terminator.
1514 for (Operation &op : llvm::drop_end(*block)) {
1515 if (failed(processOperation(&op)))
1516 return failure();
1517 }
1518
1519 // Process the terminator.
1520 if (emitMerge)
1521 if (failed(emitMerge()))
1522 return failure();
1523 if (failed(processOperation(&block->back())))
1524 return failure();
1525
1526 return success();
1527}
1528
1529LogicalResult Serializer::emitPhiForBlockArguments(Block *block) {
1530 // Nothing to do if this block has no arguments or it's the entry block, which
1531 // always has the same arguments as the function signature.
1532 if (block->args_empty() || block->isEntryBlock())
1533 return success();
1534
1535 LLVM_DEBUG(llvm::dbgs() << "emitting phi instructions..\n");
1536
1537 // If the block has arguments, we need to create SPIR-V OpPhi instructions.
1538 // A SPIR-V OpPhi instruction is of the syntax:
1539 // OpPhi | result type | result <id> | (value <id>, parent block <id>) pair
1540 // So we need to collect all predecessor blocks and the arguments they send
1541 // to this block.
1542 SmallVector<std::pair<Block *, OperandRange>, 4> predecessors;
1543 for (Block *mlirPredecessor : block->getPredecessors()) {
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");
1548 // The predecessor here is the immediate one according to MLIR's IR
1549 // structure. It does not directly map to the incoming parent block for the
1550 // OpPhi instructions at SPIR-V binary level. This is because structured
1551 // control flow ops are serialized to multiple SPIR-V blocks. If there is a
1552 // spirv.mlir.selection/spirv.mlir.loop op in the MLIR predecessor block,
1553 // the branch op jumping to the OpPhi's block then resides in the previous
1554 // structured control flow op's merge block.
1555 Block *spirvPredecessor = getPhiIncomingBlock(mlirPredecessor);
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();
1565 } else {
1566 assert(branchCondOp.getFalseTarget() == block);
1567 blockOperands = branchCondOp.getFalseTargetOperands();
1568 }
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();
1576 } else {
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);
1582 }
1583 assert(!blockOperands->empty() &&
1584 "expected non-empty block operand range");
1585 predecessors.emplace_back(spirvPredecessor, *blockOperands);
1586 } else {
1587 return terminator->emitError("unimplemented terminator for Phi creation");
1588 }
1589 LLVM_DEBUG({
1590 llvm::dbgs() << " block arguments:\n";
1591 for (Value v : predecessors.back().second)
1592 llvm::dbgs() << " " << v << "\n";
1593 });
1594 }
1595
1596 // Then create OpPhi instruction for each of the block argument.
1597 for (auto argIndex : llvm::seq<unsigned>(0, block->getNumArguments())) {
1598 BlockArgument arg = block->getArgument(argIndex);
1599
1600 // Get the type <id> and result <id> for this OpPhi instruction.
1601 uint32_t phiTypeID = 0;
1602 if (failed(processType(arg.getLoc(), arg.getType(), phiTypeID)))
1603 return failure();
1604 uint32_t phiID = getNextID();
1605
1606 LLVM_DEBUG(llvm::dbgs() << "[phi] for block argument #" << argIndex << ' '
1607 << arg << " (id = " << phiID << ")\n");
1608
1609 // Prepare the (value <id>, parent block <id>) pairs.
1610 SmallVector<uint32_t, 8> phiArgs;
1611 phiArgs.push_back(phiTypeID);
1612 phiArgs.push_back(phiID);
1613
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 << ' ');
1619 // Each pair is a value <id> ...
1620 uint32_t valueId = getValueID(value);
1621 if (valueId == 0) {
1622 // The op generating this value hasn't been visited yet so we don't have
1623 // an <id> assigned yet. Record this to fix up later.
1624 LLVM_DEBUG(llvm::dbgs() << "(need to fix)\n");
1625 deferredPhiValues[value].push_back(functionBody.size() + 1 +
1626 phiArgs.size());
1627 } else {
1628 LLVM_DEBUG(llvm::dbgs() << "(id = " << valueId << ")\n");
1629 }
1630 phiArgs.push_back(valueId);
1631 // ... and a parent block <id>.
1632 phiArgs.push_back(predBlockId);
1633 }
1634
1635 encodeInstructionInto(functionBody, spirv::Opcode::OpPhi, phiArgs);
1636 valueIDMap[arg] = phiID;
1637 }
1638
1639 return success();
1640}
1641
1642//===----------------------------------------------------------------------===//
1643// Operation
1644//===----------------------------------------------------------------------===//
1645
1646LogicalResult Serializer::encodeExtensionInstruction(
1647 Operation *op, StringRef extensionSetName, uint32_t extensionOpcode,
1648 ArrayRef<uint32_t> operands, SmallVectorImpl<uint32_t> &binary) {
1649 // Check if the extension has been imported.
1650 auto &setID = extendedInstSetIDMap[extensionSetName];
1651 if (!setID) {
1652 setID = getNextID();
1653 SmallVector<uint32_t, 16> importOperands;
1654 importOperands.push_back(setID);
1655 spirv::encodeStringLiteralInto(importOperands, extensionSetName);
1656 encodeInstructionInto(extendedSets, spirv::Opcode::OpExtInstImport,
1657 importOperands);
1658 }
1659
1660 // The first two operands are the result type <id> and result <id>. The set
1661 // <id> and the opcode need to be insert after this.
1662 if (operands.size() < 2) {
1663 return op->emitError("extended instructions must have a result encoding");
1664 }
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());
1671 encodeInstructionInto(binary, spirv::Opcode::OpExtInst, extInstOperands);
1672 return success();
1673}
1674
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)))
1680 return failure();
1681
1682 if (extensionSetName == extTosa)
1683 updateTosaOpsMap(op);
1684
1685 return success();
1686}
1687
1688LogicalResult Serializer::processOperation(Operation *opInst) {
1689 LLVM_DEBUG(llvm::dbgs() << "[op] '" << opInst->getName() << "'\n");
1690
1691 // First dispatch the ops that do not directly mirror an instruction from
1692 // the SPIR-V spec.
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);
1698 })
1699 .Case([&](spirv::ConstantOp op) { return processConstantOp(op); })
1700 .Case([&](spirv::CompositeConstructOp op) {
1701 return processCompositeConstructOp(op);
1702 })
1703 .Case([&](spirv::EXTConstantCompositeReplicateOp op) {
1704 return processConstantCompositeReplicateOp(op);
1705 })
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);
1710 })
1711 .Case([&](spirv::GraphOutputsARMOp op) {
1712 return processGraphOutputsARMOp(op);
1713 })
1714 .Case([&](spirv::GlobalVariableOp op) {
1715 return processGlobalVariableOp(op);
1716 })
1717 .Case([&](spirv::GraphConstantARMOp op) {
1718 return processGraphConstantARMOp(op);
1719 })
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);
1726 })
1727 .Case([&](spirv::EXTSpecConstantCompositeReplicateOp op) {
1728 return processSpecConstantCompositeReplicateOp(op);
1729 })
1730 .Case([&](spirv::SpecConstantOperationOp op) {
1731 return processSpecConstantOperationOp(op);
1732 })
1733 .Case([&](spirv::SwitchOp op) { return processSwitchOp(op); })
1734 .Case([&](spirv::UndefOp op) { return processUndefOp(op); })
1735 .Case([&](spirv::VariableOp op) { return processVariableOp(op); })
1736
1737 // Then handle all the ops that directly mirror SPIR-V instructions with
1738 // auto-generated methods.
1739 .Default(
1740 [&](Operation *op) { return dispatchToAutogenSerialization(op); });
1741}
1742
1743LogicalResult
1744Serializer::processCompositeConstructOp(spirv::CompositeConstructOp op) {
1745 Location loc = op.getLoc();
1746
1747 uint32_t resultTypeID = 0;
1748 if (failed(processType(loc, op.getType(), resultTypeID)))
1749 return failure();
1750
1751 uint32_t resultID = getNextID();
1752 valueIDMap[op.getResult()] = resultID;
1753
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);
1762 }
1763
1764 if (failed(emitDebugLine(functionBody, loc)))
1765 return failure();
1766
1767 encodeInstructionWithContinuationInto(
1768 functionBody, spirv::Opcode::OpCompositeConstruct, operands);
1769
1770 for (auto attr : op->getDiscardableAttrDictionary().getValue()) {
1771 if (failed(processDecoration(loc, resultID, attr)))
1772 return failure();
1773 }
1774
1775 return success();
1776}
1777
1778LogicalResult Serializer::processOpWithoutGrammarAttr(Operation *op,
1779 StringRef extInstSet,
1780 uint32_t opcode) {
1781 SmallVector<uint32_t, 4> operands;
1782 Location loc = op->getLoc();
1783
1784 uint32_t resultID = 0;
1785 if (op->getNumResults() != 0) {
1786 uint32_t resultTypeID = 0;
1787 if (failed(processType(loc, op->getResult(0).getType(), resultTypeID)))
1788 return failure();
1789 operands.push_back(resultTypeID);
1790
1791 resultID = getNextID();
1792 operands.push_back(resultID);
1793 valueIDMap[op->getResult(0)] = resultID;
1794 };
1795
1796 for (Value operand : op->getOperands())
1797 operands.push_back(getValueID(operand));
1798
1799 if (extInstSet != extTosa)
1800 // OpLine cannot be present in graphs
1801 if (failed(emitDebugLine(functionBody, loc)))
1802 return failure();
1803
1804 if (extInstSet.empty()) {
1805 encodeInstructionInto(functionBody, static_cast<spirv::Opcode>(opcode),
1806 operands);
1807 } else {
1808 if (failed(encodeExtensionInstruction(op, extInstSet, opcode, operands)))
1809 return failure();
1810 }
1811
1812 if (op->getNumResults() != 0) {
1813 for (auto attr : op->getDiscardableAttrDictionary().getValue()) {
1814 if (failed(processDecoration(loc, resultID, attr)))
1815 return failure();
1816 }
1817 }
1818
1819 return success();
1820}
1821
1822void Serializer::updateTosaOpsMap(Operation *op) {
1823 if (!options.emitDebugInfo)
1824 return;
1825
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);
1829 }
1830}
1831
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(
1837 decorations,
1838 spirv::getPrefixedOpcode(wordCount, spirv::Opcode::OpDecorate), target,
1839 static_cast<uint32_t>(decoration));
1840 llvm::append_range(decorations, params);
1841 return success();
1842}
1843
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(
1849 decorations,
1850 spirv::getPrefixedOpcode(wordCount, spirv::Opcode::OpDecorateId), target,
1851 static_cast<uint32_t>(decoration));
1852 llvm::append_range(decorations, operandIds);
1853 return success();
1854}
1855
1856LogicalResult Serializer::emitDebugLine(SmallVectorImpl<uint32_t> &binary,
1857 Location loc) {
1858 if (!options.emitDebugInfo)
1859 return success();
1860
1861 if (lastProcessedWasMergeInst) {
1862 lastProcessedWasMergeInst = false;
1863 return success();
1864 }
1865
1866 auto fileLoc = dyn_cast<FileLineColLoc>(loc);
1867 if (fileLoc)
1868 encodeInstructionInto(binary, spirv::Opcode::OpLine,
1869 {fileID, fileLoc.getLine(), fileLoc.getColumn()});
1870 return success();
1871}
1872} // namespace spirv
1873} // namespace mlir
return success()
ArrayAttr()
b getContext())
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.
Definition Attributes.h:25
MLIRContext * getContext() const
Return the context this attribute belongs to.
Location getLoc() const
Return the location for this argument.
Definition Value.h:323
Block represents an ordered list of Operations.
Definition Block.h:34
BlockArgument getArgument(unsigned i)
Definition Block.h:154
unsigned getNumArguments()
Definition Block.h:153
iterator_range< pred_iterator > getPredecessors()
Definition Block.h:250
OpListType & getOperations()
Definition Block.h:162
Operation & back()
Definition Block.h:177
void print(raw_ostream &os)
bool args_empty()
Definition Block.h:124
bool isEntryBlock()
Return if this block is the entry block in the parent region.
Definition Block.cpp:36
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
Definition Block.cpp:31
llvm::iplist< Operation > OpListType
This is the list of operations in the block.
Definition Block.h:161
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...
Definition Location.h:76
StringAttr getName() const
Return the name of the attribute.
Attribute getValue() const
Return the value of the attribute.
Definition Attributes.h:181
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Block * getBlock()
Returns the operation block that contains this operation.
Definition Operation.h:230
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition Operation.h:251
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.
Definition Operation.h:115
DictionaryAttr getDiscardableAttrDictionary()
Return all of the discardable attributes on this operation as a DictionaryAttr.
Definition Operation.h:555
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:405
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.
Definition Operation.h:431
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
Definition Types.cpp:35
bool isUnsignedInteger() const
Return true if this is an unsigned integer type (with the specified width).
Definition Types.cpp:90
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
Definition Types.cpp:124
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
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)
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
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.
Definition Utils.cpp:311
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
llvm::SetVector< T, Vector, Set, N > SetVector
Definition LLVM.h:128
llvm::TypeSwitch< T, ResultT > TypeSwitch
Definition LLVM.h:147
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155