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