MLIR 24.0.0git
Deserializer.h
Go to the documentation of this file.
1//===- Deserializer.h - MLIR SPIR-V Deserializer ----------------*- C++ -*-===//
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 declares the SPIR-V binary to MLIR SPIR-V module deserializer.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef MLIR_TARGET_SPIRV_DESERIALIZER_H
14#define MLIR_TARGET_SPIRV_DESERIALIZER_H
15
18#include "mlir/IR/Builders.h"
20#include "llvm/ADT/ArrayRef.h"
21#include "llvm/ADT/SetVector.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/Support/ScopedPrinter.h"
24#include <cstdint>
25#include <optional>
26
27namespace mlir {
28namespace spirv {
29
30//===----------------------------------------------------------------------===//
31// Utility Definitions
32//===----------------------------------------------------------------------===//
33
34/// A struct for containing a header block's merge and continue targets.
35///
36/// This struct is used to track original structured control flow info from
37/// SPIR-V blob. This info will be used to create
38/// spirv.mlir.selection/spirv.mlir.loop later.
41 Block *continueBlock; // nullptr for spirv.mlir.selection
43 uint32_t control; // Selection/loop control
44
45 BlockMergeInfo(Location location, uint32_t control)
48 BlockMergeInfo(Location location, uint32_t control, Block *m,
49 Block *c = nullptr)
50 : mergeBlock(m), continueBlock(c), loc(location), control(control) {}
51};
52
53/// A struct for containing OpLine instruction information.
54struct DebugLine {
55 uint32_t fileID;
56 uint32_t line;
57 uint32_t column;
58};
59
60/// Map from a selection/loop's header block to its merge (and continue) target.
61/// Use `MapVector<>` to ensure a deterministic iteration order with a pointer
62/// key.
64
65/// A "deferred struct type" is a struct type with one or more member types not
66/// known when the Deserializer first encounters the struct. This happens, for
67/// example, with recursive structs where a pointer to the struct type is
68/// forward declared through OpTypeForwardPointer in the SPIR-V module before
69/// the struct declaration; the actual pointer to struct type should be defined
70/// later through an OpTypePointer. For example, the following C struct:
71///
72/// struct A {
73/// A* next;
74/// };
75///
76/// would be represented in the SPIR-V module as:
77///
78/// OpName %A "A"
79/// OpTypeForwardPointer %APtr Generic
80/// %A = OpTypeStruct %APtr
81/// %APtr = OpTypePointer Generic %A
82///
83/// This means that the spirv::StructType cannot be fully constructed directly
84/// when the Deserializer encounters it. Instead we create a
85/// DeferredStructTypeInfo that contains all the information we know about the
86/// spirv::StructType. Once all forward references for the struct are resolved,
87/// the struct's body is set with all member info.
90
91 // A list of all unresolved member types for the struct. First element of each
92 // item is operand ID, second element is member index in the struct.
94
95 // The list of member types. For unresolved members, this list contains
96 // place-holder empty types that will be updated later.
101};
102
103/// A struct that collects the info needed to materialize/emit a
104/// SpecConstantOperation op.
110
111/// A struct that collects the info needed to materialize/emit a
112/// GraphConstantARMOp.
117
118//===----------------------------------------------------------------------===//
119// Deserializer Declaration
120//===----------------------------------------------------------------------===//
121
122/// A SPIR-V module serializer.
123///
124/// A SPIR-V binary module is a single linear stream of instructions; each
125/// instruction is composed of 32-bit words. The first word of an instruction
126/// records the total number of words of that instruction using the 16
127/// higher-order bits. So this deserializer uses that to get instruction
128/// boundary and parse instructions and build a SPIR-V ModuleOp gradually.
129///
130// TODO: clean up created ops on errors
132public:
133 /// Creates a deserializer for the given SPIR-V `binary` module.
134 /// The SPIR-V ModuleOp will be created into `context.
135 explicit Deserializer(ArrayRef<uint32_t> binary, MLIRContext *context,
136 const DeserializationOptions &options);
137
138 /// Deserializes the remembered SPIR-V binary module.
139 LogicalResult deserialize();
140
141 /// Collects the final SPIR-V ModuleOp.
143
144private:
145 //===--------------------------------------------------------------------===//
146 // Module structure
147 //===--------------------------------------------------------------------===//
148
149 /// Initializes the `moduleOp` ModuleOp in this deserializer instance.
150 OwningOpRef<spirv::ModuleOp> createModuleOp();
151
152 /// Processes SPIR-V module header in `binary`.
153 LogicalResult processHeader();
154
155 /// Processes the SPIR-V OpCapability with `operands` and updates bookkeeping
156 /// in the deserializer.
157 LogicalResult processCapability(ArrayRef<uint32_t> operands);
158
159 /// Processes the SPIR-V OpExtension with `operands` and updates bookkeeping
160 /// in the deserializer.
161 LogicalResult processExtension(ArrayRef<uint32_t> words);
162
163 /// Processes the SPIR-V OpExtInstImport with `operands` and updates
164 /// bookkeeping in the deserializer.
165 LogicalResult processExtInstImport(ArrayRef<uint32_t> words);
166
167 /// Attaches (version, capabilities, extensions) triple to `moduleOp` as an
168 /// attribute.
169 void attachVCETriple();
170
171 /// Processes the SPIR-V OpMemoryModel with `operands` and updates `moduleOp`.
172 LogicalResult processMemoryModel(ArrayRef<uint32_t> operands);
173
174 /// Process SPIR-V OpName with `operands`.
175 LogicalResult processName(ArrayRef<uint32_t> operands);
176
177 /// Processes an OpDecorate instruction.
178 LogicalResult processDecoration(ArrayRef<uint32_t> words);
179
180 /// Resolves all OpDecorateId entries previously queued during
181 /// processDecoration. Called after all module ops have been deserialized so
182 /// the operand <id>s can be looked up as MLIR symbols.
183 LogicalResult resolveDeferredIdDecorations();
184
185 // Processes an OpMemberDecorate instruction.
186 LogicalResult processMemberDecoration(ArrayRef<uint32_t> words);
187
188 /// Processes an OpMemberName instruction.
189 LogicalResult processMemberName(ArrayRef<uint32_t> words);
190
191 /// Gets the function op associated with a result <id> of OpFunction.
192 spirv::FuncOp getFunction(uint32_t id) { return funcMap.lookup(id); }
193
194 /// Processes the SPIR-V function at the current `offset` into `binary`.
195 /// The operands to the OpFunction instruction is passed in as ``operands`.
196 /// This method processes each instruction inside the function and dispatches
197 /// them to their handler method accordingly.
198 LogicalResult processFunction(ArrayRef<uint32_t> operands);
199
200 /// Processes OpFunctionEnd and finalizes function. This wires up block
201 /// argument created from OpPhi instructions and also structurizes control
202 /// flow.
203 LogicalResult processFunctionEnd(ArrayRef<uint32_t> operands);
204
205 /// Gets the constant's attribute and type associated with the given <id>.
206 std::optional<std::pair<Attribute, Type>> getConstant(uint32_t id);
207
208 /// Gets the replicated composite constant's attribute and type associated
209 /// with the given <id>.
210 std::optional<std::pair<Attribute, Type>>
212
213 /// Gets the info needed to materialize the spec constant operation op
214 /// associated with the given <id>.
215 std::optional<SpecConstOperationMaterializationInfo>
216 getSpecConstantOperation(uint32_t id);
217
218 /// Gets the type and constituent <id>s of the undef composite with the
219 /// given <id>.
220 std::optional<std::pair<Type, SmallVector<uint32_t>>>
221 getUndefComposite(uint32_t id);
222
223 /// Gets the constant's integer attribute with the given <id>. Returns a
224 /// null IntegerAttr if the given is not registered or does not correspond
225 /// to an integer constant.
226 IntegerAttr getConstantInt(uint32_t id);
227
228 /// Returns a symbol to be used for the function name with the given
229 /// result <id>. This tries to use the function's OpName if
230 /// exists; otherwise creates one based on the <id>.
231 std::string getFunctionSymbol(uint32_t id);
232
233 /// Returns a symbol to be used for the graph name with the given
234 /// result <id>. This tries to use the graph's OpName if
235 /// exists; otherwise creates one based on the <id>.
236 std::string getGraphSymbol(uint32_t id);
237
238 /// Returns a symbol to be used for the specialization constant with the
239 /// given result <id>. This tries to use the specialization constant's
240 /// OpName if exists; otherwise creates one based on the <id>.
241 std::string getSpecConstantSymbol(uint32_t id);
242
243 /// Gets the specialization constant with the given result <id>.
244 spirv::SpecConstantOp getSpecConstant(uint32_t id) {
245 return specConstMap.lookup(id);
246 }
247
248 /// Gets the composite specialization constant with the given result <id>.
249 spirv::SpecConstantCompositeOp getSpecConstantComposite(uint32_t id) {
250 return specConstCompositeMap.lookup(id);
251 }
252
253 /// Gets the replicated composite specialization constant with the given
254 /// result <id>.
255 spirv::EXTSpecConstantCompositeReplicateOp
257 return specConstCompositeReplicateMap.lookup(id);
258 }
259
260 /// Creates a spirv::SpecConstantOp.
261 spirv::SpecConstantOp createSpecConstant(Location loc, uint32_t resultID,
262 TypedAttr defaultValue);
263
264 /// Gets the GraphConstantARM ID attribute and result type with the given
265 /// result <id>.
266 std::optional<spirv::GraphConstantARMOpMaterializationInfo>
267 getGraphConstantARM(uint32_t id);
268
269 /// Processes the OpVariable or OpUntypedVariableKHR instructions at current
270 /// `offset` into `binary`. It is expected that this method is used for
271 /// variables that are to be defined at module scope and will be deserialized
272 /// into a spirv.GlobalVariable instruction.
273 LogicalResult processGlobalVariable(spirv::Opcode opcode,
274 ArrayRef<uint32_t> operands);
275
276 /// Gets the global variable associated with a result <id> of OpVariable.
277 spirv::GlobalVariableOp getGlobalVariable(uint32_t id) {
278 return globalVariableMap.lookup(id);
279 }
280
281 /// Sets the function argument's attributes. |argID| is the function
282 /// argument's result <id>, and |argIndex| is its index in the function's
283 /// argument list.
284 LogicalResult setFunctionArgAttrs(uint32_t argID,
286 size_t argIndex);
287
288 /// Gets the symbol name from the name of decoration.
289 StringAttr getSymbolDecoration(StringRef decorationName) {
290 auto attrName = llvm::convertToSnakeFromCamelCase(decorationName);
291 return opBuilder.getStringAttr(attrName);
292 }
293
294 /// Move a conditional branch or a switch into a separate basic block to avoid
295 /// unnecessary sinking of defs that may be required outside a selection
296 /// region. This function also ensures that a single block cannot be a header
297 /// block of one selection construct and the merge block of another.
298 LogicalResult splitSelectionHeader();
299
300 //===--------------------------------------------------------------------===//
301 // Type
302 //===--------------------------------------------------------------------===//
303
304 /// Gets type for a given result <id>.
305 Type getType(uint32_t id) { return typeMap.lookup(id); }
306
307 /// Get the type associated with the result <id> of an OpUndef.
308 Type getUndefType(uint32_t id) { return undefMap.lookup(id); }
309
310 /// Gets the type and function <id> of an OpConstantFunctionPointerINTEL.
311 std::pair<Type, uint32_t> getConstantFunctionPointer(uint32_t id) {
312 return constantFunctionPointerMap.lookup(id);
313 }
314
315 /// Returns true if the given `type` is for SPIR-V void type.
316 bool isVoidType(Type type) const { return isa<NoneType>(type); }
317
318 /// Processes a SPIR-V type instruction with given `opcode` and `operands` and
319 /// registers the type into `moduleOp`.
320 LogicalResult processType(spirv::Opcode opcode, ArrayRef<uint32_t> operands);
321
322 LogicalResult processOpTypePointer(ArrayRef<uint32_t> operands);
323
324 LogicalResult processArrayType(ArrayRef<uint32_t> operands);
325
327
329
330 LogicalResult processFunctionType(ArrayRef<uint32_t> operands);
331
332 LogicalResult processImageType(ArrayRef<uint32_t> operands);
333
334 LogicalResult processSampledImageType(ArrayRef<uint32_t> operands);
335
336 LogicalResult processSamplerType(ArrayRef<uint32_t> operands);
337
338 LogicalResult processNamedBarrierType(ArrayRef<uint32_t> operands);
339
340 LogicalResult processUntypedPointerType(ArrayRef<uint32_t> operands);
341
342 LogicalResult processRuntimeArrayType(ArrayRef<uint32_t> operands);
343
344 LogicalResult processStructType(ArrayRef<uint32_t> operands);
345
346 LogicalResult processMatrixType(ArrayRef<uint32_t> operands);
347
348 LogicalResult processTensorARMType(ArrayRef<uint32_t> operands);
349
350 LogicalResult processGraphTypeARM(ArrayRef<uint32_t> operands);
351
352 LogicalResult processGraphEntryPointARM(ArrayRef<uint32_t> operands);
353
354 LogicalResult processGraphARM(ArrayRef<uint32_t> operands);
355
356 LogicalResult processOpGraphSetOutputARM(ArrayRef<uint32_t> operands);
357
358 LogicalResult processGraphEndARM(ArrayRef<uint32_t> operands);
359
360 LogicalResult processTypeForwardPointer(ArrayRef<uint32_t> operands);
361
362 //===--------------------------------------------------------------------===//
363 // Constant
364 //===--------------------------------------------------------------------===//
365
366 /// Processes a SPIR-V Op{|Spec}Constant instruction with the given
367 /// `operands`. `isSpec` indicates whether this is a specialization constant.
368 LogicalResult processConstant(ArrayRef<uint32_t> operands, bool isSpec);
369
370 /// Processes a SPIR-V Op{|Spec}Constant{True|False} instruction with the
371 /// given `operands`. `isSpec` indicates whether this is a specialization
372 /// constant.
373 LogicalResult processConstantBool(bool isTrue, ArrayRef<uint32_t> operands,
374 bool isSpec);
375
376 /// Processes a SPIR-V OpConstantComposite instruction with the given
377 /// `operands`.
378 LogicalResult processConstantComposite(ArrayRef<uint32_t> operands);
379
380 /// Processes a SPIR-V OpConstantCompositeReplicateEXT instruction with
381 /// the given `operands`.
382 LogicalResult
384
385 /// Processes a SPIR-V OpSpecConstantComposite instruction with the given
386 /// `operands`.
387 LogicalResult processSpecConstantComposite(ArrayRef<uint32_t> operands);
388
389 /// Processes a SPIR-V OpSpecConstantCompositeReplicateEXT instruction with
390 /// the given `operands`.
391 LogicalResult
393
394 /// Processes a SPIR-V OpSpecConstantOp instruction with the given
395 /// `operands`.
396 LogicalResult processSpecConstantOperation(ArrayRef<uint32_t> operands);
397
398 /// Materializes/emits an OpSpecConstantOp instruction.
399 Value materializeSpecConstantOperation(uint32_t resultID,
400 spirv::Opcode enclosedOpcode,
401 uint32_t resultTypeID,
402 ArrayRef<uint32_t> enclosedOpOperands);
403
404 /// Processes a SPIR-V OpConstantNull instruction with the given `operands`.
405 LogicalResult processConstantNull(ArrayRef<uint32_t> operands);
406
407 /// Processes a SPIR-V OpGraphConstantARM instruction with the given
408 /// `operands`.
409 LogicalResult processGraphConstantARM(ArrayRef<uint32_t> operands);
410
411 //===--------------------------------------------------------------------===//
412 // Debug
413 //===--------------------------------------------------------------------===//
414
415 /// Discontinues any source-level location information that might be active
416 /// from a previous OpLine instruction.
417 void clearDebugLine();
418
419 /// Creates a FileLineColLoc with the OpLine location information.
421
422 /// Processes a SPIR-V OpLine instruction with the given `operands`.
423 LogicalResult processDebugLine(ArrayRef<uint32_t> operands);
424
425 /// Processes a SPIR-V OpString instruction with the given `operands`.
426 LogicalResult processDebugString(ArrayRef<uint32_t> operands);
427
428 //===--------------------------------------------------------------------===//
429 // Control flow
430 //===--------------------------------------------------------------------===//
431
432 /// Returns the block for the given label <id>.
433 Block *getBlock(uint32_t id) const { return blockMap.lookup(id); }
434
435 // In SPIR-V, structured control flow is explicitly declared using merge
436 // instructions (OpSelectionMerge and OpLoopMerge). In the SPIR-V dialect,
437 // we use spirv.mlir.selection and spirv.mlir.loop to group structured control
438 // flow. The deserializer need to turn structured control flow marked with
439 // merge instructions into using spirv.mlir.selection/spirv.mlir.loop ops.
440 //
441 // Because structured control flow can nest and the basic block order have
442 // flexibility, we cannot isolate a structured selection/loop without
443 // deserializing all the blocks. So we use the following approach:
444 //
445 // 1. Deserialize all basic blocks in a function and create MLIR blocks for
446 // them into the function's region. In the meanwhile, keep a map between
447 // selection/loop header blocks to their corresponding merge (and continue)
448 // target blocks.
449 // 2. For each selection/loop header block, recursively get all basic blocks
450 // reachable (except the merge block) and put them in a newly created
451 // spirv.mlir.selection/spirv.mlir.loop's region. Structured control flow
452 // guarantees that we enter and exit in structured ways and the construct
453 // is nestable.
454 // 3. Put the new spirv.mlir.selection/spirv.mlir.loop op at the beginning of
455 // the
456 // old merge block and redirect all branches to the old header block to the
457 // old merge block (which contains the spirv.mlir.selection/spirv.mlir.loop
458 // op now).
459
460 /// For OpPhi instructions, we use block arguments to represent them. OpPhi
461 /// encodes a list of (value, predecessor) pairs. At the time of handling the
462 /// block containing an OpPhi instruction, the predecessor block might not be
463 /// processed yet, also the value sent by it. So we need to defer handling
464 /// the block argument from the predecessors. We use the following approach:
465 ///
466 /// 1. For each OpPhi instruction, add a block argument to the current block
467 /// in construction. Record the block argument in `valueMap` so its uses
468 /// can be resolved. For the list of (value, predecessor) pairs, update
469 /// `blockPhiInfo` for bookkeeping.
470 /// 2. After processing all blocks, loop over `blockPhiInfo` to fix up each
471 /// block recorded there to create the proper block arguments on their
472 /// terminators.
473
474 /// A data structure for containing a SPIR-V block's phi info. It will be
475 /// represented as block argument in SPIR-V dialect.
477 SmallVector<uint32_t, 2>; // The result <id> of the values sent
478
479 /// Gets or creates the block corresponding to the given label <id>. The newly
480 /// created block will always be placed at the end of the current function.
481 Block *getOrCreateBlock(uint32_t id);
482
483 LogicalResult processBranch(ArrayRef<uint32_t> operands);
484
485 LogicalResult processBranchConditional(ArrayRef<uint32_t> operands);
486
487 /// Processes a SPIR-V OpLabel instruction with the given `operands`.
488 LogicalResult processLabel(ArrayRef<uint32_t> operands);
489
490 /// Processes a SPIR-V OpSelectionMerge instruction with the given `operands`.
491 LogicalResult processSelectionMerge(ArrayRef<uint32_t> operands);
492
493 /// Processes a SPIR-V OpLoopMerge instruction with the given `operands`.
494 LogicalResult processLoopMerge(ArrayRef<uint32_t> operands);
495
496 /// Processes a SPIR-V OpPhi instruction with the given `operands`.
497 LogicalResult processPhi(ArrayRef<uint32_t> operands);
498
499 /// Processes a SPIR-V OpSwitch instruction with the given `operands`.
500 LogicalResult processSwitch(ArrayRef<uint32_t> operands);
501
502 /// Creates block arguments on predecessors previously recorded when handling
503 /// OpPhi instructions.
504 LogicalResult wireUpBlockArgument();
505
506 /// Extracts blocks belonging to a structured selection/loop into a
507 /// spirv.mlir.selection/spirv.mlir.loop op. This method iterates until all
508 /// blocks declared as selection/loop headers are handled.
509 LogicalResult structurizeControlFlow();
510
511 /// Creates a block for graph with the given graphID.
512 LogicalResult createGraphBlock(uint32_t graphID);
513
514 //===--------------------------------------------------------------------===//
515 // Instruction
516 //===--------------------------------------------------------------------===//
517
518 /// Get the Value associated with a result <id>.
519 ///
520 /// This method materializes normal constants and inserts "casting" ops
521 /// (`spirv.mlir.addressof` and `spirv.mlir.referenceof`) to turn an symbol
522 /// into a SSA value for handling uses of module scope constants/variables in
523 /// functions.
524 Value getValue(uint32_t id);
525
526 /// Slices the first instruction out of `binary` and returns its opcode and
527 /// operands via `opcode` and `operands` respectively. Returns failure if
528 /// there is no more remaining instructions (`expectedOpcode` will be used to
529 /// compose the error message) or the next instruction is malformed.
530 LogicalResult
531 sliceInstruction(spirv::Opcode &opcode, ArrayRef<uint32_t> &operands,
532 std::optional<spirv::Opcode> expectedOpcode = std::nullopt);
533
534 /// If `opcode` is a SPV_INTEL_long_composites splittable opcode and the
535 /// next binary instruction(s) are matching `*ContinuedINTEL` ops, consumes
536 /// them and rebinds `operands` to a buffer (held in `mergedStorage`)
537 /// containing the parent + continuation operands concatenated.
538 void
539 mergeLongCompositeContinuations(spirv::Opcode opcode,
540 ArrayRef<uint32_t> &operands,
541 SmallVectorImpl<uint32_t> &mergedStorage);
542
543 /// Processes a SPIR-V instruction with the given `opcode` and `operands`.
544 /// This method is the main entrance for handling SPIR-V instruction; it
545 /// checks the instruction opcode and dispatches to the corresponding handler.
546 /// Processing of Some instructions (like OpEntryPoint and OpExecutionMode)
547 /// might need to be deferred, since they contain forward references to <id>s
548 /// in the deserialized binary, but module in SPIR-V dialect expects these to
549 /// be ssa-uses.
550 LogicalResult processInstruction(spirv::Opcode opcode,
551 ArrayRef<uint32_t> operands,
552 bool deferInstructions = true);
553
554 /// Processes a SPIR-V instruction from the given `operands`. It should
555 /// deserialize into an op with the given `opName` and `numOperands`.
556 /// This method is a generic one for dispatching any SPIR-V ops without
557 /// variadic operands and attributes in TableGen definitions.
559 StringRef opName, bool hasResult,
560 unsigned numOperands);
561
562 /// Processes a OpUndef instruction. Adds a spirv.Undef operation at the
563 /// current insertion point.
564 LogicalResult processUndef(ArrayRef<uint32_t> operands);
565
566 /// Processes an OpConstantFunctionPointerINTEL instruction.
568
569 /// Method to dispatch to the specialized deserialization function for an
570 /// operation in SPIR-V dialect that is a mirror of an instruction in the
571 /// SPIR-V spec. This is auto-generated from ODS. Dispatch is handled for
572 /// all operations in SPIR-V dialect that have hasOpcode == 1.
573 LogicalResult dispatchToAutogenDeserialization(spirv::Opcode opcode,
574 ArrayRef<uint32_t> words);
575
576 /// Processes a SPIR-V OpExtInst with given `operands`. This slices the
577 /// entries of `operands` that specify the extended instruction set <id> and
578 /// the instruction opcode. The op deserializer is then invoked using the
579 /// other entries.
580 LogicalResult processExtInst(ArrayRef<uint32_t> operands);
581
582 /// Processes a SPIR-V OpExtInst with given `operands` for a
583 /// NonSemantic.Graph.DebugInfo instruction.
585 bool deferInstructions);
586
587 /// Dispatches the deserialization of extended instruction set operation based
588 /// on the extended instruction set name, and instruction opcode. This is
589 /// autogenerated from ODS.
590 LogicalResult
592 uint32_t instructionID,
593 ArrayRef<uint32_t> words);
594
595 /// Method to deserialize an operation in the SPIR-V dialect that is a mirror
596 /// of an instruction in the SPIR-V spec. This is auto generated if hasOpcode
597 /// == 1 and autogenSerialization == 1 in ODS.
598 template <typename OpTy>
599 LogicalResult processOp(ArrayRef<uint32_t> words) {
600 return emitError(unknownLoc, "unsupported deserialization for ")
601 << OpTy::getOperationName() << " op";
602 }
603
604private:
605 /// The SPIR-V binary module.
606 ArrayRef<uint32_t> binary;
607
608 /// Contains the data of the OpLine instruction which precedes the current
609 /// processing instruction.
610 std::optional<DebugLine> debugLine;
611
612 /// The current word offset into the binary module.
613 unsigned curOffset = 0;
614
615 /// MLIRContext to create SPIR-V ModuleOp into.
616 MLIRContext *context;
617
618 // TODO: create Location subclass for binary blob
619 Location unknownLoc;
620
621 /// The SPIR-V ModuleOp.
623
624 /// The current function under construction.
625 std::optional<spirv::FuncOp> curFunction;
626
627 /// The current graph under construction.
628 std::optional<spirv::GraphARMOp> curGraph;
629
630 /// The current block under construction.
631 Block *curBlock = nullptr;
632
633 OpBuilder opBuilder;
634
635 spirv::Version version = spirv::Version::V_1_0;
636
637 /// The list of capabilities used by the module.
638 llvm::SmallSetVector<spirv::Capability, 4> capabilities;
639
640 /// The list of extensions used by the module.
641 llvm::SmallSetVector<spirv::Extension, 2> extensions;
642
643 // Result <id> to type mapping.
645
646 // Result <id> to constant attribute and type mapping.
647 ///
648 /// In the SPIR-V binary format, all constants are placed in the module and
649 /// shared by instructions at module level and in subsequent functions. But in
650 /// the SPIR-V dialect, we materialize the constant to where it's used in the
651 /// function. So when seeing a constant instruction in the binary format, we
652 /// don't immediately emit a constant op into the module, we keep its value
653 /// (and type) here. Later when it's used, we materialize the constant.
655
656 // Result <id> to debug location for constants materialized from constantMap.
658
659 // Result <id> to replicated constant attribute and type mapping.
660 ///
661 /// In the SPIR-V binary format, OpConstantCompositeReplicateEXT is placed in
662 /// the module and shared by instructions at module level and in subsequent
663 /// functions. But in the SPIR-V dialect, this is materialized to where
664 /// it's used in the function. So when seeing a
665 /// OpConstantCompositeReplicateEXT in the binary format, we don't immediately
666 /// emit a `spirv.EXT.ConstantCompositeReplicate` op into the module, we keep
667 /// the id of its value and type here. Later when it's used, we materialize
668 /// the `spirv.EXT.ConstantCompositeReplicate`.
669 DenseMap<uint32_t, std::pair<Attribute, Type>> constantCompositeReplicateMap;
670
671 // Result <id> to spec constant mapping.
673
674 // Result <id> to composite spec constant mapping.
676
677 // Result <id> to replicated composite spec constant mapping.
679 specConstCompositeReplicateMap;
680
681 /// Result <id> to info needed to materialize an OpSpecConstantOp
682 /// mapping.
684 specConstOperationMap;
685
686 // Result <id> to GraphConstantARM ID attribute and result type.
688 graphConstantMap;
689
690 // Result <id> to variable mapping.
692
693 // Result <id> to function mapping.
695
696 // Result <id> to function mapping.
698
699 // Result <id> to block mapping.
701
702 // Header block to its merge (and continue) target mapping.
703 BlockMergeInfoMap blockMergeInfo;
704
705 // For each pair of {predecessor, target} blocks, maps the pair of blocks to
706 // the list of phi arguments passed from predecessor to target.
707 DenseMap<std::pair<Block * /*predecessor*/, Block * /*target*/>, BlockPhiInfo>
708 blockPhiInfo;
709
710 // Result <id> to value mapping.
712
713 // Mapping from result <id> to undef value of a type.
715
716 // Mapping from function pointer <id> to its type and function <id>.
717 DenseMap<uint32_t, std::pair<Type, uint32_t>> constantFunctionPointerMap;
718
719 // Composites with OpUndef constituents, built as spirv.CompositeConstruct.
721
722 // Constant and undef ops already materialized in a block of the current
723 // function or graph.
725
726 // Result <id> to name mapping.
728
729 // Result <id> to debug info mapping.
731
732 // Result <id> to decorations mapping.
734
735 // FuncParamAttr decorations awaiting an OpFunctionParameter or OpFunction.
736 // Keeping them separate prevents unsupported targets from acquiring
737 // discardable attributes that would be silently dropped during serialization.
738 DenseMap<uint32_t, ArrayAttr> functionParameterAttrs;
739
740 // Decoration entries from OpDecorateId whose operand <id>s must be resolved
741 // to MLIR symbols after all module ops have been deserialized.
742 struct DeferredIdDecoration {
743 uint32_t targetID;
744 spirv::Decoration decoration;
745 uint32_t operandID;
746 Location loc;
747 };
748 SmallVector<DeferredIdDecoration> pendingIdDecorations;
749
750 // Result <id> to type decorations.
751 DenseMap<uint32_t, uint32_t> typeDecorations;
752
753 // Result <id> to member decorations.
754 // decorated-struct-type-<id> ->
755 // (struct-member-index -> (decoration -> decoration-operands))
756 DenseMap<uint32_t,
758 memberDecorationMap;
759
760 // Result <id> to member name.
761 // struct-type-<id> -> (struct-member-index -> name)
763
764 // Result <id> to extended instruction set name.
765 DenseMap<uint32_t, StringRef> extendedInstSets;
766
767 // List of instructions that are processed in a deferred fashion (after an
768 // initial processing of the entire binary). Some operations like
769 // OpEntryPoint, and OpExecutionMode use forward references to function
770 // <id>s. In SPIR-V dialect the corresponding operations (spirv.EntryPoint and
771 // spirv.ExecutionMode) need these references resolved. So these instructions
772 // are deserialized and stored for processing once the entire binary is
773 // processed.
775 deferredInstructions;
776
777 /// A list of IDs for all types forward-declared through OpTypeForwardPointer
778 /// instructions.
779 SetVector<uint32_t> typeForwardPointerIDs;
780
781 /// A list of all structs which have unresolved member types.
782 SmallVector<DeferredStructTypeInfo, 0> deferredStructTypesInfos;
783
784 /// Deserialization options.
785 DeserializationOptions options;
786
787 /// List of IDs assigned to graph outputs.
788 SmallVector<Value> graphOutputs;
789
790#ifndef NDEBUG
791 /// A logger used to emit information during the deserialzation process.
792 llvm::ScopedPrinter logger;
793#endif
794};
795
796} // namespace spirv
797} // namespace mlir
798
799#endif // MLIR_TARGET_SPIRV_DESERIALIZER_H
static llvm::ManagedStatic< PassManagerOptions > options
Block represents an ordered list of Operations.
Definition Block.h:34
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
This class helps build Operations.
Definition Builders.h:210
This class acts as an owning reference to an op, and will automatically destroy the held op on destru...
Definition OwningOpRef.h:29
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
A SPIR-V module serializer.
LogicalResult wireUpBlockArgument()
Creates block arguments on predecessors previously recorded when handling OpPhi instructions.
Value materializeSpecConstantOperation(uint32_t resultID, spirv::Opcode enclosedOpcode, uint32_t resultTypeID, ArrayRef< uint32_t > enclosedOpOperands)
Materializes/emits an OpSpecConstantOp instruction.
LogicalResult processOpTypePointer(ArrayRef< uint32_t > operands)
Value getValue(uint32_t id)
Get the Value associated with a result <id>.
LogicalResult processMatrixType(ArrayRef< uint32_t > operands)
std::optional< SpecConstOperationMaterializationInfo > getSpecConstantOperation(uint32_t id)
Gets the info needed to materialize the spec constant operation op associated with the given <id>.
LogicalResult dispatchToAutogenDeserialization(spirv::Opcode opcode, ArrayRef< uint32_t > words)
Method to dispatch to the specialized deserialization function for an operation in SPIR-V dialect tha...
LogicalResult processGraphDebugInfoExtInst(ArrayRef< uint32_t > operands, bool deferInstructions)
Processes a SPIR-V OpExtInst with given operands for a NonSemantic.Graph.DebugInfo instruction.
LogicalResult processConstantNull(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpConstantNull instruction with the given operands.
LogicalResult processSpecConstantComposite(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpSpecConstantComposite instruction with the given operands.
LogicalResult processInstruction(spirv::Opcode opcode, ArrayRef< uint32_t > operands, bool deferInstructions=true)
Processes a SPIR-V instruction with the given opcode and operands.
LogicalResult processBranchConditional(ArrayRef< uint32_t > operands)
LogicalResult processGlobalVariable(spirv::Opcode opcode, ArrayRef< uint32_t > operands)
Processes the OpVariable or OpUntypedVariableKHR instructions at current offset into binary.
spirv::GlobalVariableOp getGlobalVariable(uint32_t id)
Gets the global variable associated with a result <id> of OpVariable.
LogicalResult createGraphBlock(uint32_t graphID)
Creates a block for graph with the given graphID.
LogicalResult processStructType(ArrayRef< uint32_t > operands)
LogicalResult processGraphARM(ArrayRef< uint32_t > operands)
LogicalResult processConstantFunctionPointer(ArrayRef< uint32_t > operands)
Processes an OpConstantFunctionPointerINTEL instruction.
LogicalResult processSamplerType(ArrayRef< uint32_t > operands)
LogicalResult setFunctionArgAttrs(uint32_t argID, SmallVectorImpl< Attribute > &argAttrs, size_t argIndex)
Sets the function argument's attributes.
LogicalResult structurizeControlFlow()
Extracts blocks belonging to a structured selection/loop into a spirv.mlir.selection/spirv....
LogicalResult processLabel(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpLabel instruction with the given operands.
LogicalResult processUntypedPointerType(ArrayRef< uint32_t > operands)
Type getType(uint32_t id)
Gets type for a given result <id>.
LogicalResult processSampledImageType(ArrayRef< uint32_t > operands)
LogicalResult processExtInst(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpExtInst with given 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)
spirv::EXTSpecConstantCompositeReplicateOp getSpecConstantCompositeReplicate(uint32_t id)
Gets the replicated composite specialization constant with the given result <id>.
LogicalResult processOp(ArrayRef< uint32_t > words)
Method to deserialize an operation in the SPIR-V dialect that is a mirror of an instruction in the SP...
SmallVector< uint32_t, 2 > BlockPhiInfo
For OpPhi instructions, we use block arguments to represent them.
Type getUndefType(uint32_t id)
Get the type associated with the result <id> of an OpUndef.
LogicalResult processCooperativeMatrixTypeNV(ArrayRef< uint32_t > operands)
LogicalResult processSpecConstantCompositeReplicateEXT(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpSpecConstantCompositeReplicateEXT instruction with the given operands.
LogicalResult processCooperativeMatrixTypeKHR(ArrayRef< uint32_t > operands)
std::pair< Type, uint32_t > getConstantFunctionPointer(uint32_t id)
Gets the type and function <id> of an OpConstantFunctionPointerINTEL.
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 dispatchToExtensionSetAutogenDeserialization(StringRef extensionSetName, uint32_t instructionID, ArrayRef< uint32_t > words)
Dispatches the deserialization of extended instruction set operation based on the extended instructio...
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)
void mergeLongCompositeContinuations(spirv::Opcode opcode, ArrayRef< uint32_t > &operands, SmallVectorImpl< uint32_t > &mergedStorage)
If opcode is a SPV_INTEL_long_composites splittable opcode and the next binary instruction(s) are mat...
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 processOpWithoutGrammarAttr(ArrayRef< uint32_t > words, StringRef opName, bool hasResult, unsigned numOperands)
Processes a SPIR-V instruction from 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 processUndef(ArrayRef< uint32_t > operands)
Processes a OpUndef instruction.
LogicalResult processFunctionEnd(ArrayRef< uint32_t > operands)
Processes OpFunctionEnd and finalizes function.
LogicalResult processRuntimeArrayType(ArrayRef< uint32_t > operands)
LogicalResult processSpecConstantOperation(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpSpecConstantOp instruction with the given operands.
LogicalResult processConstant(ArrayRef< uint32_t > operands, bool isSpec)
Processes a SPIR-V Op{|Spec}Constant instruction with the given operands.
Location createFileLineColLoc(OpBuilder opBuilder)
Creates a FileLineColLoc with the OpLine location information.
LogicalResult processGraphConstantARM(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpGraphConstantARM instruction with the given operands.
LogicalResult processConstantBool(bool isTrue, ArrayRef< uint32_t > operands, bool isSpec)
Processes a SPIR-V Op{|Spec}Constant{True|False} instruction with the given operands.
spirv::SpecConstantOp getSpecConstant(uint32_t id)
Gets the specialization constant with the given result <id>.
LogicalResult processConstantCompositeReplicateEXT(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpConstantCompositeReplicateEXT instruction with the given operands.
LogicalResult processSelectionMerge(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpSelectionMerge instruction with the given operands.
LogicalResult processOpGraphSetOutputARM(ArrayRef< uint32_t > operands)
LogicalResult processDebugLine(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpLine instruction with the given operands.
std::optional< std::pair< Type, SmallVector< uint32_t > > > getUndefComposite(uint32_t id)
Gets the type and constituent <id>s of the undef composite with the given <id>.
LogicalResult splitSelectionHeader()
Move a conditional branch or a switch into a separate basic block to avoid unnecessary sinking of def...
std::string getGraphSymbol(uint32_t id)
Returns a symbol to be used for the graph name with the given result <id>.
SPIR-V struct type.
Definition SPIRVTypes.h:314
OwningOpRef< spirv::ModuleOp > deserialize(ArrayRef< uint32_t > binary, MLIRContext *context, const DeserializationOptions &options={})
Deserializes the given SPIR-V binary module and creates a MLIR ModuleOp in the given context.
llvm::MapVector< Block *, BlockMergeInfo > BlockMergeInfoMap
Map from a selection/loop's header block to its merge (and continue) target.
Include the generated interface declarations.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
llvm::SetVector< T, Vector, Set, N > SetVector
Definition LLVM.h:128
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
BlockMergeInfo(Location location, uint32_t control, Block *m, Block *c=nullptr)
BlockMergeInfo(Location location, uint32_t control)
A struct for containing OpLine instruction information.
A "deferred struct type" is a struct type with one or more member types not known when the Deserializ...
SmallVector< spirv::StructType::StructDecorationInfo, 0 > structDecorationsInfo
SmallVector< spirv::StructType::MemberDecorationInfo, 0 > memberDecorationsInfo
SmallVector< spirv::StructType::OffsetInfo, 0 > offsetInfo
SmallVector< Type, 4 > memberTypes
SmallVector< std::pair< uint32_t, unsigned >, 0 > unresolvedMemberTypes
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.