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