MLIR 24.0.0git
Deserializer.cpp
Go to the documentation of this file.
1//===- Deserializer.cpp - MLIR SPIR-V Deserializer ------------------------===//
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 SPIR-V binary to MLIR SPIR-V module deserializer.
10//
11//===----------------------------------------------------------------------===//
12
13#include "Deserializer.h"
14
20#include "mlir/IR/Builders.h"
21#include "mlir/IR/IRMapping.h"
22#include "mlir/IR/Location.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/Sequence.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/StringExtras.h"
28#include "llvm/ADT/bit.h"
29#include "llvm/Support/Debug.h"
30#include "llvm/Support/MathExtras.h"
31#include "llvm/Support/SaveAndRestore.h"
32#include "llvm/Support/raw_ostream.h"
33#include <optional>
34#include <utility>
35
36using namespace mlir;
37
38#define DEBUG_TYPE "spirv-deserialization"
39
40//===----------------------------------------------------------------------===//
41// Utility Functions
42//===----------------------------------------------------------------------===//
43
44/// Returns true if the given `block` is a function entry block.
45static inline bool isFnEntryBlock(Block *block) {
46 return block->isEntryBlock() &&
47 isa_and_nonnull<spirv::FuncOp>(block->getParentOp());
48}
49
50static void setInherentOrDiscardableAttr(Operation *op, StringAttr name,
51 Attribute value) {
52 if (op->getName().getInherentAttr(op, name).has_value()) {
53 op->getName().setInherentAttr(op, name, value);
54 return;
55 }
56 op->setDiscardableAttr(name, value);
57}
58
59//===----------------------------------------------------------------------===//
60// Deserializer Method Definitions
61//===----------------------------------------------------------------------===//
62
63spirv::Deserializer::Deserializer(ArrayRef<uint32_t> binary,
64 MLIRContext *context,
66 : binary(binary), context(context), unknownLoc(UnknownLoc::get(context)),
67 moduleOp(createModuleOp()), opBuilder(moduleOp->getRegion()),
69#ifndef NDEBUG
70 ,
71 logger(llvm::dbgs())
72#endif
73{
74}
75
76LogicalResult spirv::Deserializer::deserialize() {
77 LLVM_DEBUG({
78 logger.resetIndent();
79 logger.startLine()
80 << "//+++---------- start deserialization ----------+++//\n";
81 });
82
83 if (failed(processHeader()))
84 return failure();
85
86 spirv::Opcode opcode = spirv::Opcode::OpNop;
87 ArrayRef<uint32_t> operands;
88 auto binarySize = binary.size();
89 while (curOffset < binarySize) {
90 // Slice the next instruction out and populate `opcode` and `operands`.
91 // Internally this also updates `curOffset`.
92 if (failed(sliceInstruction(opcode, operands)))
93 return failure();
94
95 if (failed(processInstruction(opcode, operands)))
96 return failure();
97 }
98
99 assert(curOffset == binarySize &&
100 "deserializer should never index beyond the binary end");
101
102 for (auto &deferred : deferredInstructions) {
103 if (failed(processInstruction(deferred.first, deferred.second, false))) {
104 return failure();
105 }
106 }
107
108 if (failed(resolveDeferredIdDecorations()))
109 return failure();
110
111 if (!functionParameterAttrs.empty())
112 return emitError(unknownLoc, "FuncParamAttr decoration on result <id> ")
113 << functionParameterAttrs.begin()->first
114 << " is not supported: expected OpFunctionParameter or OpFunction";
115
116 attachVCETriple();
117
118 LLVM_DEBUG(logger.startLine()
119 << "//+++-------- completed deserialization --------+++//\n");
120 return success();
121}
122
123OwningOpRef<spirv::ModuleOp> spirv::Deserializer::collect() {
124 return std::move(moduleOp);
125}
126
127//===----------------------------------------------------------------------===//
128// Module structure
129//===----------------------------------------------------------------------===//
130
131OwningOpRef<spirv::ModuleOp> spirv::Deserializer::createModuleOp() {
132 OpBuilder builder(context);
133 OperationState state(unknownLoc, spirv::ModuleOp::getOperationName());
134 spirv::ModuleOp::build(builder, state);
135 return cast<spirv::ModuleOp>(Operation::create(state));
136}
137
138LogicalResult spirv::Deserializer::processHeader() {
139 if (binary.size() < spirv::kHeaderWordCount)
140 return emitError(unknownLoc,
141 "SPIR-V binary module must have a 5-word header");
142
143 if (binary[0] != spirv::kMagicNumber)
144 return emitError(unknownLoc, "incorrect magic number");
145
146 // Version number bytes: 0 | major number | minor number | 0
147 uint32_t majorVersion = (binary[1] << 8) >> 24;
148 uint32_t minorVersion = (binary[1] << 16) >> 24;
149 if (majorVersion == 1) {
150 switch (minorVersion) {
151#define MIN_VERSION_CASE(v) \
152 case v: \
153 version = spirv::Version::V_1_##v; \
154 break
155
163#undef MIN_VERSION_CASE
164 default:
165 return emitError(unknownLoc, "unsupported SPIR-V minor version: ")
166 << minorVersion;
167 }
168 } else {
169 return emitError(unknownLoc, "unsupported SPIR-V major version: ")
170 << majorVersion;
171 }
172
173 // TODO: generator number, bound, schema
174 curOffset = spirv::kHeaderWordCount;
175 return success();
176}
177
178LogicalResult
179spirv::Deserializer::processCapability(ArrayRef<uint32_t> operands) {
180 if (operands.size() != 1)
181 return emitError(unknownLoc, "OpCapability must have one parameter");
182
183 auto cap = spirv::symbolizeCapability(operands[0]);
184 if (!cap)
185 return emitError(unknownLoc, "unknown capability: ") << operands[0];
186
187 capabilities.insert(*cap);
188 return success();
189}
190
191LogicalResult spirv::Deserializer::processExtension(ArrayRef<uint32_t> words) {
192 if (words.empty()) {
193 return emitError(
194 unknownLoc,
195 "OpExtension must have a literal string for the extension name");
196 }
197
198 unsigned wordIndex = 0;
199 StringRef extName = decodeStringLiteral(words, wordIndex);
200 if (wordIndex != words.size())
201 return emitError(unknownLoc,
202 "unexpected trailing words in OpExtension instruction");
203 auto ext = spirv::symbolizeExtension(extName);
204 if (!ext)
205 return emitError(unknownLoc, "unknown extension: ") << extName;
206
207 extensions.insert(*ext);
208 return success();
209}
210
211LogicalResult
212spirv::Deserializer::processExtInstImport(ArrayRef<uint32_t> words) {
213 if (words.size() < 2) {
214 return emitError(unknownLoc,
215 "OpExtInstImport must have a result <id> and a literal "
216 "string for the extended instruction set name");
217 }
218
219 unsigned wordIndex = 1;
220 extendedInstSets[words[0]] = decodeStringLiteral(words, wordIndex);
221 if (wordIndex != words.size()) {
222 return emitError(unknownLoc,
223 "unexpected trailing words in OpExtInstImport");
224 }
225 return success();
226}
227
228void spirv::Deserializer::attachVCETriple() {
229 moduleOp->setVceTripleAttr(spirv::VerCapExtAttr::get(
230 version, capabilities.getArrayRef(), extensions.getArrayRef(), context));
231}
232
233LogicalResult
234spirv::Deserializer::processMemoryModel(ArrayRef<uint32_t> operands) {
235 if (operands.size() != 2)
236 return emitError(unknownLoc, "OpMemoryModel must have two operands");
237
238 moduleOp->setAddressingModel(
239 static_cast<spirv::AddressingModel>(operands.front()));
240
241 moduleOp->setMemoryModel(static_cast<spirv::MemoryModel>(operands.back()));
242
243 return success();
244}
245
246template <typename AttrTy, typename EnumAttrTy, typename EnumTy>
248 Location loc, OpBuilder &opBuilder,
250 StringAttr symbol, StringRef decorationName, StringRef cacheControlKind) {
251 if (words.size() != 4) {
252 return emitError(loc, "OpDecorate with ")
253 << decorationName << " needs a cache control integer literal and a "
254 << cacheControlKind << " cache control literal";
255 }
256 unsigned cacheLevel = words[2];
257 auto cacheControlAttr = static_cast<EnumTy>(words[3]);
258 auto value = opBuilder.getAttr<AttrTy>(cacheLevel, cacheControlAttr);
260 if (auto attrList =
261 dyn_cast_or_null<ArrayAttr>(decorations[words[0]].get(symbol)))
262 llvm::append_range(attrs, attrList);
263 attrs.push_back(value);
264 decorations[words[0]].set(symbol, opBuilder.getArrayAttr(attrs));
265 return success();
266}
267
268LogicalResult spirv::Deserializer::processDecoration(ArrayRef<uint32_t> words) {
269 // TODO: This function should also be auto-generated. For now, since only a
270 // few decorations are processed/handled in a meaningful manner, going with a
271 // manual implementation.
272 if (words.size() < 2) {
273 return emitError(
274 unknownLoc, "OpDecorate must have at least result <id> and Decoration");
275 }
276 auto decorationName =
277 stringifyDecoration(static_cast<spirv::Decoration>(words[1]));
278 if (decorationName.empty()) {
279 return emitError(unknownLoc, "invalid Decoration code : ") << words[1];
280 }
281 auto symbol = getSymbolDecoration(decorationName);
282 switch (static_cast<spirv::Decoration>(words[1])) {
283 case spirv::Decoration::FPFastMathMode:
284 if (words.size() != 3) {
285 return emitError(unknownLoc, "OpDecorate with ")
286 << decorationName << " needs a single integer literal";
287 }
288 decorations[words[0]].set(
289 symbol, FPFastMathModeAttr::get(opBuilder.getContext(),
290 static_cast<FPFastMathMode>(words[2])));
291 break;
292 case spirv::Decoration::FPRoundingMode:
293 if (words.size() != 3) {
294 return emitError(unknownLoc, "OpDecorate with ")
295 << decorationName << " needs a single integer literal";
296 }
297 decorations[words[0]].set(
298 symbol, FPRoundingModeAttr::get(opBuilder.getContext(),
299 static_cast<FPRoundingMode>(words[2])));
300 break;
301 case spirv::Decoration::FuncParamAttr: {
302 if (words.size() != 3)
303 return emitError(unknownLoc,
304 "OpDecorate with FuncParamAttr needs a single "
305 "function parameter attribute");
306 auto value = spirv::symbolizeFunctionParameterAttribute(words[2]);
307 if (!value)
308 return emitError(unknownLoc, "invalid FunctionParameterAttribute code: ")
309 << words[2];
310 SmallVector<Attribute> attrs;
311 if (auto previous = functionParameterAttrs.lookup(words[0]))
312 llvm::append_range(attrs, previous);
313 attrs.push_back(
314 spirv::FunctionParameterAttributeAttr::get(context, *value));
315 functionParameterAttrs[words[0]] = opBuilder.getArrayAttr(attrs);
316 break;
317 }
318 case spirv::Decoration::Alignment:
319 case spirv::Decoration::MaxByteOffset:
320 case spirv::Decoration::DescriptorSet:
321 case spirv::Decoration::Binding:
322 case spirv::Decoration::Location:
323 case spirv::Decoration::SpecId:
324 case spirv::Decoration::Index:
325 case spirv::Decoration::Offset:
326 case spirv::Decoration::XfbBuffer:
327 case spirv::Decoration::XfbStride:
328 if (words.size() != 3) {
329 return emitError(unknownLoc, "OpDecorate with ")
330 << decorationName << " needs a single integer literal";
331 }
332 decorations[words[0]].set(
333 symbol, opBuilder.getI32IntegerAttr(static_cast<int32_t>(words[2])));
334 break;
335 case spirv::Decoration::BuiltIn:
336 if (words.size() != 3) {
337 return emitError(unknownLoc, "OpDecorate with ")
338 << decorationName << " needs a single integer literal";
339 }
340 decorations[words[0]].set(
341 symbol, opBuilder.getStringAttr(
342 stringifyBuiltIn(static_cast<spirv::BuiltIn>(words[2]))));
343 break;
344 case spirv::Decoration::ArrayStride:
345 if (words.size() != 3) {
346 return emitError(unknownLoc, "OpDecorate with ")
347 << decorationName << " needs a single integer literal";
348 }
349 typeDecorations[words[0]] = words[2];
350 break;
351 case spirv::Decoration::LinkageAttributes: {
352 if (words.size() < 4) {
353 return emitError(unknownLoc, "OpDecorate with ")
354 << decorationName
355 << " needs at least 1 string and 1 integer literal";
356 }
357 // LinkageAttributes has two parameters ["linkageName", linkageType]
358 // e.g., OpDecorate %imported_func LinkageAttributes "outside.func" Import
359 // "linkageName" is a stringliteral encoded as uint32_t,
360 // hence the size of name is variable length which results in words.size()
361 // being variable length, words.size() = 3 + strlen(name)/4 + 1 or
362 // 3 + ceildiv(strlen(name), 4).
363 unsigned wordIndex = 2;
364 auto linkageName = spirv::decodeStringLiteral(words, wordIndex).str();
365 auto linkageTypeAttr = opBuilder.getAttr<::mlir::spirv::LinkageTypeAttr>(
366 static_cast<::mlir::spirv::LinkageType>(words[wordIndex++]));
367 auto linkageAttr = opBuilder.getAttr<::mlir::spirv::LinkageAttributesAttr>(
368 StringAttr::get(context, linkageName), linkageTypeAttr);
369 decorations[words[0]].set(symbol, dyn_cast<Attribute>(linkageAttr));
370 break;
371 }
372 case spirv::Decoration::Aliased:
373 case spirv::Decoration::AliasedPointer:
374 case spirv::Decoration::Block:
375 case spirv::Decoration::BufferBlock:
376 case spirv::Decoration::Centroid:
377 case spirv::Decoration::CPacked:
378 case spirv::Decoration::Flat:
379 case spirv::Decoration::NonReadable:
380 case spirv::Decoration::NonUniform:
381 case spirv::Decoration::NonWritable:
382 case spirv::Decoration::NoPerspective:
383 case spirv::Decoration::NoSignedWrap:
384 case spirv::Decoration::NoUnsignedWrap:
385 case spirv::Decoration::RelaxedPrecision:
386 case spirv::Decoration::Restrict:
387 case spirv::Decoration::RestrictPointer:
388 case spirv::Decoration::NoContraction:
389 case spirv::Decoration::Constant:
390 case spirv::Decoration::Invariant:
391 case spirv::Decoration::Patch:
392 case spirv::Decoration::Coherent:
393 case spirv::Decoration::Volatile:
394 case spirv::Decoration::SaturatedConversion:
395 if (words.size() != 2) {
396 return emitError(unknownLoc, "OpDecorate with ")
397 << decorationName << " needs a single target <id>";
398 }
399 decorations[words[0]].set(symbol, opBuilder.getUnitAttr());
400 break;
401 case spirv::Decoration::CacheControlLoadINTEL: {
402 LogicalResult res = deserializeCacheControlDecoration<
403 CacheControlLoadINTELAttr, LoadCacheControlAttr, LoadCacheControl>(
404 unknownLoc, opBuilder, decorations, words, symbol, decorationName,
405 "load");
406 if (failed(res))
407 return res;
408 break;
409 }
410 case spirv::Decoration::CacheControlStoreINTEL: {
411 LogicalResult res = deserializeCacheControlDecoration<
412 CacheControlStoreINTELAttr, StoreCacheControlAttr, StoreCacheControl>(
413 unknownLoc, opBuilder, decorations, words, symbol, decorationName,
414 "store");
415 if (failed(res))
416 return res;
417 break;
418 }
419 case spirv::Decoration::AlignmentId:
420 case spirv::Decoration::MaxByteOffsetId:
421 case spirv::Decoration::CounterBuffer:
422 if (words.size() != 3) {
423 return emitError(unknownLoc, "OpDecorateId with ")
424 << decorationName << " needs a single <id> operand";
425 }
426 pendingIdDecorations.push_back({words[0],
427 static_cast<spirv::Decoration>(words[1]),
428 words[2], unknownLoc});
429 break;
430 default:
431 return emitError(unknownLoc, "unhandled Decoration : '") << decorationName;
432 }
433 return success();
434}
435
436LogicalResult spirv::Deserializer::resolveDeferredIdDecorations() {
437 for (const DeferredIdDecoration &entry : pendingIdDecorations) {
438 StringRef decorationName = stringifyDecoration(entry.decoration);
439 StringAttr symbol = getSymbolDecoration(decorationName);
440
441 // Resolve the operand <id> to a symbol name. The operand must reference a
442 // module-scope symbol op (global variable or specialization constant).
443 StringRef operandSymName;
444 if (spirv::GlobalVariableOp varOp =
445 globalVariableMap.lookup(entry.operandID))
446 operandSymName = varOp.getSymName();
447 else if (spirv::SpecConstantOp specOp =
448 specConstMap.lookup(entry.operandID))
449 operandSymName = specOp.getSymName();
450 else
451 return emitError(entry.loc, "OpDecorateId with ")
452 << decorationName << " references <id> " << entry.operandID
453 << " which is not a global variable or specialization constant";
454
455 auto symRef = FlatSymbolRefAttr::get(context, operandSymName);
456
457 // Resolve the decoration target. By the time this method runs, all
458 // instructions have been processed, so every defined <id> must appear in
459 // one of these maps; an unresolved target indicates malformed input.
460 Operation *targetOp = nullptr;
461 if (spirv::GlobalVariableOp varOp =
462 globalVariableMap.lookup(entry.targetID))
463 targetOp = varOp;
464 else if (spirv::SpecConstantOp specOp = specConstMap.lookup(entry.targetID))
465 targetOp = specOp;
466 else if (spirv::FuncOp fnOp = funcMap.lookup(entry.targetID))
467 targetOp = fnOp;
468 else if (Value v = valueMap.lookup(entry.targetID))
469 targetOp = v.getDefiningOp();
470
471 if (!targetOp)
472 return emitError(entry.loc, "OpDecorateId with ")
473 << decorationName << " references unknown target <id> "
474 << entry.targetID;
475
476 setInherentOrDiscardableAttr(targetOp, symbol, symRef);
477 }
478 return success();
479}
480
481LogicalResult
482spirv::Deserializer::processMemberDecoration(ArrayRef<uint32_t> words) {
483 // The binary layout of OpMemberDecorate is different comparing to OpDecorate
484 if (words.size() < 3) {
485 return emitError(unknownLoc,
486 "OpMemberDecorate must have at least 3 operands");
487 }
488
489 auto decoration = static_cast<spirv::Decoration>(words[2]);
490 if (decoration == spirv::Decoration::Offset && words.size() != 4) {
491 return emitError(unknownLoc,
492 " missing offset specification in OpMemberDecorate with "
493 "Offset decoration");
494 }
495 ArrayRef<uint32_t> decorationOperands;
496 if (words.size() > 3) {
497 decorationOperands = words.slice(3);
498 }
499 memberDecorationMap[words[0]][words[1]][decoration] = decorationOperands;
500 return success();
501}
502
503LogicalResult spirv::Deserializer::processMemberName(ArrayRef<uint32_t> words) {
504 if (words.size() < 3) {
505 return emitError(unknownLoc, "OpMemberName must have at least 3 operands");
506 }
507 unsigned wordIndex = 2;
508 auto name = decodeStringLiteral(words, wordIndex);
509 if (wordIndex != words.size()) {
510 return emitError(unknownLoc,
511 "unexpected trailing words in OpMemberName instruction");
512 }
513 memberNameMap[words[0]][words[1]] = name;
514 return success();
515}
516
518 uint32_t argID, SmallVectorImpl<Attribute> &argAttrs, size_t argIndex) {
519 spirv::DecorationAttr foundDecorationAttr;
520 NamedAttrList attributes;
521 if (auto it = functionParameterAttrs.find(argID);
522 it != functionParameterAttrs.end()) {
523 attributes.set(spirv::getFuncParamAttrName(), it->second);
524 functionParameterAttrs.erase(it);
525 }
526 for (NamedAttribute decAttr : decorations.lookup(argID)) {
527 if (decAttr.getName() == getSymbolDecoration(stringifyDecoration(
528 spirv::Decoration::Alignment))) {
530 decAttr.getValue());
531 continue;
532 }
533 if (!isa<UnitAttr>(decAttr.getValue()))
534 return emitError(unknownLoc, "unhandled decoration '")
535 << decAttr.getName().getValue()
536 << "' on function argument with result <id> " << argID;
537
538 // TODO: Support multiple decorations per function parameter.
539 if (foundDecorationAttr)
540 return emitError(unknownLoc, "already found a decoration for function "
541 "argument with result <id> ")
542 << argID;
543
544 std::optional<spirv::Decoration> decoration = spirv::symbolizeDecoration(
545 llvm::convertToCamelFromSnakeCase(decAttr.getName(), true));
546 if (!decoration)
547 return emitError(unknownLoc, "unknown decoration '")
548 << decAttr.getName().getValue()
549 << "' on function argument with result <id> " << argID;
550 foundDecorationAttr = spirv::DecorationAttr::get(context, *decoration);
551 }
552
553 if (foundDecorationAttr)
554 attributes.set(spirv::DecorationAttr::name, foundDecorationAttr);
555 argAttrs[argIndex] = attributes.getDictionary(context);
556 return success();
557}
558
559LogicalResult
561 if (curFunction) {
562 return emitError(unknownLoc, "found function inside function");
563 }
564
565 // Get the result type
566 if (operands.size() != 4) {
567 return emitError(unknownLoc, "OpFunction must have 4 parameters");
568 }
569 Type resultType = getType(operands[0]);
570 if (!resultType) {
571 return emitError(unknownLoc, "undefined result type from <id> ")
572 << operands[0];
573 }
574
575 uint32_t fnID = operands[1];
576 if (funcMap.count(fnID)) {
577 return emitError(unknownLoc, "duplicate function definition/declaration");
578 }
579
580 auto fnControl = spirv::symbolizeFunctionControl(operands[2]);
581 if (!fnControl) {
582 return emitError(unknownLoc, "unknown Function Control: ") << operands[2];
583 }
584
585 Type fnType = getType(operands[3]);
586 if (!fnType || !isa<FunctionType>(fnType)) {
587 return emitError(unknownLoc, "unknown function type from <id> ")
588 << operands[3];
589 }
590 auto functionType = cast<FunctionType>(fnType);
591
592 if ((isVoidType(resultType) && functionType.getNumResults() != 0) ||
593 (functionType.getNumResults() == 1 &&
594 functionType.getResult(0) != resultType)) {
595 return emitError(unknownLoc, "mismatch in function type ")
596 << functionType << " and return type " << resultType << " specified";
597 }
598
599 std::string fnName = getFunctionSymbol(fnID);
600 auto funcOp = spirv::FuncOp::create(opBuilder, unknownLoc, fnName,
601 functionType, fnControl.value());
602 if (auto it = functionParameterAttrs.find(fnID);
603 it != functionParameterAttrs.end()) {
604 if (functionType.getNumResults() == 0)
605 return emitError(unknownLoc,
606 "FuncParamAttr decoration requires a non-void function "
607 "result");
608 funcOp.setResultAttr(0, spirv::getFuncParamAttrName(), it->second);
609 functionParameterAttrs.erase(it);
610 }
611 // Processing other function attributes.
612 if (decorations.count(fnID)) {
613 for (auto attr : decorations[fnID].getAttrs()) {
614 setInherentOrDiscardableAttr(funcOp, attr.getName(), attr.getValue());
615 }
616 }
617 curFunction = funcMap[fnID] = funcOp;
618 auto *entryBlock = funcOp.addEntryBlock();
619 LLVM_DEBUG({
620 logger.startLine()
621 << "//===-------------------------------------------===//\n";
622 logger.startLine() << "[fn] name: " << fnName << "\n";
623 logger.startLine() << "[fn] type: " << fnType << "\n";
624 logger.startLine() << "[fn] ID: " << fnID << "\n";
625 logger.startLine() << "[fn] entry block: " << entryBlock << "\n";
626 logger.indent();
627 });
628
629 SmallVector<Attribute> argAttrs;
630 argAttrs.resize(functionType.getNumInputs());
631
632 // Parse the op argument instructions
633 if (functionType.getNumInputs()) {
634 for (size_t i = 0, e = functionType.getNumInputs(); i != e; ++i) {
635 auto argType = functionType.getInput(i);
636 spirv::Opcode opcode = spirv::Opcode::OpNop;
637 ArrayRef<uint32_t> operands;
638 if (failed(sliceInstruction(opcode, operands,
639 spirv::Opcode::OpFunctionParameter))) {
640 return failure();
641 }
642 if (opcode != spirv::Opcode::OpFunctionParameter) {
643 return emitError(
644 unknownLoc,
645 "missing OpFunctionParameter instruction for argument ")
646 << i;
647 }
648 if (operands.size() != 2) {
649 return emitError(
650 unknownLoc,
651 "expected result type and result <id> for OpFunctionParameter");
652 }
653 auto argDefinedType = getType(operands[0]);
654 if (!argDefinedType || argDefinedType != argType) {
655 return emitError(unknownLoc,
656 "mismatch in argument type between function type "
657 "definition ")
658 << functionType << " and argument type definition "
659 << argDefinedType << " at argument " << i;
660 }
661 if (getValue(operands[1])) {
662 return emitError(unknownLoc, "duplicate definition of result <id> ")
663 << operands[1];
664 }
665 if (failed(setFunctionArgAttrs(operands[1], argAttrs, i))) {
666 return failure();
667 }
668
669 auto argValue = funcOp.getArgument(i);
670 valueMap[operands[1]] = argValue;
671 }
672 }
673
674 if (llvm::any_of(argAttrs, [](Attribute attr) {
675 auto argAttr = cast<DictionaryAttr>(attr);
676 return !argAttr.empty();
677 }))
678 funcOp.setArgAttrsAttr(ArrayAttr::get(context, argAttrs));
679
680 // entryBlock is needed to access the arguments, Once that is done, we can
681 // erase the block for functions with 'Import' LinkageAttributes, since these
682 // are essentially function declarations, so they have no body.
683 auto linkageAttr = funcOp.getLinkageAttributes();
684 auto hasImportLinkage =
685 linkageAttr && (linkageAttr.value().getLinkageType().getValue() ==
686 spirv::LinkageType::Import);
687 if (hasImportLinkage)
688 funcOp.eraseBody();
689
690 // RAII guard to reset the insertion point to the module's region after
691 // deserializing the body of this function.
692 OpBuilder::InsertionGuard moduleInsertionGuard(opBuilder);
693
694 spirv::Opcode opcode = spirv::Opcode::OpNop;
695 ArrayRef<uint32_t> instOperands;
696
697 // Special handling for the entry block. We need to make sure it starts with
698 // an OpLabel instruction. The entry block takes the same parameters as the
699 // function. All other blocks do not take any parameter. We have already
700 // created the entry block, here we need to register it to the correct label
701 // <id>.
702 if (failed(sliceInstruction(opcode, instOperands,
703 spirv::Opcode::OpFunctionEnd))) {
704 return failure();
705 }
706 if (opcode == spirv::Opcode::OpFunctionEnd) {
707 return processFunctionEnd(instOperands);
708 }
709 if (opcode != spirv::Opcode::OpLabel) {
710 return emitError(unknownLoc, "a basic block must start with OpLabel");
711 }
712 if (instOperands.size() != 1) {
713 return emitError(unknownLoc, "OpLabel should only have result <id>");
714 }
715 blockMap[instOperands[0]] = entryBlock;
716 if (failed(processLabel(instOperands))) {
717 return failure();
718 }
719
720 // Then process all the other instructions in the function until we hit
721 // OpFunctionEnd.
722 while (succeeded(sliceInstruction(opcode, instOperands,
723 spirv::Opcode::OpFunctionEnd)) &&
724 opcode != spirv::Opcode::OpFunctionEnd) {
725 if (failed(processInstruction(opcode, instOperands))) {
726 return failure();
727 }
728 }
729 if (opcode != spirv::Opcode::OpFunctionEnd) {
730 return failure();
731 }
732
733 return processFunctionEnd(instOperands);
734}
735
736LogicalResult
738 // Process OpFunctionEnd.
739 if (!operands.empty()) {
740 return emitError(unknownLoc, "unexpected operands for OpFunctionEnd");
741 }
742
743 // Wire up block arguments from OpPhi instructions.
744 // Put all structured control flow in spirv.mlir.selection/spirv.mlir.loop
745 // ops.
746 if (failed(wireUpBlockArgument()) || failed(structurizeControlFlow())) {
747 return failure();
748 }
749
750 blockConstantMap.clear();
751 curBlock = nullptr;
752 curFunction = std::nullopt;
753
754 LLVM_DEBUG({
755 logger.unindent();
756 logger.startLine()
757 << "//===-------------------------------------------===//\n";
758 });
759 return success();
760}
761
762LogicalResult
764 if (operands.size() < 2) {
765 return emitError(unknownLoc,
766 "missing graph defintion in OpGraphEntryPointARM");
767 }
768
769 unsigned wordIndex = 0;
770 uint32_t graphID = operands[wordIndex++];
771 if (!graphMap.contains(graphID)) {
772 return emitError(unknownLoc,
773 "missing graph definition/declaration with id ")
774 << graphID;
775 }
776
777 spirv::GraphARMOp graphARM = graphMap[graphID];
778 StringRef name = decodeStringLiteral(operands, wordIndex);
779 graphARM.setSymName(name);
780 graphARM.setEntryPoint(true);
781
783 for (int64_t size = operands.size(); wordIndex < size; ++wordIndex) {
784 if (spirv::GlobalVariableOp arg = getGlobalVariable(operands[wordIndex])) {
785 interface.push_back(SymbolRefAttr::get(arg.getOperation()));
786 } else {
787 return emitError(unknownLoc, "undefined result <id> ")
788 << operands[wordIndex] << " while decoding OpGraphEntryPoint";
789 }
790 }
791
792 // RAII guard to reset the insertion point to previous value when done.
793 OpBuilder::InsertionGuard insertionGuard(opBuilder);
794 opBuilder.setInsertionPoint(graphARM);
795 spirv::GraphEntryPointARMOp::create(
796 opBuilder, unknownLoc, SymbolRefAttr::get(opBuilder.getContext(), name),
797 opBuilder.getArrayAttr(interface));
798
799 return success();
800}
801
802LogicalResult
804 if (curGraph) {
805 return emitError(unknownLoc, "found graph inside graph");
806 }
807 // Get the result type.
808 if (operands.size() < 2) {
809 return emitError(unknownLoc, "OpGraphARM must have at least 2 parameters");
810 }
811
812 Type type = getType(operands[0]);
813 if (!type || !isa<GraphType>(type)) {
814 return emitError(unknownLoc, "unknown graph type from <id> ")
815 << operands[0];
816 }
817 auto graphType = cast<GraphType>(type);
818 if (graphType.getNumResults() <= 0) {
819 return emitError(unknownLoc, "expected at least one result");
820 }
821
822 uint32_t graphID = operands[1];
823 if (graphMap.count(graphID)) {
824 return emitError(unknownLoc, "duplicate graph definition/declaration");
825 }
826
827 std::string graphName = getGraphSymbol(graphID);
828 auto graphOp =
829 spirv::GraphARMOp::create(opBuilder, unknownLoc, graphName, graphType);
830 curGraph = graphMap[graphID] = graphOp;
831 Block *entryBlock = graphOp.addEntryBlock();
832 LLVM_DEBUG({
833 logger.startLine()
834 << "//===-------------------------------------------===//\n";
835 logger.startLine() << "[graph] name: " << graphName << "\n";
836 logger.startLine() << "[graph] type: " << graphType << "\n";
837 logger.startLine() << "[graph] ID: " << graphID << "\n";
838 logger.startLine() << "[graph] entry block: " << entryBlock << "\n";
839 logger.indent();
840 });
841
842 // Parse the op argument instructions.
843 for (auto [index, argType] : llvm::enumerate(graphType.getInputs())) {
844 spirv::Opcode opcode;
845 ArrayRef<uint32_t> operands;
846 if (failed(sliceInstruction(opcode, operands,
847 spirv::Opcode::OpGraphInputARM))) {
848 return failure();
849 }
850 if (operands.size() != 3) {
851 return emitError(unknownLoc, "expected result type, result <id> and "
852 "input index for OpGraphInputARM");
853 }
854
855 Type argDefinedType = getType(operands[0]);
856 if (!argDefinedType) {
857 return emitError(unknownLoc, "unknown operand type <id> ") << operands[0];
858 }
859
860 if (argDefinedType != argType) {
861 return emitError(unknownLoc,
862 "mismatch in argument type between graph type "
863 "definition ")
864 << graphType << " and argument type definition " << argDefinedType
865 << " at argument " << index;
866 }
867 if (getValue(operands[1])) {
868 return emitError(unknownLoc, "duplicate definition of result <id> ")
869 << operands[1];
870 }
871
872 IntegerAttr inputIndexAttr = getConstantInt(operands[2]);
873 if (!inputIndexAttr) {
874 return emitError(unknownLoc,
875 "unable to read inputIndex value from constant op ")
876 << operands[2];
877 }
878 BlockArgument argValue = graphOp.getArgument(inputIndexAttr.getInt());
879 valueMap[operands[1]] = argValue;
880 }
881
882 graphOutputs.resize(graphType.getNumResults());
883
884 // RAII guard to reset the insertion point to the module's region after
885 // deserializing the body of this function.
886 OpBuilder::InsertionGuard moduleInsertionGuard(opBuilder);
887
888 blockMap[graphID] = entryBlock;
889 if (failed(createGraphBlock(graphID))) {
890 return failure();
891 }
892
893 // Process all the instructions in the graph until and including
894 // OpGraphEndARM.
895 spirv::Opcode opcode;
896 ArrayRef<uint32_t> instOperands;
897 do {
898 if (failed(sliceInstruction(opcode, instOperands, std::nullopt))) {
899 return failure();
900 }
901
902 if (failed(processInstruction(opcode, instOperands))) {
903 return failure();
904 }
905 } while (opcode != spirv::Opcode::OpGraphEndARM);
906
907 return success();
908}
909
910LogicalResult
912 if (operands.size() != 2) {
913 return emitError(
914 unknownLoc,
915 "expected value id and output index for OpGraphSetOutputARM");
916 }
917
918 uint32_t id = operands[0];
919 Value value = getValue(id);
920 if (!value) {
921 return emitError(unknownLoc, "could not find result <id> ") << id;
922 }
923
924 IntegerAttr outputIndexAttr = getConstantInt(operands[1]);
925 if (!outputIndexAttr) {
926 return emitError(unknownLoc,
927 "unable to read outputIndex value from constant op ")
928 << operands[1];
929 }
930 graphOutputs[outputIndexAttr.getInt()] = value;
931 return success();
932}
933
934LogicalResult
936 // Create GraphOutputsARM instruction.
937 spirv::GraphOutputsARMOp::create(opBuilder, unknownLoc, graphOutputs);
938
939 // Process OpGraphEndARM.
940 if (!operands.empty()) {
941 return emitError(unknownLoc, "unexpected operands for OpGraphEndARM");
942 }
943
944 blockConstantMap.clear();
945 curBlock = nullptr;
946 curGraph = std::nullopt;
947 graphOutputs.clear();
948
949 LLVM_DEBUG({
950 logger.unindent();
951 logger.startLine()
952 << "//===-------------------------------------------===//\n";
953 });
954 return success();
955}
956
957std::optional<std::pair<Attribute, Type>>
959 auto constIt = constantMap.find(id);
960 if (constIt != constantMap.end())
961 return constIt->getSecond();
962
963 auto replicatedConstIt = constantCompositeReplicateMap.find(id);
964 if (replicatedConstIt == constantCompositeReplicateMap.end())
965 return std::nullopt;
966
967 auto [value, type] = replicatedConstIt->getSecond();
968 auto shapedType = dyn_cast<ShapedType>(type);
969 if (!shapedType)
970 return std::nullopt;
971 return std::make_pair(SplatElementsAttr::get(shapedType, value), type);
972}
973
974std::optional<std::pair<Attribute, Type>>
976 if (auto it = constantCompositeReplicateMap.find(id);
977 it != constantCompositeReplicateMap.end())
978 return it->second;
979 return std::nullopt;
980}
981
982std::optional<spirv::SpecConstOperationMaterializationInfo>
984 auto constIt = specConstOperationMap.find(id);
985 if (constIt == specConstOperationMap.end())
986 return std::nullopt;
987 return constIt->getSecond();
988}
989
990std::optional<std::pair<Type, SmallVector<uint32_t>>>
992 if (auto it = undefCompositeMap.find(id); it != undefCompositeMap.end())
993 return it->second;
994 return std::nullopt;
995}
996
998 auto funcName = nameMap.lookup(id).str();
999 if (funcName.empty()) {
1000 funcName = "spirv_fn_" + std::to_string(id);
1001 }
1002 return funcName;
1003}
1004
1005std::string spirv::Deserializer::getGraphSymbol(uint32_t id) {
1006 std::string graphName = nameMap.lookup(id).str();
1007 if (graphName.empty()) {
1008 graphName = "spirv_graph_" + std::to_string(id);
1009 }
1010 return graphName;
1011}
1012
1014 auto constName = nameMap.lookup(id).str();
1015 if (constName.empty()) {
1016 constName = "spirv_spec_const_" + std::to_string(id);
1017 }
1018 return constName;
1019}
1020
1021spirv::SpecConstantOp
1023 TypedAttr defaultValue) {
1024 auto symName = opBuilder.getStringAttr(getSpecConstantSymbol(resultID));
1025 auto op = spirv::SpecConstantOp::create(opBuilder, unknownLoc, symName,
1026 defaultValue,
1027 /*sym_visibility=*/nullptr);
1028 if (decorations.count(resultID)) {
1029 for (auto attr : decorations[resultID].getAttrs())
1030 setInherentOrDiscardableAttr(op, attr.getName(), attr.getValue());
1031 }
1032 specConstMap[resultID] = op;
1033 return op;
1034}
1035
1036std::optional<spirv::GraphConstantARMOpMaterializationInfo>
1038 auto graphConstIt = graphConstantMap.find(id);
1039 if (graphConstIt == graphConstantMap.end())
1040 return std::nullopt;
1041 return graphConstIt->getSecond();
1042}
1043
1044LogicalResult
1046 ArrayRef<uint32_t> operands) {
1047 StringRef opName = spirv::stringifyOpcode(opcode);
1048 bool isUntyped = opcode == spirv::Opcode::OpUntypedVariableKHR;
1049 unsigned wordIndex = 0;
1050 if (operands.size() < 3) {
1051 return emitError(unknownLoc, opName)
1052 << " needs at least 3 operands, type, <id> and storage class";
1053 }
1054
1055 // Result Type.
1056 auto type = getType(operands[wordIndex]);
1057 if (!type) {
1058 return emitError(unknownLoc, "unknown result type <id> : ")
1059 << operands[wordIndex];
1060 }
1061 std::optional<spirv::StorageClass> ptrStorageClass;
1062 if (isUntyped) {
1063 if (auto ptrType = dyn_cast<spirv::UntypedPointerType>(type))
1064 ptrStorageClass = ptrType.getStorageClass();
1065 } else if (auto ptrType = dyn_cast<spirv::PointerType>(type)) {
1066 ptrStorageClass = ptrType.getStorageClass();
1067 }
1068 if (!ptrStorageClass) {
1069 return emitError(unknownLoc, "expected a result type <id> to be a ")
1070 << (isUntyped ? "spirv.untyped_ptr" : "spirv.ptr")
1071 << ", found : " << type;
1072 }
1073 wordIndex++;
1074
1075 // Result <id>.
1076 auto variableID = operands[wordIndex];
1077 auto variableName = nameMap.lookup(variableID).str();
1078 if (variableName.empty()) {
1079 variableName = "spirv_var_" + std::to_string(variableID);
1080 }
1081 wordIndex++;
1082
1083 // Storage class.
1084 auto storageClass = static_cast<spirv::StorageClass>(operands[wordIndex]);
1085 if (*ptrStorageClass != storageClass) {
1086 return emitError(unknownLoc, "mismatch in storage class of pointer type ")
1087 << type << " and that specified in " << opName
1088 << " instruction : " << stringifyStorageClass(storageClass);
1089 }
1090 wordIndex++;
1091
1092 // Data Type. An Initializer requires it, so it always comes first.
1093 TypeAttr dataType;
1094 if (isUntyped && wordIndex < operands.size()) {
1095 Type objectType = getType(operands[wordIndex]);
1096 if (!objectType) {
1097 return emitError(unknownLoc, "unknown data type <id> : ")
1098 << operands[wordIndex];
1099 }
1100 dataType = TypeAttr::get(objectType);
1101 wordIndex++;
1102 }
1103
1104 // Initializer.
1105 FlatSymbolRefAttr initializer = nullptr;
1106
1107 if (wordIndex < operands.size()) {
1108 Operation *op = nullptr;
1109
1110 if (auto initOp = getGlobalVariable(operands[wordIndex]))
1111 op = initOp;
1112 else if (auto initOp = getSpecConstant(operands[wordIndex]))
1113 op = initOp;
1114 else if (auto initOp = getSpecConstantComposite(operands[wordIndex]))
1115 op = initOp;
1116 else
1117 return emitError(unknownLoc, "unknown <id> ")
1118 << operands[wordIndex] << "used as initializer";
1119
1120 initializer = SymbolRefAttr::get(op);
1121 wordIndex++;
1122 }
1123 if (wordIndex != operands.size()) {
1124 return emitError(unknownLoc,
1125 "found more operands than expected when deserializing ")
1126 << opName << " instruction, only " << wordIndex << " of "
1127 << operands.size() << " processed";
1128 }
1129 auto loc = createFileLineColLoc(opBuilder);
1130 auto varOp = spirv::GlobalVariableOp::create(
1131 opBuilder, loc, TypeAttr::get(type),
1132 opBuilder.getStringAttr(variableName), initializer);
1133 if (dataType)
1134 varOp.setDataTypeAttr(dataType);
1135
1136 // Decorations.
1137 if (decorations.count(variableID)) {
1138 for (auto attr : decorations[variableID].getAttrs())
1139 setInherentOrDiscardableAttr(varOp, attr.getName(), attr.getValue());
1140 }
1141 globalVariableMap[variableID] = varOp;
1142 return success();
1143}
1144
1145IntegerAttr spirv::Deserializer::getConstantInt(uint32_t id) {
1146 auto constInfo = getConstant(id);
1147 if (!constInfo) {
1148 return nullptr;
1149 }
1150 return dyn_cast<IntegerAttr>(constInfo->first);
1151}
1152
1153LogicalResult spirv::Deserializer::processName(ArrayRef<uint32_t> operands) {
1154 if (operands.size() < 2) {
1155 return emitError(unknownLoc, "OpName needs at least 2 operands");
1156 }
1157
1158 unsigned wordIndex = 1;
1159 StringRef name = decodeStringLiteral(operands, wordIndex);
1160 if (wordIndex != operands.size()) {
1161 return emitError(unknownLoc,
1162 "unexpected trailing words in OpName instruction");
1163 }
1164
1165 // In SPIRV it's valid for multiple OpName instructions to refer to the same
1166 // <id>. Use a "last one wins" approach to resolve such cases.
1167 nameMap.emplace_or_assign(operands[0], name);
1168
1169 return success();
1170}
1171
1172//===----------------------------------------------------------------------===//
1173// Type
1174//===----------------------------------------------------------------------===//
1175
1176LogicalResult spirv::Deserializer::processType(spirv::Opcode opcode,
1177 ArrayRef<uint32_t> operands) {
1178 if (operands.empty()) {
1179 return emitError(unknownLoc, "type instruction with opcode ")
1180 << spirv::stringifyOpcode(opcode) << " needs at least one <id>";
1181 }
1182
1183 /// TODO: Types might be forward declared in some instructions and need to be
1184 /// handled appropriately.
1185 if (typeMap.count(operands[0])) {
1186 return emitError(unknownLoc, "duplicate definition for result <id> ")
1187 << operands[0];
1188 }
1189
1190 switch (opcode) {
1191 case spirv::Opcode::OpTypeVoid:
1192 if (operands.size() != 1)
1193 return emitError(unknownLoc, "OpTypeVoid must have no parameters");
1194 typeMap[operands[0]] = opBuilder.getNoneType();
1195 break;
1196 case spirv::Opcode::OpTypeBool:
1197 if (operands.size() != 1)
1198 return emitError(unknownLoc, "OpTypeBool must have no parameters");
1199 typeMap[operands[0]] = opBuilder.getI1Type();
1200 break;
1201 case spirv::Opcode::OpTypeInt: {
1202 if (operands.size() != 3)
1203 return emitError(
1204 unknownLoc, "OpTypeInt must have bitwidth and signedness parameters");
1205
1206 // SPIR-V OpTypeInt "Signedness specifies whether there are signed semantics
1207 // to preserve or validate.
1208 // 0 indicates unsigned, or no signedness semantics
1209 // 1 indicates signed semantics."
1210 //
1211 // So we cannot differentiate signless and unsigned integers; always use
1212 // signless semantics for such cases.
1213 auto sign = operands[2] == 1 ? IntegerType::SignednessSemantics::Signed
1214 : IntegerType::SignednessSemantics::Signless;
1215 typeMap[operands[0]] = IntegerType::get(context, operands[1], sign);
1216 } break;
1217 case spirv::Opcode::OpTypeFloat: {
1218 if (operands.size() != 2 && operands.size() != 3)
1219 return emitError(unknownLoc,
1220 "OpTypeFloat expects either 2 operands (type, bitwidth) "
1221 "or 3 operands (type, bitwidth, encoding), but got ")
1222 << operands.size();
1223 uint32_t bitWidth = operands[1];
1224
1225 Type floatTy;
1226 if (operands.size() == 2) {
1227 switch (bitWidth) {
1228 case 16:
1229 floatTy = opBuilder.getF16Type();
1230 break;
1231 case 32:
1232 floatTy = opBuilder.getF32Type();
1233 break;
1234 case 64:
1235 floatTy = opBuilder.getF64Type();
1236 break;
1237 default:
1238 return emitError(unknownLoc, "unsupported OpTypeFloat bitwidth: ")
1239 << bitWidth;
1240 }
1241 }
1242
1243 if (operands.size() == 3) {
1244 if (spirv::FPEncoding(operands[2]) == spirv::FPEncoding::BFloat16KHR &&
1245 bitWidth == 16)
1246 floatTy = opBuilder.getBF16Type();
1247 else if (spirv::FPEncoding(operands[2]) ==
1248 spirv::FPEncoding::Float8E4M3EXT &&
1249 bitWidth == 8)
1250 floatTy = opBuilder.getF8E4M3FNType();
1251 else if (spirv::FPEncoding(operands[2]) ==
1252 spirv::FPEncoding::Float8E5M2EXT &&
1253 bitWidth == 8)
1254 floatTy = opBuilder.getF8E5M2Type();
1255 else if (spirv::FPEncoding(operands[2]) ==
1256 spirv::FPEncoding::Float4E2M1EXT &&
1257 bitWidth == 4)
1258 floatTy = Float4E2M1FNType::get(context);
1259 else if (spirv::FPEncoding(operands[2]) ==
1260 spirv::FPEncoding::Float6E2M3EXT &&
1261 bitWidth == 6)
1262 floatTy = Float6E2M3FNType::get(context);
1263 else if (spirv::FPEncoding(operands[2]) ==
1264 spirv::FPEncoding::Float6E3M2EXT &&
1265 bitWidth == 6)
1266 floatTy = Float6E3M2FNType::get(context);
1267 else if (spirv::FPEncoding(operands[2]) ==
1268 spirv::FPEncoding::Float8UnsignedE8M0EXT &&
1269 bitWidth == 8)
1270 floatTy = opBuilder.getF8E8M0Type();
1271 else
1272 return emitError(unknownLoc, "unsupported OpTypeFloat FP encoding: ")
1273 << operands[2] << " and bitWidth " << bitWidth;
1274 }
1275
1276 typeMap[operands[0]] = floatTy;
1277 } break;
1278 case spirv::Opcode::OpTypeVector: {
1279 if (operands.size() != 3) {
1280 return emitError(
1281 unknownLoc,
1282 "OpTypeVector must have element type and count parameters");
1283 }
1284 Type elementTy = getType(operands[1]);
1285 if (!elementTy) {
1286 return emitError(unknownLoc, "OpTypeVector references undefined <id> ")
1287 << operands[1];
1288 }
1289 typeMap[operands[0]] = VectorType::get({operands[2]}, elementTy);
1290 } break;
1291 case spirv::Opcode::OpTypePointer: {
1292 return processOpTypePointer(operands);
1293 } break;
1294 case spirv::Opcode::OpTypeArray:
1295 return processArrayType(operands);
1296 case spirv::Opcode::OpTypeCooperativeMatrixKHR:
1297 return processCooperativeMatrixTypeKHR(operands);
1298 case spirv::Opcode::OpTypeFunction:
1299 return processFunctionType(operands);
1300 case spirv::Opcode::OpTypeImage:
1301 return processImageType(operands);
1302 case spirv::Opcode::OpTypeSampler:
1303 return processSamplerType(operands);
1304 case spirv::Opcode::OpTypeNamedBarrier:
1305 return processNamedBarrierType(operands);
1306 case spirv::Opcode::OpTypeUntypedPointerKHR:
1307 return processUntypedPointerType(operands);
1308 case spirv::Opcode::OpTypeSampledImage:
1309 return processSampledImageType(operands);
1310 case spirv::Opcode::OpTypeRuntimeArray:
1311 return processRuntimeArrayType(operands);
1312 case spirv::Opcode::OpTypeStruct:
1313 return processStructType(operands);
1314 case spirv::Opcode::OpTypeMatrix:
1315 return processMatrixType(operands);
1316 case spirv::Opcode::OpTypeTensorARM:
1317 return processTensorARMType(operands);
1318 case spirv::Opcode::OpTypeGraphARM:
1319 return processGraphTypeARM(operands);
1320 default:
1321 return emitError(unknownLoc, "unhandled type instruction");
1322 }
1323 return success();
1324}
1325
1326LogicalResult
1328 if (operands.size() != 3)
1329 return emitError(unknownLoc, "OpTypePointer must have two parameters");
1330
1331 auto pointeeType = getType(operands[2]);
1332 if (!pointeeType)
1333 return emitError(unknownLoc, "unknown OpTypePointer pointee type <id> ")
1334 << operands[2];
1335
1336 uint32_t typePointerID = operands[0];
1337 auto storageClass = static_cast<spirv::StorageClass>(operands[1]);
1338 auto pointerType =
1339 spirv::PointerType::getChecked([&] { return emitError(unknownLoc); },
1340 context, pointeeType, storageClass);
1341 if (!pointerType)
1342 return failure();
1343 typeMap[typePointerID] = pointerType;
1344
1345 for (auto *deferredStructIt = std::begin(deferredStructTypesInfos);
1346 deferredStructIt != std::end(deferredStructTypesInfos);) {
1347 for (auto *unresolvedMemberIt =
1348 std::begin(deferredStructIt->unresolvedMemberTypes);
1349 unresolvedMemberIt !=
1350 std::end(deferredStructIt->unresolvedMemberTypes);) {
1351 if (unresolvedMemberIt->first == typePointerID) {
1352 // The newly constructed pointer type can resolve one of the
1353 // deferred struct type members; update the memberTypes list and
1354 // clean the unresolvedMemberTypes list accordingly.
1355 deferredStructIt->memberTypes[unresolvedMemberIt->second] =
1356 typeMap[typePointerID];
1357 unresolvedMemberIt =
1358 deferredStructIt->unresolvedMemberTypes.erase(unresolvedMemberIt);
1359 } else {
1360 ++unresolvedMemberIt;
1361 }
1362 }
1363
1364 if (deferredStructIt->unresolvedMemberTypes.empty()) {
1365 // All deferred struct type members are now resolved, set the struct body.
1366 auto structType = deferredStructIt->deferredStructType;
1367
1368 assert(structType && "expected a spirv::StructType");
1369 assert(structType.isIdentified() && "expected an indentified struct");
1370
1371 if (failed(structType.trySetBody(
1372 deferredStructIt->memberTypes, deferredStructIt->offsetInfo,
1373 deferredStructIt->memberDecorationsInfo,
1374 deferredStructIt->structDecorationsInfo)))
1375 return failure();
1376
1377 deferredStructIt = deferredStructTypesInfos.erase(deferredStructIt);
1378 } else {
1379 ++deferredStructIt;
1380 }
1381 }
1382
1383 return success();
1384}
1385
1386LogicalResult
1388 if (operands.size() != 3) {
1389 return emitError(unknownLoc,
1390 "OpTypeArray must have element type and count parameters");
1391 }
1392
1393 Type elementTy = getType(operands[1]);
1394 if (!elementTy) {
1395 return emitError(unknownLoc, "OpTypeArray references undefined <id> ")
1396 << operands[1];
1397 }
1398
1399 unsigned count = 0;
1400 // TODO: The count can also come frome a specialization constant.
1401 auto countInfo = getConstant(operands[2]);
1402 if (!countInfo) {
1403 return emitError(unknownLoc, "OpTypeArray count <id> ")
1404 << operands[2] << "can only come from normal constant right now";
1405 }
1406
1407 if (auto intVal = dyn_cast<IntegerAttr>(countInfo->first)) {
1408 count = intVal.getValue().getZExtValue();
1409 } else {
1410 return emitError(unknownLoc, "OpTypeArray count must come from a "
1411 "scalar integer constant instruction");
1412 }
1413
1414 typeMap[operands[0]] = spirv::ArrayType::get(
1415 elementTy, count, typeDecorations.lookup(operands[0]));
1416 return success();
1417}
1418
1419LogicalResult
1421 assert(!operands.empty() && "No operands for processing function type");
1422 if (operands.size() == 1) {
1423 return emitError(unknownLoc, "missing return type for OpTypeFunction");
1424 }
1425 auto returnType = getType(operands[1]);
1426 if (!returnType) {
1427 return emitError(unknownLoc, "unknown return type in OpTypeFunction");
1428 }
1429 SmallVector<Type, 1> argTypes;
1430 for (size_t i = 2, e = operands.size(); i < e; ++i) {
1431 auto ty = getType(operands[i]);
1432 if (!ty) {
1433 return emitError(unknownLoc, "unknown argument type in OpTypeFunction");
1434 }
1435 argTypes.push_back(ty);
1436 }
1437 ArrayRef<Type> returnTypes;
1438 if (!isVoidType(returnType)) {
1439 returnTypes = llvm::ArrayRef(returnType);
1440 }
1441 typeMap[operands[0]] = FunctionType::get(context, argTypes, returnTypes);
1442 return success();
1443}
1444
1446 ArrayRef<uint32_t> operands) {
1447 if (operands.size() != 6) {
1448 return emitError(unknownLoc,
1449 "OpTypeCooperativeMatrixKHR must have element type, "
1450 "scope, row and column parameters, and use");
1451 }
1452
1453 Type elementTy = getType(operands[1]);
1454 if (!elementTy) {
1455 return emitError(unknownLoc,
1456 "OpTypeCooperativeMatrixKHR references undefined <id> ")
1457 << operands[1];
1458 }
1459
1460 std::optional<spirv::Scope> scope =
1461 spirv::symbolizeScope(getConstantInt(operands[2]).getInt());
1462 if (!scope) {
1463 return emitError(
1464 unknownLoc,
1465 "OpTypeCooperativeMatrixKHR references undefined scope <id> ")
1466 << operands[2];
1467 }
1468
1469 IntegerAttr rowsAttr = getConstantInt(operands[3]);
1470 IntegerAttr columnsAttr = getConstantInt(operands[4]);
1471 IntegerAttr useAttr = getConstantInt(operands[5]);
1472
1473 if (!rowsAttr)
1474 return emitError(unknownLoc, "OpTypeCooperativeMatrixKHR `Rows` references "
1475 "undefined constant <id> ")
1476 << operands[3];
1477
1478 if (!columnsAttr)
1479 return emitError(unknownLoc, "OpTypeCooperativeMatrixKHR `Columns` "
1480 "references undefined constant <id> ")
1481 << operands[4];
1482
1483 if (!useAttr)
1484 return emitError(unknownLoc, "OpTypeCooperativeMatrixKHR `Use` references "
1485 "undefined constant <id> ")
1486 << operands[5];
1487
1488 unsigned rows = rowsAttr.getInt();
1489 unsigned columns = columnsAttr.getInt();
1490
1491 std::optional<spirv::CooperativeMatrixUseKHR> use =
1492 spirv::symbolizeCooperativeMatrixUseKHR(useAttr.getInt());
1493 if (!use) {
1494 return emitError(
1495 unknownLoc,
1496 "OpTypeCooperativeMatrixKHR references undefined use <id> ")
1497 << operands[5];
1498 }
1499
1500 typeMap[operands[0]] = spirv::CooperativeMatrixType::getChecked(
1501 [&] { return emitError(unknownLoc); }, context, elementTy, rows, columns,
1502 *scope, *use);
1503 return success(static_cast<bool>(typeMap[operands[0]]));
1504}
1505
1506LogicalResult
1508 if (operands.size() != 2) {
1509 return emitError(unknownLoc, "OpTypeRuntimeArray must have two operands");
1510 }
1511 Type memberType = getType(operands[1]);
1512 if (!memberType) {
1513 return emitError(unknownLoc,
1514 "OpTypeRuntimeArray references undefined <id> ")
1515 << operands[1];
1516 }
1517 typeMap[operands[0]] = spirv::RuntimeArrayType::get(
1518 memberType, typeDecorations.lookup(operands[0]));
1519 return success();
1520}
1521
1522LogicalResult
1524 // TODO: Find a way to handle identified structs when debug info is stripped.
1525
1526 if (operands.empty()) {
1527 return emitError(unknownLoc, "OpTypeStruct must have at least result <id>");
1528 }
1529
1530 if (operands.size() == 1) {
1531 // Handle empty struct.
1532 typeMap[operands[0]] =
1533 spirv::StructType::getEmpty(context, nameMap.lookup(operands[0]).str());
1534 return success();
1535 }
1536
1537 // First element is operand ID, second element is member index in the struct.
1538 SmallVector<std::pair<uint32_t, unsigned>, 0> unresolvedMemberTypes;
1539 SmallVector<Type, 4> memberTypes;
1540
1541 for (auto op : llvm::drop_begin(operands, 1)) {
1542 Type memberType = getType(op);
1543 bool typeForwardPtr = (typeForwardPointerIDs.count(op) != 0);
1544
1545 if (!memberType && !typeForwardPtr)
1546 return emitError(unknownLoc, "OpTypeStruct references undefined <id> ")
1547 << op;
1548
1549 if (!memberType)
1550 unresolvedMemberTypes.emplace_back(op, memberTypes.size());
1551
1552 memberTypes.push_back(memberType);
1553 }
1554
1557 if (memberDecorationMap.count(operands[0])) {
1558 auto &allMemberDecorations = memberDecorationMap[operands[0]];
1559 for (auto memberIndex : llvm::seq<uint32_t>(0, memberTypes.size())) {
1560 if (allMemberDecorations.count(memberIndex)) {
1561 for (auto &memberDecoration : allMemberDecorations[memberIndex]) {
1562 // Check for offset.
1563 if (memberDecoration.first == spirv::Decoration::Offset) {
1564 // If offset info is empty, resize to the number of members;
1565 if (offsetInfo.empty()) {
1566 offsetInfo.resize(memberTypes.size());
1567 }
1568 offsetInfo[memberIndex] = memberDecoration.second[0];
1569 } else {
1570 auto intType = mlir::IntegerType::get(context, 32);
1571 if (!memberDecoration.second.empty()) {
1572 memberDecorationsInfo.emplace_back(
1573 memberIndex, memberDecoration.first,
1574 IntegerAttr::get(intType, memberDecoration.second[0]));
1575 } else {
1576 memberDecorationsInfo.emplace_back(
1577 memberIndex, memberDecoration.first, UnitAttr::get(context));
1578 }
1579 }
1580 }
1581 }
1582 }
1583 }
1584
1586 if (decorations.count(operands[0])) {
1587 NamedAttrList &allDecorations = decorations[operands[0]];
1588 for (NamedAttribute &decorationAttr : allDecorations) {
1589 std::optional<spirv::Decoration> decoration = spirv::symbolizeDecoration(
1590 llvm::convertToCamelFromSnakeCase(decorationAttr.getName(), true));
1591 assert(decoration.has_value());
1592 structDecorationsInfo.emplace_back(decoration.value(),
1593 decorationAttr.getValue());
1594 }
1595 }
1596
1597 uint32_t structID = operands[0];
1598 std::string structIdentifier = nameMap.lookup(structID).str();
1599
1600 if (structIdentifier.empty()) {
1601 assert(unresolvedMemberTypes.empty() &&
1602 "didn't expect unresolved member types");
1603 typeMap[structID] = spirv::StructType::get(
1604 memberTypes, offsetInfo, memberDecorationsInfo, structDecorationsInfo);
1605 } else {
1606 auto structTy = spirv::StructType::getIdentified(context, structIdentifier);
1607 typeMap[structID] = structTy;
1608
1609 if (!unresolvedMemberTypes.empty())
1610 deferredStructTypesInfos.push_back(
1611 {structTy, std::move(unresolvedMemberTypes), std::move(memberTypes),
1612 std::move(offsetInfo), std::move(memberDecorationsInfo),
1613 std::move(structDecorationsInfo)});
1614 else if (failed(structTy.trySetBody(memberTypes, offsetInfo,
1615 memberDecorationsInfo,
1616 structDecorationsInfo)))
1617 return failure();
1618 }
1619
1620 // TODO: Update StructType to have member name as attribute as
1621 // well.
1622 return success();
1623}
1624
1625LogicalResult
1627 if (operands.size() != 3) {
1628 // Three operands are needed: result_id, column_type, and column_count
1629 return emitError(unknownLoc, "OpTypeMatrix must have 3 operands"
1630 " (result_id, column_type, and column_count)");
1631 }
1632 // Matrix columns must be of vector type
1633 Type elementTy = getType(operands[1]);
1634 if (!elementTy) {
1635 return emitError(unknownLoc,
1636 "OpTypeMatrix references undefined column type.")
1637 << operands[1];
1638 }
1639
1640 uint32_t colsCount = operands[2];
1641 typeMap[operands[0]] = spirv::MatrixType::getChecked(
1642 [&] { return emitError(unknownLoc); }, elementTy, colsCount);
1643 return success(static_cast<bool>(typeMap[operands[0]]));
1644}
1645
1646LogicalResult
1648 unsigned size = operands.size();
1649 if (size < 2 || size > 4)
1650 return emitError(unknownLoc, "OpTypeTensorARM must have 2-4 operands "
1651 "(result_id, element_type, (rank), (shape)) ")
1652 << size;
1653
1654 Type elementTy = getType(operands[1]);
1655 if (!elementTy)
1656 return emitError(unknownLoc,
1657 "OpTypeTensorARM references undefined element type ")
1658 << operands[1];
1659
1660 if (size == 2) {
1661 typeMap[operands[0]] = TensorArmType::get({}, elementTy);
1662 return success();
1663 }
1664
1665 IntegerAttr rankAttr = getConstantInt(operands[2]);
1666 if (!rankAttr)
1667 return emitError(unknownLoc, "OpTypeTensorARM rank must come from a "
1668 "scalar integer constant instruction");
1669 unsigned rank = rankAttr.getValue().getZExtValue();
1670 if (size == 3) {
1671 SmallVector<int64_t, 4> shape(rank, ShapedType::kDynamic);
1672 typeMap[operands[0]] = TensorArmType::get(shape, elementTy);
1673 return success();
1674 }
1675
1676 std::optional<std::pair<Attribute, Type>> shapeInfo =
1677 getConstant(operands[3]);
1678 if (!shapeInfo)
1679 return emitError(unknownLoc, "OpTypeTensorARM shape must come from a "
1680 "constant instruction of type OpTypeArray");
1681
1682 ArrayAttr shapeArrayAttr = dyn_cast<ArrayAttr>(shapeInfo->first);
1684 for (auto dimAttr : shapeArrayAttr.getValue()) {
1685 auto dimIntAttr = dyn_cast<IntegerAttr>(dimAttr);
1686 if (!dimIntAttr)
1687 return emitError(unknownLoc, "OpTypeTensorARM shape has an invalid "
1688 "dimension size");
1689 shape.push_back(dimIntAttr.getValue().getSExtValue());
1690 }
1691 typeMap[operands[0]] = TensorArmType::get(shape, elementTy);
1692 return success();
1693}
1694
1695LogicalResult
1697 unsigned size = operands.size();
1698 if (size < 2) {
1699 return emitError(unknownLoc, "OpTypeGraphARM must have at least 2 operands "
1700 "(result_id, num_inputs, (inout0_type, "
1701 "inout1_type, ...))")
1702 << size;
1703 }
1704 uint32_t numInputs = operands[1];
1705 SmallVector<Type, 1> argTypes;
1706 SmallVector<Type, 1> returnTypes;
1707 for (unsigned i = 2; i < size; ++i) {
1708 Type inOutTy = getType(operands[i]);
1709 if (!inOutTy) {
1710 return emitError(unknownLoc,
1711 "OpTypeGraphARM references undefined element type.")
1712 << operands[i];
1713 }
1714 if (i - 2 >= numInputs) {
1715 returnTypes.push_back(inOutTy);
1716 } else {
1717 argTypes.push_back(inOutTy);
1718 }
1719 }
1720 typeMap[operands[0]] = GraphType::get(context, argTypes, returnTypes);
1721 return success();
1722}
1723
1724LogicalResult
1726 if (operands.size() != 2)
1727 return emitError(unknownLoc,
1728 "OpTypeForwardPointer instruction must have two operands");
1729
1730 typeForwardPointerIDs.insert(operands[0]);
1731 // TODO: Use the 2nd operand (Storage Class) to validate the OpTypePointer
1732 // instruction that defines the actual type.
1733
1734 return success();
1735}
1736
1737LogicalResult
1739 // TODO: Add support for Access Qualifier.
1740 if (operands.size() != 8)
1741 return emitError(
1742 unknownLoc,
1743 "OpTypeImage with non-eight operands are not supported yet");
1744
1745 Type elementTy = getType(operands[1]);
1746 if (!elementTy)
1747 return emitError(unknownLoc, "OpTypeImage references undefined <id>: ")
1748 << operands[1];
1749
1750 auto dim = spirv::symbolizeDim(operands[2]);
1751 if (!dim)
1752 return emitError(unknownLoc, "unknown Dim for OpTypeImage: ")
1753 << operands[2];
1754
1755 auto depthInfo = spirv::symbolizeImageDepthInfo(operands[3]);
1756 if (!depthInfo)
1757 return emitError(unknownLoc, "unknown Depth for OpTypeImage: ")
1758 << operands[3];
1759
1760 auto arrayedInfo = spirv::symbolizeImageArrayedInfo(operands[4]);
1761 if (!arrayedInfo)
1762 return emitError(unknownLoc, "unknown Arrayed for OpTypeImage: ")
1763 << operands[4];
1764
1765 auto samplingInfo = spirv::symbolizeImageSamplingInfo(operands[5]);
1766 if (!samplingInfo)
1767 return emitError(unknownLoc, "unknown MS for OpTypeImage: ") << operands[5];
1768
1769 auto samplerUseInfo = spirv::symbolizeImageSamplerUseInfo(operands[6]);
1770 if (!samplerUseInfo)
1771 return emitError(unknownLoc, "unknown Sampled for OpTypeImage: ")
1772 << operands[6];
1773
1774 auto format = spirv::symbolizeImageFormat(operands[7]);
1775 if (!format)
1776 return emitError(unknownLoc, "unknown Format for OpTypeImage: ")
1777 << operands[7];
1778
1779 typeMap[operands[0]] = spirv::ImageType::getChecked(
1780 [&] { return emitError(unknownLoc); }, context,
1781 std::make_tuple(elementTy, dim.value(), depthInfo.value(),
1782 arrayedInfo.value(), samplingInfo.value(),
1783 samplerUseInfo.value(), format.value()));
1784 return success(static_cast<bool>(typeMap[operands[0]]));
1785}
1786
1787LogicalResult
1789 if (operands.size() != 2)
1790 return emitError(unknownLoc, "OpTypeSampledImage must have two operands");
1791
1792 Type elementTy = getType(operands[1]);
1793 if (!elementTy)
1794 return emitError(unknownLoc,
1795 "OpTypeSampledImage references undefined <id>: ")
1796 << operands[1];
1797
1798 typeMap[operands[0]] = spirv::SampledImageType::get(elementTy);
1799 return success();
1800}
1801
1802LogicalResult
1804 if (operands.size() != 1)
1805 return emitError(unknownLoc, "OpTypeSampler must have no parameters");
1806
1807 typeMap[operands[0]] = spirv::SamplerType::get(context);
1808 return success();
1809}
1810
1811LogicalResult
1813 if (operands.size() != 1)
1814 return emitError(unknownLoc, "OpTypeNamedBarrier must have no parameters");
1815
1816 typeMap[operands[0]] = spirv::NamedBarrierType::get(context);
1817 return success();
1818}
1819
1820LogicalResult
1822 if (operands.size() != 2)
1823 return emitError(unknownLoc,
1824 "OpTypeUntypedPointerKHR must have one parameter");
1825
1826 typeMap[operands[0]] = spirv::UntypedPointerType::get(
1827 context, static_cast<spirv::StorageClass>(operands[1]));
1828 return success();
1829}
1830
1831//===----------------------------------------------------------------------===//
1832// Constant
1833//===----------------------------------------------------------------------===//
1834
1836 bool isSpec) {
1837 StringRef opname = isSpec ? "OpSpecConstant" : "OpConstant";
1838
1839 if (operands.size() < 2) {
1840 return emitError(unknownLoc)
1841 << opname << " must have type <id> and result <id>";
1842 }
1843 if (operands.size() < 3) {
1844 return emitError(unknownLoc)
1845 << opname << " must have at least 1 more parameter";
1846 }
1847
1848 Type resultType = getType(operands[0]);
1849 if (!resultType) {
1850 return emitError(unknownLoc, "undefined result type from <id> ")
1851 << operands[0];
1852 }
1853
1854 auto checkOperandSizeForBitwidth = [&](unsigned bitwidth) -> LogicalResult {
1855 if (bitwidth == 64) {
1856 if (operands.size() == 4) {
1857 return success();
1858 }
1859 return emitError(unknownLoc)
1860 << opname << " should have 2 parameters for 64-bit values";
1861 }
1862 if (bitwidth <= 32) {
1863 if (operands.size() == 3) {
1864 return success();
1865 }
1866
1867 return emitError(unknownLoc)
1868 << opname
1869 << " should have 1 parameter for values with no more than 32 bits";
1870 }
1871 return emitError(unknownLoc, "unsupported OpConstant bitwidth: ")
1872 << bitwidth;
1873 };
1874
1875 auto resultID = operands[1];
1876
1877 if (auto intType = dyn_cast<IntegerType>(resultType)) {
1878 auto bitwidth = intType.getWidth();
1879 if (failed(checkOperandSizeForBitwidth(bitwidth))) {
1880 return failure();
1881 }
1882
1883 APInt value;
1884 if (bitwidth == 64) {
1885 // 64-bit integers are represented with two SPIR-V words. According to
1886 // SPIR-V spec: "When the type’s bit width is larger than one word, the
1887 // literal’s low-order words appear first."
1888 struct DoubleWord {
1889 uint32_t word1;
1890 uint32_t word2;
1891 } words = {operands[2], operands[3]};
1892 value = APInt(64, llvm::bit_cast<uint64_t>(words), /*isSigned=*/true);
1893 } else if (bitwidth <= 32) {
1894 value = APInt(bitwidth, operands[2], /*isSigned=*/true,
1895 /*implicitTrunc=*/true);
1896 }
1897
1898 auto attr = opBuilder.getIntegerAttr(intType, value);
1899
1900 if (isSpec) {
1901 createSpecConstant(unknownLoc, resultID, attr);
1902 } else {
1903 // For normal constants, we just record the attribute (and its type) for
1904 // later materialization at use sites.
1905 constantMap.try_emplace(resultID, attr, intType);
1906 }
1907
1908 return success();
1909 }
1910
1911 if (auto floatType = dyn_cast<FloatType>(resultType)) {
1912 auto bitwidth = floatType.getWidth();
1913 if (failed(checkOperandSizeForBitwidth(bitwidth))) {
1914 return failure();
1915 }
1916
1917 APFloat value(0.f);
1918 if (floatType.isF64()) {
1919 // Double values are represented with two SPIR-V words. According to
1920 // SPIR-V spec: "When the type’s bit width is larger than one word, the
1921 // literal’s low-order words appear first."
1922 struct DoubleWord {
1923 uint32_t word1;
1924 uint32_t word2;
1925 } words = {operands[2], operands[3]};
1926 value = APFloat(llvm::bit_cast<double>(words));
1927 } else if (floatType.isF32()) {
1928 value = APFloat(llvm::bit_cast<float>(operands[2]));
1929 } else if (floatType.isF16()) {
1930 APInt data(16, operands[2]);
1931 value = APFloat(APFloat::IEEEhalf(), data);
1932 } else if (floatType.isBF16()) {
1933 APInt data(16, operands[2]);
1934 value = APFloat(APFloat::BFloat(), data);
1935 } else if (floatType.isF8E4M3FN()) {
1936 APInt data(8, operands[2]);
1937 value = APFloat(APFloat::Float8E4M3FN(), data);
1938 } else if (floatType.isF8E5M2()) {
1939 APInt data(8, operands[2]);
1940 value = APFloat(APFloat::Float8E5M2(), data);
1941 } else if (isa<Float4E2M1FNType>(floatType)) {
1942 value = APFloat(APFloat::Float4E2M1FN(), APInt(4, operands[2]));
1943 } else if (isa<Float6E2M3FNType>(floatType)) {
1944 value = APFloat(APFloat::Float6E2M3FN(), APInt(6, operands[2]));
1945 } else if (isa<Float6E3M2FNType>(floatType)) {
1946 value = APFloat(APFloat::Float6E3M2FN(), APInt(6, operands[2]));
1947 } else if (isa<Float8E8M0FNUType>(floatType)) {
1948 value = APFloat(APFloat::Float8E8M0FNU(), APInt(8, operands[2]));
1949 }
1950
1951 auto attr = opBuilder.getFloatAttr(floatType, value);
1952 if (isSpec) {
1953 createSpecConstant(unknownLoc, resultID, attr);
1954 } else {
1955 // For normal constants, we just record the attribute (and its type) for
1956 // later materialization at use sites.
1957 constantMap.try_emplace(resultID, attr, floatType);
1958 }
1959
1960 return success();
1961 }
1962
1963 return emitError(unknownLoc, "OpConstant can only generate values of "
1964 "scalar integer or floating-point type");
1965}
1966
1968 bool isTrue, ArrayRef<uint32_t> operands, bool isSpec) {
1969 if (operands.size() != 2) {
1970 return emitError(unknownLoc, "Op")
1971 << (isSpec ? "Spec" : "") << "Constant"
1972 << (isTrue ? "True" : "False")
1973 << " must have type <id> and result <id>";
1974 }
1975
1976 auto attr = opBuilder.getBoolAttr(isTrue);
1977 auto resultID = operands[1];
1978 if (isSpec) {
1979 createSpecConstant(unknownLoc, resultID, attr);
1980 } else {
1981 // For normal constants, we just record the attribute (and its type) for
1982 // later materialization at use sites.
1983 constantMap.try_emplace(resultID, attr, opBuilder.getI1Type());
1984 }
1985
1986 return success();
1987}
1988
1989LogicalResult
1991 if (operands.size() < 2) {
1992 return emitError(unknownLoc,
1993 "OpConstantComposite must have type <id> and result <id>");
1994 }
1995 Type resultType = getType(operands[0]);
1996 if (!resultType) {
1997 return emitError(unknownLoc, "undefined result type from <id> ")
1998 << operands[0];
1999 }
2000
2001 // Unused constants are not materialized as ops, so their verifier cannot
2002 // diagnose missing constituents. Only empty structs may have none.
2003 auto structType = dyn_cast<spirv::StructType>(resultType);
2004 if (operands.size() < 3 &&
2005 (!structType || structType.getNumElements() != 0)) {
2006 return emitError(unknownLoc,
2007 "OpConstantComposite must have at least 1 parameter");
2008 }
2009
2010 ArrayRef<uint32_t> constituents = operands.drop_front(2);
2011 bool canHoldUndef =
2012 isa<VectorType, spirv::ArrayType, spirv::StructType>(resultType);
2014 elements.reserve(constituents.size());
2015 for (auto [index, id] : llvm::enumerate(constituents)) {
2016 std::optional<std::pair<Attribute, Type>> elementInfo = getConstant(id);
2017 if (!elementInfo) {
2018 if (canHoldUndef && (getUndefType(id) || undefCompositeMap.contains(id)))
2019 continue;
2020 // spirv.Constant cannot represent undefined constituents.
2021 if (getUndefType(id)) {
2022 return emitError(unknownLoc, "OpConstantComposite component #")
2023 << index << " <id> " << id
2024 << " is an OpUndef, which cannot be represented in "
2025 "spirv.Constant";
2026 }
2027 if (undefCompositeMap.contains(id)) {
2028 return emitError(unknownLoc, "OpConstantComposite component #")
2029 << index << " <id> " << id
2030 << " has OpUndef constituents, which cannot be represented in "
2031 "spirv.Constant";
2032 }
2033 return emitError(unknownLoc, "OpConstantComposite component #")
2034 << index << " <id> " << id << " must come from a normal constant";
2035 }
2036 elements.push_back(elementInfo->first);
2037 }
2038
2039 auto resultID = operands[1];
2040 if (elements.size() != constituents.size()) {
2041 undefCompositeMap.try_emplace(resultID, resultType,
2042 SmallVector<uint32_t>(constituents));
2043 return success();
2044 }
2045
2046 if (auto tensorType = dyn_cast<TensorArmType>(resultType)) {
2047 SmallVector<Attribute> flattenedElems;
2048 for (Attribute element : elements) {
2049 if (auto denseElemAttr = dyn_cast<DenseElementsAttr>(element)) {
2050 for (auto value : denseElemAttr.getValues<Attribute>())
2051 flattenedElems.push_back(value);
2052 } else {
2053 flattenedElems.push_back(element);
2054 }
2055 }
2056 auto attr = DenseElementsAttr::get(tensorType, flattenedElems);
2057 constantMap.try_emplace(resultID, attr, tensorType);
2058 } else if (auto shapedType = dyn_cast<ShapedType>(resultType)) {
2059 auto attr = DenseElementsAttr::get(shapedType, elements);
2060 // For normal constants, we just record the attribute (and its type) for
2061 // later materialization at use sites.
2062 constantMap.try_emplace(resultID, attr, shapedType);
2063 } else if (isa<spirv::ArrayType, spirv::StructType>(resultType)) {
2064 auto attr = opBuilder.getArrayAttr(elements);
2065 constantMap.try_emplace(resultID, attr, resultType);
2066 } else {
2067 return emitError(unknownLoc, "unsupported OpConstantComposite type: ")
2068 << resultType;
2069 }
2070
2071 return success();
2072}
2073
2075 ArrayRef<uint32_t> operands) {
2076 if (operands.size() != 3) {
2077 return emitError(
2078 unknownLoc,
2079 "OpConstantCompositeReplicateEXT expects 3 operands but found ")
2080 << operands.size();
2081 }
2082
2083 Type resultType = getType(operands[0]);
2084 if (!resultType) {
2085 return emitError(unknownLoc, "undefined result type from <id> ")
2086 << operands[0];
2087 }
2088
2089 auto compositeType = dyn_cast<CompositeType>(resultType);
2090 if (!compositeType) {
2091 return emitError(unknownLoc,
2092 "result type from <id> is not a composite type")
2093 << operands[0];
2094 }
2095
2096 uint32_t resultID = operands[1];
2097 uint32_t constantID = operands[2];
2098
2099 std::optional<std::pair<Attribute, Type>> replicatedConstantCompositeInfo =
2101 if (replicatedConstantCompositeInfo.has_value()) {
2102 constantCompositeReplicateMap.try_emplace(
2103 resultID, replicatedConstantCompositeInfo.value().first, resultType);
2104 return success();
2105 }
2106
2107 std::optional<std::pair<Attribute, Type>> constantInfo =
2108 getConstant(constantID);
2109 if (constantInfo.has_value()) {
2110 constantCompositeReplicateMap.try_emplace(
2111 resultID, constantInfo.value().first, resultType);
2112 return success();
2113 }
2114
2115 return emitError(unknownLoc, "OpConstantCompositeReplicateEXT operand <id> ")
2116 << constantID
2117 << " must come from a normal constant or a "
2118 "OpConstantCompositeReplicateEXT";
2119}
2120
2121LogicalResult
2123 if (operands.size() < 2) {
2124 return emitError(
2125 unknownLoc,
2126 "OpSpecConstantComposite must have type <id> and result <id>");
2127 }
2128 if (operands.size() < 3) {
2129 return emitError(unknownLoc,
2130 "OpSpecConstantComposite must have at least 1 parameter");
2131 }
2132
2133 Type resultType = getType(operands[0]);
2134 if (!resultType) {
2135 return emitError(unknownLoc, "undefined result type from <id> ")
2136 << operands[0];
2137 }
2138
2139 auto resultID = operands[1];
2140 auto symName = opBuilder.getStringAttr(getSpecConstantSymbol(resultID));
2141
2143 elements.reserve(operands.size() - 2);
2144 for (auto [index, id] : llvm::enumerate(operands.drop_front(2))) {
2145 Operation *elementOp = getSpecConstant(id);
2146 if (!elementOp)
2147 elementOp = getSpecConstantComposite(id);
2148 if (!elementOp) {
2149 return emitError(unknownLoc, "OpSpecConstantComposite component #")
2150 << index << " <id> " << id
2151 << " cannot be represented in spirv.SpecConstantComposite";
2152 }
2153 elements.push_back(SymbolRefAttr::get(elementOp));
2154 }
2155
2156 auto op = spirv::SpecConstantCompositeOp::create(
2157 opBuilder, unknownLoc, TypeAttr::get(resultType), symName,
2158 opBuilder.getArrayAttr(elements), /*sym_visibility=*/nullptr);
2159 specConstCompositeMap[resultID] = op;
2160
2161 return success();
2162}
2163
2165 ArrayRef<uint32_t> operands) {
2166 if (operands.size() != 3) {
2167 return emitError(unknownLoc, "OpSpecConstantCompositeReplicateEXT expects "
2168 "3 operands but found ")
2169 << operands.size();
2170 }
2171
2172 Type resultType = getType(operands[0]);
2173 if (!resultType) {
2174 return emitError(unknownLoc, "undefined result type from <id> ")
2175 << operands[0];
2176 }
2177
2178 auto compositeType = dyn_cast<CompositeType>(resultType);
2179 if (!compositeType) {
2180 return emitError(unknownLoc,
2181 "result type from <id> is not a composite type")
2182 << operands[0];
2183 }
2184
2185 uint32_t resultID = operands[1];
2186
2187 auto symName = opBuilder.getStringAttr(getSpecConstantSymbol(resultID));
2188 spirv::SpecConstantOp constituentSpecConstantOp =
2189 getSpecConstant(operands[2]);
2190 if (!constituentSpecConstantOp) {
2191 return emitError(unknownLoc, "OpSpecConstantCompositeReplicateEXT operand "
2192 "<id> ")
2193 << operands[2]
2194 << " cannot be represented in "
2195 "spirv.EXT.SpecConstantCompositeReplicate";
2196 }
2197 auto op = spirv::EXTSpecConstantCompositeReplicateOp::create(
2198 opBuilder, unknownLoc, TypeAttr::get(resultType), symName,
2199 SymbolRefAttr::get(constituentSpecConstantOp),
2200 /*sym_visibility=*/nullptr);
2201
2202 specConstCompositeReplicateMap[resultID] = op;
2203
2204 return success();
2205}
2206
2207LogicalResult
2209 if (operands.size() < 3)
2210 return emitError(unknownLoc, "OpConstantOperation must have type <id>, "
2211 "result <id>, and operand opcode");
2212
2213 uint32_t resultTypeID = operands[0];
2214
2215 if (!getType(resultTypeID))
2216 return emitError(unknownLoc, "undefined result type from <id> ")
2217 << resultTypeID;
2218
2219 uint32_t resultID = operands[1];
2220 spirv::Opcode enclosedOpcode = static_cast<spirv::Opcode>(operands[2]);
2221 auto emplaceResult = specConstOperationMap.try_emplace(
2222 resultID,
2224 enclosedOpcode, resultTypeID,
2225 SmallVector<uint32_t>{operands.begin() + 3, operands.end()}});
2226
2227 if (!emplaceResult.second)
2228 return emitError(unknownLoc, "value with <id>: ")
2229 << resultID << " is probably defined before.";
2230
2231 return success();
2232}
2233
2235 uint32_t resultID, spirv::Opcode enclosedOpcode, uint32_t resultTypeID,
2236 ArrayRef<uint32_t> enclosedOpOperands) {
2237
2238 Type resultType = getType(resultTypeID);
2239
2240 // Instructions wrapped by OpSpecConstantOp need an ID for their
2241 // Deserializer::processOp<op_name>(...) to emit the corresponding SPIR-V
2242 // dialect wrapped op. For that purpose, a new value map is created and "fake"
2243 // ID in that map is assigned to the result of the enclosed instruction. Note
2244 // that there is no need to update this fake ID since we only need to
2245 // reference the created Value for the enclosed op from the spv::YieldOp
2246 // created later in this method (both of which are the only values in their
2247 // region: the SpecConstantOperation's region). If we encounter another
2248 // SpecConstantOperation in the module, we simply re-use the fake ID since the
2249 // previous Value assigned to it isn't visible in the current scope anyway.
2250 DenseMap<uint32_t, Value> newValueMap;
2251 llvm::SaveAndRestore valueMapGuard(valueMap, newValueMap);
2252 constexpr uint32_t fakeID = static_cast<uint32_t>(-3);
2253
2254 SmallVector<uint32_t, 4> enclosedOpResultTypeAndOperands;
2255 enclosedOpResultTypeAndOperands.push_back(resultTypeID);
2256 enclosedOpResultTypeAndOperands.push_back(fakeID);
2257 enclosedOpResultTypeAndOperands.append(enclosedOpOperands.begin(),
2258 enclosedOpOperands.end());
2259
2260 // Process enclosed instruction before creating the enclosing
2261 // specConstantOperation (and its region). This way, references to constants,
2262 // global variables, and spec constants will be materialized outside the new
2263 // op's region. For more info, see Deserializer::getValue's implementation.
2264 if (failed(
2265 processInstruction(enclosedOpcode, enclosedOpResultTypeAndOperands)))
2266 return Value();
2267
2268 // Since the enclosed op is emitted in the current block, split it in a
2269 // separate new block.
2270 Block *enclosedBlock = curBlock->splitBlock(&curBlock->back());
2271
2272 auto loc = createFileLineColLoc(opBuilder);
2273 auto specConstOperationOp =
2274 spirv::SpecConstantOperationOp::create(opBuilder, loc, resultType);
2275
2276 Region &body = specConstOperationOp.getBody();
2277 // Move the new block into SpecConstantOperation's body.
2278 body.getBlocks().splice(body.end(), curBlock->getParent()->getBlocks(),
2279 Region::iterator(enclosedBlock));
2280 Block &block = body.back();
2281
2282 // RAII guard to reset the insertion point to the module's region after
2283 // deserializing the body of the specConstantOperation.
2284 OpBuilder::InsertionGuard moduleInsertionGuard(opBuilder);
2285 opBuilder.setInsertionPointToEnd(&block);
2286
2287 spirv::YieldOp::create(opBuilder, loc, block.front().getResult(0));
2288 return specConstOperationOp.getResult();
2289}
2290
2291LogicalResult
2293 if (operands.size() != 2) {
2294 return emitError(unknownLoc,
2295 "OpConstantNull must only have type <id> and result <id>");
2296 }
2297
2298 Type resultType = getType(operands[0]);
2299 if (!resultType) {
2300 return emitError(unknownLoc, "undefined result type from <id> ")
2301 << operands[0];
2302 }
2303
2304 auto resultID = operands[1];
2305 Attribute attr;
2306 if (resultType.isIntOrFloat() || isa<VectorType>(resultType)) {
2307 attr = opBuilder.getZeroAttr(resultType);
2308 } else if (auto tensorType = dyn_cast<TensorArmType>(resultType)) {
2309 if (auto element = opBuilder.getZeroAttr(tensorType.getElementType()))
2310 attr = DenseElementsAttr::get(tensorType, element);
2311 } else if (isa<spirv::ArrayType, spirv::PointerType, spirv::StructType>(
2312 resultType)) {
2313 attr = spirv::NullAttr::get(resultType);
2314 }
2315
2316 if (attr) {
2317 // For normal constants, we just record the attribute (and its type) for
2318 // later materialization at use sites.
2319 constantMap.try_emplace(resultID, attr, resultType);
2320 return success();
2321 }
2322
2323 return emitError(unknownLoc, "unsupported OpConstantNull type: ")
2324 << resultType;
2325}
2326
2327LogicalResult
2329 if (operands.size() < 3) {
2330 return emitError(unknownLoc)
2331 << "OpGraphConstantARM must have at least 2 operands";
2332 }
2333
2334 Type resultType = getType(operands[0]);
2335 if (!resultType) {
2336 return emitError(unknownLoc, "undefined result type from <id> ")
2337 << operands[0];
2338 }
2339
2340 uint32_t resultID = operands[1];
2341
2342 if (!dyn_cast<spirv::TensorArmType>(resultType)) {
2343 return emitError(unknownLoc, "result must be of type OpTypeTensorARM");
2344 }
2345
2346 APInt graph_constant_id = APInt(32, operands[2], /*isSigned=*/true);
2347 Type i32Ty = opBuilder.getIntegerType(32);
2348 IntegerAttr attr = opBuilder.getIntegerAttr(i32Ty, graph_constant_id);
2349 graphConstantMap.try_emplace(
2350 resultID, GraphConstantARMOpMaterializationInfo{resultType, attr});
2351
2352 return success();
2353}
2354
2355//===----------------------------------------------------------------------===//
2356// Control flow
2357//===----------------------------------------------------------------------===//
2358
2360 if (auto *block = getBlock(id)) {
2361 LLVM_DEBUG(logger.startLine() << "[block] got exiting block for id = " << id
2362 << " @ " << block << "\n");
2363 return block;
2364 }
2365
2366 // We don't know where this block will be placed finally (in a
2367 // spirv.mlir.selection or spirv.mlir.loop or function). Create it into the
2368 // function for now and sort out the proper place later.
2369 auto *block = curFunction->addBlock();
2370 LLVM_DEBUG(logger.startLine() << "[block] created block for id = " << id
2371 << " @ " << block << "\n");
2372 return blockMap[id] = block;
2373}
2374
2376 if (!curBlock) {
2377 return emitError(unknownLoc, "OpBranch must appear inside a block");
2378 }
2379
2380 if (operands.size() != 1) {
2381 return emitError(unknownLoc, "OpBranch must take exactly one target label");
2382 }
2383
2384 auto *target = getOrCreateBlock(operands[0]);
2385 auto loc = createFileLineColLoc(opBuilder);
2386 // The preceding instruction for the OpBranch instruction could be an
2387 // OpLoopMerge or an OpSelectionMerge instruction, in this case they will have
2388 // the same OpLine information.
2389 spirv::BranchOp::create(opBuilder, loc, target);
2390
2392 return success();
2393}
2394
2395LogicalResult
2397 if (!curBlock) {
2398 return emitError(unknownLoc,
2399 "OpBranchConditional must appear inside a block");
2400 }
2401
2402 if (operands.size() != 3 && operands.size() != 5) {
2403 return emitError(unknownLoc,
2404 "OpBranchConditional must have condition, true label, "
2405 "false label, and optionally two branch weights");
2406 }
2407
2408 auto condition = getValue(operands[0]);
2409 auto *trueBlock = getOrCreateBlock(operands[1]);
2410 auto *falseBlock = getOrCreateBlock(operands[2]);
2411
2412 std::optional<std::pair<uint32_t, uint32_t>> weights;
2413 if (operands.size() == 5) {
2414 weights = std::make_pair(operands[3], operands[4]);
2415 }
2416 // The preceding instruction for the OpBranchConditional instruction could be
2417 // an OpSelectionMerge instruction, in this case they will have the same
2418 // OpLine information.
2419 auto loc = createFileLineColLoc(opBuilder);
2420 spirv::BranchConditionalOp::create(
2421 opBuilder, loc, condition, trueBlock,
2422 /*trueArguments=*/ArrayRef<Value>(), falseBlock,
2423 /*falseArguments=*/ArrayRef<Value>(), weights);
2424
2426 return success();
2427}
2428
2430 if (!curFunction) {
2431 return emitError(unknownLoc, "OpLabel must appear inside a function");
2432 }
2433
2434 if (operands.size() != 1) {
2435 return emitError(unknownLoc, "OpLabel should only have result <id>");
2436 }
2437
2438 auto labelID = operands[0];
2439 // We may have forward declared this block.
2440 auto *block = getOrCreateBlock(labelID);
2441 LLVM_DEBUG(logger.startLine()
2442 << "[block] populating block " << block << "\n");
2443 // If we have seen this block, make sure it was just a forward declaration.
2444 assert(block->empty() && "re-deserialize the same block!");
2445
2446 opBuilder.setInsertionPointToStart(block);
2447 blockMap[labelID] = curBlock = block;
2448
2449 return success();
2450}
2451
2452LogicalResult spirv::Deserializer::createGraphBlock(uint32_t graphID) {
2453 if (!curGraph) {
2454 return emitError(unknownLoc, "a graph block must appear inside a graph");
2455 }
2456
2457 // We may have forward declared this block.
2458 Block *block = getOrCreateBlock(graphID);
2459 LLVM_DEBUG(logger.startLine()
2460 << "[block] populating block " << block << "\n");
2461 // If we have seen this block, make sure it was just a forward declaration.
2462 assert(block->empty() && "re-deserialize the same block!");
2463
2464 opBuilder.setInsertionPointToStart(block);
2465 blockMap[graphID] = curBlock = block;
2466
2467 return success();
2468}
2469
2470LogicalResult
2472 if (!curBlock) {
2473 return emitError(unknownLoc, "OpSelectionMerge must appear in a block");
2474 }
2475
2476 if (operands.size() < 2) {
2477 return emitError(
2478 unknownLoc,
2479 "OpSelectionMerge must specify merge target and selection control");
2480 }
2481
2482 auto *mergeBlock = getOrCreateBlock(operands[0]);
2483 auto loc = createFileLineColLoc(opBuilder);
2484 auto selectionControl = operands[1];
2485
2486 if (!blockMergeInfo.try_emplace(curBlock, loc, selectionControl, mergeBlock)
2487 .second) {
2488 return emitError(
2489 unknownLoc,
2490 "a block cannot have more than one OpSelectionMerge instruction");
2491 }
2492
2493 return success();
2494}
2495
2496LogicalResult
2498 if (!curBlock) {
2499 return emitError(unknownLoc, "OpLoopMerge must appear in a block");
2500 }
2501
2502 if (operands.size() < 3) {
2503 return emitError(unknownLoc, "OpLoopMerge must specify merge target, "
2504 "continue target and loop control");
2505 }
2506
2507 auto *mergeBlock = getOrCreateBlock(operands[0]);
2508 auto *continueBlock = getOrCreateBlock(operands[1]);
2509 auto loc = createFileLineColLoc(opBuilder);
2510 uint32_t loopControl = operands[2];
2511
2512 if (!blockMergeInfo
2513 .try_emplace(curBlock, loc, loopControl, mergeBlock, continueBlock)
2514 .second) {
2515 return emitError(
2516 unknownLoc,
2517 "a block cannot have more than one OpLoopMerge instruction");
2518 }
2519
2520 return success();
2521}
2522
2524 if (!curBlock) {
2525 return emitError(unknownLoc, "OpPhi must appear in a block");
2526 }
2527
2528 if (operands.size() < 4) {
2529 return emitError(unknownLoc, "OpPhi must specify result type, result <id>, "
2530 "and variable-parent pairs");
2531 }
2532
2533 // Create a block argument for this OpPhi instruction.
2534 Type blockArgType = getType(operands[0]);
2535 BlockArgument blockArg = curBlock->addArgument(blockArgType, unknownLoc);
2536 valueMap[operands[1]] = blockArg;
2537 LLVM_DEBUG(logger.startLine()
2538 << "[phi] created block argument " << blockArg
2539 << " id = " << operands[1] << " of type " << blockArgType << "\n");
2540
2541 // For each (value, predecessor) pair, insert the value to the predecessor's
2542 // blockPhiInfo entry so later we can fix the block argument there.
2543 for (unsigned i = 2, e = operands.size(); i < e; i += 2) {
2544 uint32_t value = operands[i];
2545 Block *predecessor = getOrCreateBlock(operands[i + 1]);
2546 std::pair<Block *, Block *> predecessorTargetPair{predecessor, curBlock};
2547 blockPhiInfo[predecessorTargetPair].push_back(value);
2548 LLVM_DEBUG(logger.startLine() << "[phi] predecessor @ " << predecessor
2549 << " with arg id = " << value << "\n");
2550 }
2551
2552 return success();
2553}
2554
2556 if (!curBlock)
2557 return emitError(unknownLoc, "OpSwitch must appear in a block");
2558
2559 if (operands.size() < 2)
2560 return emitError(unknownLoc, "OpSwitch must at least specify selector and "
2561 "a default target");
2562
2563 Value selector = getValue(operands[0]);
2564 if (!selector)
2565 return emitError(unknownLoc, "unknown OpSwitch selector <id>: ")
2566 << operands[0];
2567 auto selectorType = dyn_cast<IntegerType>(selector.getType());
2568 if (!selectorType)
2569 return emitError(unknownLoc, "OpSwitch selector must be an integer");
2570
2571 // Each case literal has the width of the selector type. Literals wider than
2572 // one word span multiple words with the low-order word first.
2573 unsigned bitWidth = selectorType.getWidth();
2574 unsigned literalWords = llvm::divideCeil(bitWidth, 32);
2575 unsigned wordsPerCase = literalWords + 1;
2576 if ((operands.size() - 2) % wordsPerCase != 0)
2577 return emitError(unknownLoc, "OpSwitch must specify selector, default "
2578 "target and any number of literal and label "
2579 "<id> pairs, where each literal of a ")
2580 << bitWidth << "-bit selector spans " << literalWords << " word(s)";
2581
2582 Block *defaultBlock = getOrCreateBlock(operands[1]);
2583 Location loc = createFileLineColLoc(opBuilder);
2584
2585 SmallVector<APInt> literals;
2586 SmallVector<Block *> blocks;
2587 for (unsigned i = 2, e = operands.size(); i < e; i += wordsPerCase) {
2588 APInt literal;
2589 if (bitWidth <= 32) {
2590 // Sub-word literals occupy the low-order bits of the word and are
2591 // sign-extended for signed selector types, so truncate to the selector
2592 // width.
2593 literal = APInt(bitWidth, operands[i], /*isSigned=*/true,
2594 /*implicitTrunc=*/true);
2595 } else {
2596 literal = APInt(bitWidth, 0);
2597 for (unsigned w = 0; w < literalWords; ++w)
2598 literal.insertBits(APInt(32, operands[i + w]), w * 32);
2599 }
2600 literals.push_back(literal);
2601 blocks.push_back(getOrCreateBlock(operands[i + literalWords]));
2602 }
2603
2604 SmallVector<ValueRange> targetOperands(blocks.size(), {});
2605 spirv::SwitchOp::create(opBuilder, loc, selector, defaultBlock,
2606 ArrayRef<Value>(), ArrayRef<APInt>(literals), blocks,
2607 targetOperands);
2608
2609 return success();
2610}
2611
2612namespace {
2613/// A class for putting all blocks in a structured selection/loop in a
2614/// spirv.mlir.selection/spirv.mlir.loop op.
2615class ControlFlowStructurizer {
2616public:
2617#ifndef NDEBUG
2618 ControlFlowStructurizer(Location loc, uint32_t control,
2619 spirv::BlockMergeInfoMap &mergeInfo, Block *header,
2620 Block *merge, Block *cont,
2621 llvm::ScopedPrinter &logger)
2622 : location(loc), control(control), blockMergeInfo(mergeInfo),
2623 headerBlock(header), mergeBlock(merge), continueBlock(cont),
2624 logger(logger) {}
2625#else
2626 ControlFlowStructurizer(Location loc, uint32_t control,
2627 spirv::BlockMergeInfoMap &mergeInfo, Block *header,
2628 Block *merge, Block *cont)
2629 : location(loc), control(control), blockMergeInfo(mergeInfo),
2630 headerBlock(header), mergeBlock(merge), continueBlock(cont) {}
2631#endif
2632
2633 /// Structurizes the loop at the given `headerBlock`.
2634 ///
2635 /// This method will create an spirv.mlir.loop op in the `mergeBlock` and move
2636 /// all blocks in the structured loop into the spirv.mlir.loop's region. All
2637 /// branches to the `headerBlock` will be redirected to the `mergeBlock`. This
2638 /// method will also update `mergeInfo` by remapping all blocks inside to the
2639 /// newly cloned ones inside structured control flow op's regions.
2640 LogicalResult structurize();
2641
2642private:
2643 /// Creates a new spirv.mlir.selection op at the beginning of the
2644 /// `mergeBlock`.
2645 spirv::SelectionOp createSelectionOp(uint32_t selectionControl);
2646
2647 /// Creates a new spirv.mlir.loop op at the beginning of the `mergeBlock`.
2648 spirv::LoopOp createLoopOp(uint32_t loopControl);
2649
2650 /// Collects all blocks reachable from `headerBlock` except `mergeBlock`.
2651 void collectBlocksInConstruct();
2652
2653 Location location;
2654 uint32_t control;
2655
2656 spirv::BlockMergeInfoMap &blockMergeInfo;
2657
2658 Block *headerBlock;
2659 Block *mergeBlock;
2660 Block *continueBlock; // nullptr for spirv.mlir.selection
2661
2662 SetVector<Block *> constructBlocks;
2663
2664#ifndef NDEBUG
2665 /// A logger used to emit information during the deserialzation process.
2666 llvm::ScopedPrinter &logger;
2667#endif
2668};
2669} // namespace
2670
2671spirv::SelectionOp
2672ControlFlowStructurizer::createSelectionOp(uint32_t selectionControl) {
2673 // Create a builder and set the insertion point to the beginning of the
2674 // merge block so that the newly created SelectionOp will be inserted there.
2675 OpBuilder builder(&mergeBlock->front());
2676
2677 auto control = static_cast<spirv::SelectionControl>(selectionControl);
2678 auto selectionOp = spirv::SelectionOp::create(builder, location, control);
2679 selectionOp.addMergeBlock(builder);
2680
2681 return selectionOp;
2682}
2683
2684spirv::LoopOp ControlFlowStructurizer::createLoopOp(uint32_t loopControl) {
2685 // Create a builder and set the insertion point to the beginning of the
2686 // merge block so that the newly created LoopOp will be inserted there.
2687 OpBuilder builder(&mergeBlock->front());
2688
2689 auto control = static_cast<spirv::LoopControl>(loopControl);
2690 auto loopOp = spirv::LoopOp::create(builder, location, control);
2691 loopOp.addEntryAndMergeBlock(builder);
2692
2693 return loopOp;
2694}
2695
2696void ControlFlowStructurizer::collectBlocksInConstruct() {
2697 assert(constructBlocks.empty() && "expected empty constructBlocks");
2698
2699 // Put the header block in the work list first.
2700 constructBlocks.insert(headerBlock);
2701
2702 // For each item in the work list, add its successors excluding the merge
2703 // block.
2704 for (unsigned i = 0; i < constructBlocks.size(); ++i) {
2705 for (auto *successor : constructBlocks[i]->getSuccessors())
2706 if (successor != mergeBlock)
2707 constructBlocks.insert(successor);
2708 }
2709}
2710
2711LogicalResult ControlFlowStructurizer::structurize() {
2712 Operation *op = nullptr;
2713 bool isLoop = continueBlock != nullptr;
2714 if (isLoop) {
2715 if (auto loopOp = createLoopOp(control))
2716 op = loopOp.getOperation();
2717 } else {
2718 if (auto selectionOp = createSelectionOp(control))
2719 op = selectionOp.getOperation();
2720 }
2721 if (!op)
2722 return failure();
2723 Region &body = op->getRegion(0);
2724
2725 IRMapping mapper;
2726 // All references to the old merge block should be directed to the
2727 // selection/loop merge block in the SelectionOp/LoopOp's region.
2728 mapper.map(mergeBlock, &body.back());
2729
2730 collectBlocksInConstruct();
2731
2732 // We've identified all blocks belonging to the selection/loop's region. Now
2733 // need to "move" them into the selection/loop. Instead of really moving the
2734 // blocks, in the following we copy them and remap all values and branches.
2735 // This is because:
2736 // * Inserting a block into a region requires the block not in any region
2737 // before. But selections/loops can nest so we can create selection/loop ops
2738 // in a nested manner, which means some blocks may already be in a
2739 // selection/loop region when to be moved again.
2740 // * It's much trickier to fix up the branches into and out of the loop's
2741 // region: we need to treat not-moved blocks and moved blocks differently:
2742 // Not-moved blocks jumping to the loop header block need to jump to the
2743 // merge point containing the new loop op but not the loop continue block's
2744 // back edge. Moved blocks jumping out of the loop need to jump to the
2745 // merge block inside the loop region but not other not-moved blocks.
2746 // We cannot use replaceAllUsesWith clearly and it's harder to follow the
2747 // logic.
2748
2749 // Create a corresponding block in the SelectionOp/LoopOp's region for each
2750 // block in this loop construct.
2751 OpBuilder builder(body);
2752 for (auto *block : constructBlocks) {
2753 // Create a block and insert it before the selection/loop merge block in the
2754 // SelectionOp/LoopOp's region.
2755 auto *newBlock = builder.createBlock(&body.back());
2756 mapper.map(block, newBlock);
2757 LLVM_DEBUG(logger.startLine() << "[cf] cloned block " << newBlock
2758 << " from block " << block << "\n");
2759 if (!isFnEntryBlock(block)) {
2760 for (BlockArgument blockArg : block->getArguments()) {
2761 auto newArg =
2762 newBlock->addArgument(blockArg.getType(), blockArg.getLoc());
2763 mapper.map(blockArg, newArg);
2764 LLVM_DEBUG(logger.startLine() << "[cf] remapped block argument "
2765 << blockArg << " to " << newArg << "\n");
2766 }
2767 } else {
2768 LLVM_DEBUG(logger.startLine()
2769 << "[cf] block " << block << " is a function entry block\n");
2770 }
2771
2772 for (auto &op : *block)
2773 newBlock->push_back(op.clone(mapper));
2774 }
2775
2776 // Go through all ops and remap the operands.
2777 auto remapOperands = [&](Operation *op) {
2778 for (auto &operand : op->getOpOperands())
2779 if (Value mappedOp = mapper.lookupOrNull(operand.get()))
2780 operand.set(mappedOp);
2781 for (auto &succOp : op->getBlockOperands())
2782 if (Block *mappedOp = mapper.lookupOrNull(succOp.get()))
2783 succOp.set(mappedOp);
2784 };
2785 for (auto &block : body)
2786 block.walk(remapOperands);
2787
2788 // We have created the SelectionOp/LoopOp and "moved" all blocks belonging to
2789 // the selection/loop construct into its region. Next we need to fix the
2790 // connections between this new SelectionOp/LoopOp with existing blocks.
2791
2792 // All existing incoming branches should go to the merge block, where the
2793 // SelectionOp/LoopOp resides right now.
2794 headerBlock->replaceAllUsesWith(mergeBlock);
2795
2796 LLVM_DEBUG({
2797 logger.startLine() << "[cf] after cloning and fixing references:\n";
2798 headerBlock->getParentOp()->print(logger.getOStream());
2799 logger.startLine() << "\n";
2800 });
2801
2802 if (isLoop) {
2803 if (!mergeBlock->args_empty()) {
2804 return mergeBlock->getParentOp()->emitError(
2805 "OpPhi in loop merge block unsupported");
2806 }
2807
2808 // The loop header block may have block arguments. Since now we place the
2809 // loop op inside the old merge block, we need to make sure the old merge
2810 // block has the same block argument list.
2811 for (BlockArgument blockArg : headerBlock->getArguments())
2812 mergeBlock->addArgument(blockArg.getType(), blockArg.getLoc());
2813
2814 // If the loop header block has block arguments, make sure the spirv.Branch
2815 // op matches.
2816 SmallVector<Value, 4> blockArgs;
2817 if (!headerBlock->args_empty())
2818 blockArgs = {mergeBlock->args_begin(), mergeBlock->args_end()};
2819
2820 // The loop entry block should have a unconditional branch jumping to the
2821 // loop header block.
2822 builder.setInsertionPointToEnd(&body.front());
2823 spirv::BranchOp::create(builder, location, mapper.lookupOrNull(headerBlock),
2824 ArrayRef<Value>(blockArgs));
2825 }
2826
2827 // Values defined inside the selection region that need to be yielded outside
2828 // the region.
2829 SmallVector<Value> valuesToYield;
2830 // Outside uses of values that were sunk into the selection region. Those uses
2831 // will be replaced with values returned by the SelectionOp.
2832 SmallVector<Value> outsideUses;
2833
2834 // Move block arguments of the original block (`mergeBlock`) into the merge
2835 // block inside the selection (`body.back()`). Values produced by block
2836 // arguments will be yielded by the selection region. We do not update uses or
2837 // erase original block arguments yet. It will be done later in the code.
2838 //
2839 // Code below is not executed for loops as it would interfere with the logic
2840 // above. Currently block arguments in the merge block are not supported, but
2841 // instead, the code above copies those arguments from the header block into
2842 // the merge block. As such, running the code would yield those copied
2843 // arguments that is most likely not a desired behaviour. This may need to be
2844 // revisited in the future.
2845 if (!isLoop)
2846 for (BlockArgument blockArg : mergeBlock->getArguments()) {
2847 // Create new block arguments in the last block ("merge block") of the
2848 // selection region. We create one argument for each argument in
2849 // `mergeBlock`. This new value will need to be yielded, and the original
2850 // value replaced, so add them to appropriate vectors.
2851 body.back().addArgument(blockArg.getType(), blockArg.getLoc());
2852 valuesToYield.push_back(body.back().getArguments().back());
2853 outsideUses.push_back(blockArg);
2854 }
2855
2856 // All the blocks cloned into the SelectionOp/LoopOp's region can now be
2857 // cleaned up.
2858 LLVM_DEBUG(logger.startLine() << "[cf] cleaning up blocks after clone\n");
2859 // First we need to drop all operands' references inside all blocks. This is
2860 // needed because we can have blocks referencing SSA values from one another.
2861 for (auto *block : constructBlocks)
2862 block->dropAllReferences();
2863
2864 // All internal uses should be removed from original blocks by now, so
2865 // whatever is left is an outside use and will need to be yielded from
2866 // the newly created selection / loop region.
2867 for (Block *block : constructBlocks) {
2868 for (Operation &op : *block) {
2869 if (!op.use_empty())
2870 for (Value result : op.getResults()) {
2871 valuesToYield.push_back(mapper.lookupOrNull(result));
2872 outsideUses.push_back(result);
2873 }
2874 }
2875 for (BlockArgument &arg : block->getArguments()) {
2876 if (!arg.use_empty()) {
2877 valuesToYield.push_back(mapper.lookupOrNull(arg));
2878 outsideUses.push_back(arg);
2879 }
2880 }
2881 }
2882
2883 assert(valuesToYield.size() == outsideUses.size());
2884
2885 // If we need to yield any values from the selection / loop region we will
2886 // take care of it here.
2887 if (!valuesToYield.empty()) {
2888 LLVM_DEBUG(logger.startLine()
2889 << "[cf] yielding values from the selection / loop region\n");
2890
2891 // Update `mlir.merge` with values to be yield.
2892 auto mergeOps = body.back().getOps<spirv::MergeOp>();
2893 Operation *merge = llvm::getSingleElement(mergeOps);
2894 assert(merge);
2895 merge->setOperands(valuesToYield);
2896
2897 // MLIR does not allow changing the number of results of an operation, so
2898 // we create a new SelectionOp / LoopOp with required list of results and
2899 // move the region from the initial SelectionOp / LoopOp. The initial
2900 // operation is then removed. Since we move the region to the new op all
2901 // links between blocks and remapping we have previously done should be
2902 // preserved.
2903 builder.setInsertionPoint(&mergeBlock->front());
2904
2905 Operation *newOp = nullptr;
2906
2907 if (isLoop)
2908 newOp = spirv::LoopOp::create(builder, location,
2909 TypeRange(ValueRange(outsideUses)),
2910 static_cast<spirv::LoopControl>(control));
2911 else
2912 newOp = spirv::SelectionOp::create(
2913 builder, location, TypeRange(ValueRange(outsideUses)),
2914 static_cast<spirv::SelectionControl>(control));
2915
2916 newOp->getRegion(0).takeBody(body);
2917
2918 // Remove initial op and swap the pointer to the newly created one.
2919 op->erase();
2920 op = newOp;
2921
2922 // Update all outside uses to use results of the SelectionOp / LoopOp and
2923 // remove block arguments from the original merge block.
2924 for (unsigned i = 0, e = outsideUses.size(); i != e; ++i)
2925 outsideUses[i].replaceAllUsesWith(op->getResult(i));
2926
2927 // We do not support block arguments in loop merge block. Also running this
2928 // function with loop would break some of the loop specific code above
2929 // dealing with block arguments.
2930 if (!isLoop)
2931 mergeBlock->eraseArguments(0, mergeBlock->getNumArguments());
2932 }
2933
2934 // Check that whether some op in the to-be-erased blocks still has uses. Those
2935 // uses come from blocks that won't be sinked into the SelectionOp/LoopOp's
2936 // region. We cannot handle such cases given that once a value is sinked into
2937 // the SelectionOp/LoopOp's region, there is no escape for it.
2938 for (auto *block : constructBlocks) {
2939 if (!block->use_empty())
2940 return emitError(block->getParent()->getLoc(),
2941 "failed control flow structurization: "
2942 "block has uses outside of the "
2943 "enclosing selection/loop construct");
2944 for (Operation &op : *block)
2945 if (!op.use_empty())
2946 return op.emitOpError("failed control flow structurization: value has "
2947 "uses outside of the "
2948 "enclosing selection/loop construct");
2949 for (BlockArgument &arg : block->getArguments())
2950 if (!arg.use_empty())
2951 return emitError(arg.getLoc(), "failed control flow structurization: "
2952 "block argument has uses outside of the "
2953 "enclosing selection/loop construct");
2954 }
2955
2956 // Then erase all old blocks.
2957 for (auto *block : constructBlocks) {
2958 // We've cloned all blocks belonging to this construct into the structured
2959 // control flow op's region. Among these blocks, some may compose another
2960 // selection/loop. If so, they will be recorded within blockMergeInfo.
2961 // We need to update the pointers there to the newly remapped ones so we can
2962 // continue structurizing them later.
2963 //
2964 // We need to walk each block as constructBlocks do not include blocks
2965 // internal to ops already structured within those blocks. It is not
2966 // fully clear to me why the mergeInfo of blocks (yet to be structured)
2967 // inside already structured selections/loops get invalidated and needs
2968 // updating, however the following example code can cause a crash (depending
2969 // on the structuring order), when the most inner selection is being
2970 // structured after the outer selection and loop have been already
2971 // structured:
2972 //
2973 // spirv.mlir.for {
2974 // // ...
2975 // spirv.mlir.selection {
2976 // // ..
2977 // // A selection region that hasn't been yet structured!
2978 // // ..
2979 // }
2980 // // ...
2981 // }
2982 //
2983 // If the loop gets structured after the outer selection, but before the
2984 // inner selection. Moving the already structured selection inside the loop
2985 // will invalidate the mergeInfo of the region that is not yet structured.
2986 // Just going over constructBlocks will not check and updated header blocks
2987 // inside the already structured selection region. Walking block fixes that.
2988 //
2989 // TODO: If structuring was done in a fixed order starting with inner
2990 // most constructs this most likely not be an issue and the whole code
2991 // section could be removed. However, with the current non-deterministic
2992 // order this is not possible.
2993 //
2994 // TODO: The asserts in the following assumes input SPIR-V blob forms
2995 // correctly nested selection/loop constructs. We should relax this and
2996 // support error cases better.
2997 auto updateMergeInfo = [&](Block *block) -> WalkResult {
2998 auto it = blockMergeInfo.find(block);
2999 if (it != blockMergeInfo.end()) {
3000 // Use the original location for nested selection/loop ops.
3001 Location loc = it->second.loc;
3002 // Copy the control before the erase below invalidates `it`.
3003 uint32_t nestedControl = it->second.control;
3004
3005 Block *newHeader = mapper.lookupOrNull(block);
3006 if (!newHeader)
3007 return emitError(loc, "failed control flow structurization: nested "
3008 "loop header block should be remapped!");
3009
3010 Block *newContinue = it->second.continueBlock;
3011 if (newContinue) {
3012 newContinue = mapper.lookupOrNull(newContinue);
3013 if (!newContinue)
3014 return emitError(loc, "failed control flow structurization: nested "
3015 "loop continue block should be remapped!");
3016 }
3017
3018 Block *newMerge = it->second.mergeBlock;
3019 if (Block *mappedTo = mapper.lookupOrNull(newMerge))
3020 newMerge = mappedTo;
3021
3022 // Erase the stale entry before inserting the remapped one.
3023 blockMergeInfo.erase(it);
3024 blockMergeInfo.try_emplace(newHeader, loc, nestedControl, newMerge,
3025 newContinue);
3026 }
3027
3028 return WalkResult::advance();
3029 };
3030
3031 if (block->walk(updateMergeInfo).wasInterrupted())
3032 return failure();
3033
3034 // The structured selection/loop's entry block does not have arguments.
3035 // If the function's header block is also part of the structured control
3036 // flow, we cannot just simply erase it because it may contain arguments
3037 // matching the function signature and used by the cloned blocks.
3038 if (isFnEntryBlock(block)) {
3039 LLVM_DEBUG(logger.startLine() << "[cf] changing entry block " << block
3040 << " to only contain a spirv.Branch op\n");
3041 // Still keep the function entry block for the potential block arguments,
3042 // but replace all ops inside with a branch to the merge block.
3043 block->clear();
3044 builder.setInsertionPointToEnd(block);
3045 spirv::BranchOp::create(builder, location, mergeBlock);
3046 } else {
3047 LLVM_DEBUG(logger.startLine() << "[cf] erasing block " << block << "\n");
3048 block->erase();
3049 }
3050 }
3051
3052 LLVM_DEBUG(logger.startLine()
3053 << "[cf] after structurizing construct with header block "
3054 << headerBlock << ":\n"
3055 << *op << "\n");
3056
3057 return success();
3058}
3059
3061 LLVM_DEBUG({
3062 logger.startLine()
3063 << "//----- [phi] start wiring up block arguments -----//\n";
3064 logger.indent();
3065 });
3066
3067 OpBuilder::InsertionGuard guard(opBuilder);
3068
3069 for (const auto &info : blockPhiInfo) {
3070 Block *block = info.first.first;
3071 Block *target = info.first.second;
3072 const BlockPhiInfo &phiInfo = info.second;
3073 LLVM_DEBUG({
3074 logger.startLine() << "[phi] block " << block << "\n";
3075 logger.startLine() << "[phi] before creating block argument:\n";
3076 block->getParentOp()->print(logger.getOStream());
3077 logger.startLine() << "\n";
3078 });
3079
3080 // Set insertion point to before this block's terminator early because we
3081 // may materialize ops via getValue() call.
3082 auto *op = block->getTerminator();
3083 opBuilder.setInsertionPoint(op);
3084
3085 SmallVector<Value, 4> blockArgs;
3086 blockArgs.reserve(phiInfo.size());
3087 for (uint32_t valueId : phiInfo) {
3088 if (Value value = getValue(valueId)) {
3089 blockArgs.push_back(value);
3090 LLVM_DEBUG(logger.startLine() << "[phi] block argument " << value
3091 << " id = " << valueId << "\n");
3092 } else {
3093 return emitError(unknownLoc, "OpPhi references undefined value!");
3094 }
3095 }
3096
3097 if (auto branchOp = dyn_cast<spirv::BranchOp>(op)) {
3098 // Replace the previous branch op with a new one with block arguments.
3099 spirv::BranchOp::create(opBuilder, branchOp.getLoc(),
3100 branchOp.getTarget(), blockArgs);
3101 branchOp.erase();
3102 } else if (auto branchCondOp = dyn_cast<spirv::BranchConditionalOp>(op)) {
3103 assert((branchCondOp.getTrueBlock() == target ||
3104 branchCondOp.getFalseBlock() == target) &&
3105 "expected target to be either the true or false target");
3106 if (target == branchCondOp.getTrueTarget())
3107 spirv::BranchConditionalOp::create(
3108 opBuilder, branchCondOp.getLoc(), branchCondOp.getCondition(),
3109 blockArgs, branchCondOp.getFalseBlockArguments(),
3110 branchCondOp.getBranchWeightsAttr(), branchCondOp.getTrueTarget(),
3111 branchCondOp.getFalseTarget());
3112 else
3113 spirv::BranchConditionalOp::create(
3114 opBuilder, branchCondOp.getLoc(), branchCondOp.getCondition(),
3115 branchCondOp.getTrueBlockArguments(), blockArgs,
3116 branchCondOp.getBranchWeightsAttr(), branchCondOp.getTrueBlock(),
3117 branchCondOp.getFalseBlock());
3118
3119 branchCondOp.erase();
3120 } else if (auto switchOp = dyn_cast<spirv::SwitchOp>(op)) {
3121 if (target == switchOp.getDefaultTarget()) {
3122 SmallVector<ValueRange> targetOperands(switchOp.getTargetOperands());
3123 DenseIntElementsAttr literals =
3124 switchOp.getLiterals().value_or(DenseIntElementsAttr());
3125 spirv::SwitchOp::create(
3126 opBuilder, switchOp.getLoc(), switchOp.getSelector(),
3127 switchOp.getDefaultTarget(), blockArgs, literals,
3128 switchOp.getTargets(), targetOperands);
3129 switchOp.erase();
3130 } else {
3131 SuccessorRange targets = switchOp.getTargets();
3132 auto it = llvm::find(targets, target);
3133 assert(it != targets.end());
3134 size_t index = std::distance(targets.begin(), it);
3135 switchOp.getTargetOperandsMutable(index).assign(blockArgs);
3136 }
3137 } else {
3138 return emitError(unknownLoc, "unimplemented terminator for Phi creation");
3139 }
3140
3141 LLVM_DEBUG({
3142 logger.startLine() << "[phi] after creating block argument:\n";
3143 block->getParentOp()->print(logger.getOStream());
3144 logger.startLine() << "\n";
3145 });
3146 }
3147 blockPhiInfo.clear();
3148
3149 LLVM_DEBUG({
3150 logger.unindent();
3151 logger.startLine()
3152 << "//--- [phi] completed wiring up block arguments ---//\n";
3153 });
3154 return success();
3155}
3156
3158 // Create a copy, so we can modify keys in the original.
3159 BlockMergeInfoMap blockMergeInfoCopy = blockMergeInfo;
3160 for (auto [block, mergeInfo] : blockMergeInfoCopy) {
3161 // Skip processing loop regions. For loop regions continueBlock is non-null.
3162 if (mergeInfo.continueBlock)
3163 continue;
3164
3165 if (!block->mightHaveTerminator())
3166 continue;
3167
3168 Operation *terminator = block->getTerminator();
3169 assert(terminator);
3170
3171 if (!isa<spirv::BranchConditionalOp, spirv::SwitchOp>(terminator))
3172 continue;
3173
3174 // Check if the current header block is a merge block of another construct.
3175 bool splitHeaderMergeBlock = false;
3176 for (const auto &[_, mergeInfo] : blockMergeInfo) {
3177 if (mergeInfo.mergeBlock == block)
3178 splitHeaderMergeBlock = true;
3179 }
3180
3181 // Do not split a block that only contains a conditional branch / switch,
3182 // unless it is also a merge block of another construct - in that case we
3183 // want to split the block. We do not want two constructs to share header /
3184 // merge block. The entry block cannot join a region, so split it too.
3185 if (!llvm::hasSingleElement(*block) || splitHeaderMergeBlock ||
3186 isFnEntryBlock(block)) {
3187 Block *newBlock = block->splitBlock(terminator);
3188 OpBuilder builder(block, block->end());
3189 spirv::BranchOp::create(builder, block->getParent()->getLoc(), newBlock);
3190
3191 // After splitting we need to update the map to use the new block as a
3192 // header.
3193 blockMergeInfo.erase(block);
3194 blockMergeInfo.try_emplace(newBlock, mergeInfo);
3195 }
3196 }
3197
3198 return success();
3199}
3200
3202 if (!options.enableControlFlowStructurization) {
3203 LLVM_DEBUG(
3204 {
3205 logger.startLine()
3206 << "//----- [cf] skip structurizing control flow -----//\n";
3207 logger.indent();
3208 });
3209 return success();
3210 }
3211
3212 LLVM_DEBUG({
3213 logger.startLine()
3214 << "//----- [cf] start structurizing control flow -----//\n";
3215 logger.indent();
3216 });
3217
3218 LLVM_DEBUG({
3219 logger.startLine() << "[cf] split conditional blocks\n";
3220 logger.startLine() << "\n";
3221 });
3222
3223 if (failed(splitSelectionHeader())) {
3224 return failure();
3225 }
3226
3227 while (!blockMergeInfo.empty()) {
3228 Block *headerBlock = blockMergeInfo.begin()->first;
3229 BlockMergeInfo mergeInfo = blockMergeInfo.begin()->second;
3230
3231 LLVM_DEBUG({
3232 logger.startLine() << "[cf] header block " << headerBlock << ":\n";
3233 headerBlock->print(logger.getOStream());
3234 logger.startLine() << "\n";
3235 });
3236
3237 auto *mergeBlock = mergeInfo.mergeBlock;
3238 assert(mergeBlock && "merge block cannot be nullptr");
3239 if (mergeInfo.continueBlock && !mergeBlock->args_empty())
3240 return emitError(unknownLoc, "OpPhi in loop merge block unimplemented");
3241 LLVM_DEBUG({
3242 logger.startLine() << "[cf] merge block " << mergeBlock << ":\n";
3243 mergeBlock->print(logger.getOStream());
3244 logger.startLine() << "\n";
3245 });
3246
3247 auto *continueBlock = mergeInfo.continueBlock;
3248 LLVM_DEBUG(if (continueBlock) {
3249 logger.startLine() << "[cf] continue block " << continueBlock << ":\n";
3250 continueBlock->print(logger.getOStream());
3251 logger.startLine() << "\n";
3252 });
3253 // Erase this case before calling into structurizer, who will update
3254 // blockMergeInfo.
3255 blockMergeInfo.erase(blockMergeInfo.begin());
3256 ControlFlowStructurizer structurizer(mergeInfo.loc, mergeInfo.control,
3257 blockMergeInfo, headerBlock,
3258 mergeBlock, continueBlock
3259#ifndef NDEBUG
3260 ,
3261 logger
3262#endif
3263 );
3264 if (failed(structurizer.structurize()))
3265 return failure();
3266 }
3267
3268 LLVM_DEBUG({
3269 logger.unindent();
3270 logger.startLine()
3271 << "//--- [cf] completed structurizing control flow ---//\n";
3272 });
3273 return success();
3274}
3275
3276//===----------------------------------------------------------------------===//
3277// Debug
3278//===----------------------------------------------------------------------===//
3279
3281 if (!debugLine)
3282 return unknownLoc;
3283
3284 auto fileName = debugInfoMap.lookup(debugLine->fileID).str();
3285 if (fileName.empty())
3286 fileName = "<unknown>";
3287 return FileLineColLoc::get(opBuilder.getStringAttr(fileName), debugLine->line,
3288 debugLine->column);
3289}
3290
3291LogicalResult
3293 // According to SPIR-V spec:
3294 // "This location information applies to the instructions physically
3295 // following this instruction, up to the first occurrence of any of the
3296 // following: the next end of block, the next OpLine instruction, or the next
3297 // OpNoLine instruction."
3298 if (operands.size() != 3)
3299 return emitError(unknownLoc, "OpLine must have 3 operands");
3300 debugLine = DebugLine{operands[0], operands[1], operands[2]};
3301 return success();
3302}
3303
3304void spirv::Deserializer::clearDebugLine() { debugLine = std::nullopt; }
3305
3306LogicalResult
3308 if (operands.size() < 2)
3309 return emitError(unknownLoc, "OpString needs at least 2 operands");
3310
3311 if (!debugInfoMap.lookup(operands[0]).empty())
3312 return emitError(unknownLoc,
3313 "duplicate debug string found for result <id> ")
3314 << operands[0];
3315
3316 unsigned wordIndex = 1;
3317 StringRef debugString = decodeStringLiteral(operands, wordIndex);
3318 if (wordIndex != operands.size())
3319 return emitError(unknownLoc,
3320 "unexpected trailing words in OpString instruction");
3321
3322 debugInfoMap[operands[0]] = debugString;
3323 return success();
3324}
return success()
static bool isLoop(Operation *op)
Returns true if the given operation represents a loop by testing whether it implements the LoopLikeOp...
static bool isFnEntryBlock(Block *block)
Returns true if the given block is a function entry block.
#define MIN_VERSION_CASE(v)
static void setInherentOrDiscardableAttr(Operation *op, StringAttr name, Attribute value)
static LogicalResult deserializeCacheControlDecoration(Location loc, OpBuilder &opBuilder, DenseMap< uint32_t, NamedAttrList > &decorations, ArrayRef< uint32_t > words, StringAttr symbol, StringRef decorationName, StringRef cacheControlKind)
static llvm::ManagedStatic< PassManagerOptions > options
Attributes are known-constant values of operations.
Definition Attributes.h:25
This class represents an argument of a Block.
Definition Value.h:308
Block represents an ordered list of Operations.
Definition Block.h:34
bool empty()
Definition Block.h:173
void erase()
Unlink this Block from its parent region and delete it.
Definition Block.cpp:66
Block * splitBlock(iterator splitBefore)
Split the block into two blocks before the specified operation or iterator.
Definition Block.cpp:323
Operation & front()
Definition Block.h:178
Operation * getTerminator()
Get the terminator operation of this block.
Definition Block.cpp:249
void print(raw_ostream &os)
bool args_empty()
Definition Block.h:124
iterator begin()
Definition Block.h:168
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
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
Definition Builders.cpp:275
Attr getAttr(Args &&...args)
Get or construct an instance of the attribute Attr with provided arguments.
Definition Builders.h:101
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
An attribute that represents a reference to a dense integer vector or tensor object.
static FileLineColLoc get(StringAttr filename, unsigned line, unsigned column)
Definition Location.cpp:161
A symbol reference with a reference path containing a single element.
static FlatSymbolRefAttr get(StringAttr value)
Construct a symbol reference for the given value name.
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
Definition IRMapping.h:30
auto lookupOrNull(T from) const
Lookup a mapped value within the map.
Definition IRMapping.h:58
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
NamedAttrList is array of NamedAttributes that tracks whether it is sorted and does some basic work t...
DictionaryAttr getDictionary(MLIRContext *context) const
Return a dictionary attribute for the underlying dictionary.
Attribute set(StringAttr name, Attribute value)
If the an attribute exists with the specified name, change it to the new value.
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:166
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:351
This class helps build Operations.
Definition Builders.h:210
void setInherentAttr(Operation *op, StringAttr name, Attribute value) const
std::optional< Attribute > getInherentAttr(Operation *op, StringRef name) const
Lookup an inherent attribute by name, this method isn't recommended and may be removed in the future.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
MutableArrayRef< BlockOperand > getBlockOperands()
Definition Operation.h:749
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
Definition Operation.h:740
bool use_empty()
Returns true if this operation has no uses.
Definition Operation.h:906
void setDiscardableAttr(StringAttr name, Attribute value)
Set a discardable attribute by name.
Definition Operation.h:514
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
MutableArrayRef< OpOperand > getOpOperands()
Definition Operation.h:410
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:115
void print(raw_ostream &os, const OpPrintingFlags &flags={})
static Operation * create(Location location, OperationName name, TypeRange resultTypes, ValueRange operands, NamedAttrList &&attributes, PropertyRef properties, BlockRange successors, unsigned numRegions)
Create a new Operation with the specific fields.
Definition Operation.cpp:65
result_range getResults()
Definition Operation.h:442
Operation * clone(IRMapping &mapper, const CloneOptions &options=CloneOptions::all())
Create a deep copy of this operation, remapping any operands that use values outside of the operation...
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
void erase()
Remove this operation from its parent block and delete it.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
Block & back()
Definition Region.h:64
iterator end()
Definition Region.h:56
BlockListType & getBlocks()
Definition Region.h:45
BlockListType::iterator iterator
Definition Region.h:52
void takeBody(Region &other)
Takes body of another region (that region will have no body after this operation completes).
Definition Region.h:253
This class implements the successor iterators for Block.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
Definition Types.cpp:118
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
static WalkResult advance()
Definition WalkResult.h:47
static ArrayType get(Type elementType, unsigned elementCount)
static CooperativeMatrixType getChecked(function_ref< InFlightDiagnostic()> emitError, MLIRContext *context, Type elementType, uint32_t rows, uint32_t columns, Scope scope, CooperativeMatrixUseKHR use)
LogicalResult wireUpBlockArgument()
Creates block arguments on predecessors previously recorded when handling OpPhi instructions.
Value materializeSpecConstantOperation(uint32_t resultID, spirv::Opcode enclosedOpcode, uint32_t resultTypeID, ArrayRef< uint32_t > enclosedOpOperands)
Materializes/emits an OpSpecConstantOp instruction.
LogicalResult processOpTypePointer(ArrayRef< uint32_t > operands)
Value getValue(uint32_t id)
Get the Value associated with a result <id>.
LogicalResult processMatrixType(ArrayRef< uint32_t > operands)
std::optional< SpecConstOperationMaterializationInfo > getSpecConstantOperation(uint32_t id)
Gets the info needed to materialize the spec constant operation op associated with the given <id>.
LogicalResult processConstantNull(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpConstantNull instruction with the given operands.
LogicalResult processSpecConstantComposite(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpSpecConstantComposite instruction with the given operands.
LogicalResult processInstruction(spirv::Opcode opcode, ArrayRef< uint32_t > operands, bool deferInstructions=true)
Processes a SPIR-V instruction with the given opcode and operands.
LogicalResult processBranchConditional(ArrayRef< uint32_t > operands)
LogicalResult processGlobalVariable(spirv::Opcode opcode, ArrayRef< uint32_t > operands)
Processes the OpVariable or OpUntypedVariableKHR instructions at current offset into binary.
spirv::GlobalVariableOp getGlobalVariable(uint32_t id)
Gets the global variable associated with a result <id> of OpVariable.
LogicalResult createGraphBlock(uint32_t graphID)
Creates a block for graph with the given graphID.
LogicalResult processStructType(ArrayRef< uint32_t > operands)
LogicalResult processGraphARM(ArrayRef< uint32_t > operands)
LogicalResult processSamplerType(ArrayRef< uint32_t > operands)
LogicalResult setFunctionArgAttrs(uint32_t argID, SmallVectorImpl< Attribute > &argAttrs, size_t argIndex)
Sets the function argument's attributes.
LogicalResult structurizeControlFlow()
Extracts blocks belonging to a structured selection/loop into a spirv.mlir.selection/spirv....
LogicalResult processLabel(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpLabel instruction with the given operands.
LogicalResult processUntypedPointerType(ArrayRef< uint32_t > operands)
LogicalResult processSampledImageType(ArrayRef< uint32_t > operands)
LogicalResult processTensorARMType(ArrayRef< uint32_t > operands)
std::optional< spirv::GraphConstantARMOpMaterializationInfo > getGraphConstantARM(uint32_t id)
Gets the GraphConstantARM ID attribute and result type with the given result <id>.
std::optional< std::pair< Attribute, Type > > getConstant(uint32_t id)
Gets the constant's attribute and type associated with the given <id>.
LogicalResult processType(spirv::Opcode opcode, ArrayRef< uint32_t > operands)
Processes a SPIR-V type instruction with given opcode and operands and registers the type into module...
LogicalResult processLoopMerge(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpLoopMerge instruction with the given operands.
LogicalResult processArrayType(ArrayRef< uint32_t > operands)
LogicalResult sliceInstruction(spirv::Opcode &opcode, ArrayRef< uint32_t > &operands, std::optional< spirv::Opcode > expectedOpcode=std::nullopt)
Slices the first instruction out of binary and returns its opcode and operands via opcode and operand...
spirv::SpecConstantCompositeOp getSpecConstantComposite(uint32_t id)
Gets the composite specialization constant with the given result <id>.
LogicalResult processNamedBarrierType(ArrayRef< uint32_t > operands)
SmallVector< uint32_t, 2 > BlockPhiInfo
For OpPhi instructions, we use block arguments to represent them.
Type getUndefType(uint32_t id)
Get the type associated with the result <id> of an OpUndef.
LogicalResult processSpecConstantCompositeReplicateEXT(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpSpecConstantCompositeReplicateEXT instruction with the given operands.
LogicalResult processCooperativeMatrixTypeKHR(ArrayRef< uint32_t > operands)
LogicalResult processGraphEntryPointARM(ArrayRef< uint32_t > operands)
LogicalResult processFunction(ArrayRef< uint32_t > operands)
Creates a deserializer for the given SPIR-V binary module.
StringAttr getSymbolDecoration(StringRef decorationName)
Gets the symbol name from the name of decoration.
Block * getOrCreateBlock(uint32_t id)
Gets or creates the block corresponding to the given label <id>.
bool isVoidType(Type type) const
Returns true if the given type is for SPIR-V void type.
std::string getSpecConstantSymbol(uint32_t id)
Returns a symbol to be used for the specialization constant with the given result <id>.
LogicalResult processDebugString(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpString instruction with the given operands.
LogicalResult processPhi(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpPhi instruction with the given operands.
std::string getFunctionSymbol(uint32_t id)
Returns a symbol to be used for the function name with the given result <id>.
void clearDebugLine()
Discontinues any source-level location information that might be active from a previous OpLine instru...
LogicalResult processFunctionType(ArrayRef< uint32_t > operands)
IntegerAttr getConstantInt(uint32_t id)
Gets the constant's integer attribute with the given <id>.
LogicalResult processTypeForwardPointer(ArrayRef< uint32_t > operands)
LogicalResult processSwitch(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpSwitch instruction with the given operands.
LogicalResult processGraphEndARM(ArrayRef< uint32_t > operands)
LogicalResult processImageType(ArrayRef< uint32_t > operands)
LogicalResult processConstantComposite(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpConstantComposite instruction with the given operands.
spirv::SpecConstantOp createSpecConstant(Location loc, uint32_t resultID, TypedAttr defaultValue)
Creates a spirv::SpecConstantOp.
Block * getBlock(uint32_t id) const
Returns the block for the given label <id>.
LogicalResult processGraphTypeARM(ArrayRef< uint32_t > operands)
LogicalResult processBranch(ArrayRef< uint32_t > operands)
std::optional< std::pair< Attribute, Type > > getConstantCompositeReplicate(uint32_t id)
Gets the replicated composite constant's attribute and type associated with the given <id>.
LogicalResult processFunctionEnd(ArrayRef< uint32_t > operands)
Processes OpFunctionEnd and finalizes function.
LogicalResult processRuntimeArrayType(ArrayRef< uint32_t > operands)
LogicalResult processSpecConstantOperation(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpSpecConstantOp instruction with the given operands.
LogicalResult processConstant(ArrayRef< uint32_t > operands, bool isSpec)
Processes a SPIR-V Op{|Spec}Constant instruction with the given operands.
Location createFileLineColLoc(OpBuilder opBuilder)
Creates a FileLineColLoc with the OpLine location information.
LogicalResult processGraphConstantARM(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpGraphConstantARM instruction with the given operands.
LogicalResult processConstantBool(bool isTrue, ArrayRef< uint32_t > operands, bool isSpec)
Processes a SPIR-V Op{|Spec}Constant{True|False} instruction with the given operands.
spirv::SpecConstantOp getSpecConstant(uint32_t id)
Gets the specialization constant with the given result <id>.
LogicalResult processConstantCompositeReplicateEXT(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpConstantCompositeReplicateEXT instruction with the given operands.
LogicalResult processSelectionMerge(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpSelectionMerge instruction with the given operands.
LogicalResult processOpGraphSetOutputARM(ArrayRef< uint32_t > operands)
LogicalResult processDebugLine(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpLine instruction with the given operands.
std::optional< std::pair< Type, SmallVector< uint32_t > > > getUndefComposite(uint32_t id)
Gets the type and constituent <id>s of the undef composite with the given <id>.
LogicalResult splitSelectionHeader()
Move a conditional branch or a switch into a separate basic block to avoid unnecessary sinking of def...
std::string getGraphSymbol(uint32_t id)
Returns a symbol to be used for the graph name with the given result <id>.
static ImageType getChecked(function_ref< InFlightDiagnostic()> emitError, MLIRContext *context, std::tuple< Type, Dim, ImageDepthInfo, ImageArrayedInfo, ImageSamplingInfo, ImageSamplerUseInfo, ImageFormat > value)
static MatrixType getChecked(function_ref< InFlightDiagnostic()> emitError, Type columnType, uint32_t columnCount)
static NamedBarrierType get(MLIRContext *context)
static PointerType getChecked(function_ref< InFlightDiagnostic()> emitError, MLIRContext *context, Type pointeeType, StorageClass storageClass)
static RuntimeArrayType get(Type elementType)
static SampledImageType get(Type imageType)
static SamplerType get(MLIRContext *context)
static StructType getIdentified(MLIRContext *context, StringRef identifier)
Construct an identified StructType.
static StructType getEmpty(MLIRContext *context, StringRef identifier="")
Construct a (possibly identified) StructType with no members.
static StructType get(ArrayRef< Type > memberTypes, ArrayRef< OffsetInfo > offsetInfo={}, ArrayRef< MemberDecorationInfo > memberDecorations={}, ArrayRef< StructDecorationInfo > structDecorations={})
Construct a literal StructType with at least one member.
static TensorArmType get(ArrayRef< int64_t > shape, Type elementType)
static UntypedPointerType get(MLIRContext *context, StorageClass storageClass)
static VerCapExtAttr get(Version version, ArrayRef< Capability > capabilities, ArrayRef< Extension > extensions, MLIRContext *context)
Gets a VerCapExtAttr instance.
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Definition CallGraph.h:229
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
SmallVector< Operation * > mergeOps
Computation function returning, for the op currently being tiled or fused, the per-iteration-domain-d...
constexpr uint32_t kMagicNumber
SPIR-V magic number.
llvm::MapVector< Block *, BlockMergeInfo > BlockMergeInfoMap
Map from a selection/loop's header block to its merge (and continue) target.
StringRef getFuncParamAttrName()
Returns the attribute name for specifying function parameter and result attributes.
StringRef getFuncParamAlignmentAttrName()
Returns the attribute name for specifying function parameter alignment.
StringRef decodeStringLiteral(ArrayRef< uint32_t > words, unsigned &wordIndex)
Decodes a string literal in words starting at wordIndex.
constexpr unsigned kHeaderWordCount
SPIR-V binary header word count.
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
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
std::string debugString(T &&op)
A struct for containing a header block's merge and continue targets.
A struct for containing OpLine instruction information.
A struct that collects the info needed to materialize/emit a GraphConstantARMOp.
A struct that collects the info needed to materialize/emit a SpecConstantOperation op.