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