brintos

brintos / llvm-project-archived public Read only

0
0
Text · 30.4 KiB · 50c9350 Raw
733 lines · c
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-exception6//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_H14#define MLIR_TARGET_SPIRV_DESERIALIZER_H15 16#include "mlir/Dialect/SPIRV/IR/SPIRVEnums.h"17#include "mlir/Dialect/SPIRV/IR/SPIRVOps.h"18#include "mlir/IR/Builders.h"19#include "mlir/Target/SPIRV/Deserialization.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 Definitions32//===----------------------------------------------------------------------===//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 from37/// SPIR-V blob. This info will be used to create38/// spirv.mlir.selection/spirv.mlir.loop later.39struct BlockMergeInfo {40  Block *mergeBlock;41  Block *continueBlock; // nullptr for spirv.mlir.selection42  Location loc;43  uint32_t control; // Selection/loop control44 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.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 pointer62/// key.63using BlockMergeInfoMap = llvm::MapVector<Block *, BlockMergeInfo>;64 65/// A "deferred struct type" is a struct type with one or more member types not66/// known when the Deserializer first encounters the struct. This happens, for67/// example, with recursive structs where a pointer to the struct type is68/// forward declared through OpTypeForwardPointer in the SPIR-V module before69/// the struct declaration; the actual pointer to struct type should be defined70/// 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 Generic80/// %A = OpTypeStruct %APtr81/// %APtr = OpTypePointer Generic %A82///83/// This means that the spirv::StructType cannot be fully constructed directly84/// when the Deserializer encounters it. Instead we create a85/// DeferredStructTypeInfo that contains all the information we know about the86/// spirv::StructType. Once all forward references for the struct are resolved,87/// the struct's body is set with all member info.88struct DeferredStructTypeInfo {89  spirv::StructType deferredStructType;90 91  // A list of all unresolved member types for the struct. First element of each92  // item is operand ID, second element is member index in the struct.93  SmallVector<std::pair<uint32_t, unsigned>, 0> unresolvedMemberTypes;94 95  // The list of member types. For unresolved members, this list contains96  // place-holder empty types that will be updated later.97  SmallVector<Type, 4> memberTypes;98  SmallVector<spirv::StructType::OffsetInfo, 0> offsetInfo;99  SmallVector<spirv::StructType::MemberDecorationInfo, 0> memberDecorationsInfo;100  SmallVector<spirv::StructType::StructDecorationInfo, 0> structDecorationsInfo;101};102 103/// A struct that collects the info needed to materialize/emit a104/// SpecConstantOperation op.105struct SpecConstOperationMaterializationInfo {106  spirv::Opcode enclodesOpcode;107  uint32_t resultTypeID;108  SmallVector<uint32_t> enclosedOpOperands;109};110 111/// A struct that collects the info needed to materialize/emit a112/// GraphConstantARMOp.113struct GraphConstantARMOpMaterializationInfo {114  Type resultType;115  IntegerAttr graphConstantID;116};117 118//===----------------------------------------------------------------------===//119// Deserializer Declaration120//===----------------------------------------------------------------------===//121 122/// A SPIR-V module serializer.123///124/// A SPIR-V binary module is a single linear stream of instructions; each125/// instruction is composed of 32-bit words. The first word of an instruction126/// records the total number of words of that instruction using the 16127/// higher-order bits. So this deserializer uses that to get instruction128/// boundary and parse instructions and build a SPIR-V ModuleOp gradually.129///130// TODO: clean up created ops on errors131class Deserializer {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.142  OwningOpRef<spirv::ModuleOp> collect();143 144private:145  //===--------------------------------------------------------------------===//146  // Module structure147  //===--------------------------------------------------------------------===//148 149  /// Initializes the `module` 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 bookkeeping156  /// in the deserializer.157  LogicalResult processCapability(ArrayRef<uint32_t> operands);158 159  /// Processes the SPIR-V OpExtension with `operands` and updates bookkeeping160  /// in the deserializer.161  LogicalResult processExtension(ArrayRef<uint32_t> words);162 163  /// Processes the SPIR-V OpExtInstImport with `operands` and updates164  /// bookkeeping in the deserializer.165  LogicalResult processExtInstImport(ArrayRef<uint32_t> words);166 167  /// Attaches (version, capabilities, extensions) triple to `module` as an168  /// attribute.169  void attachVCETriple();170 171  /// Processes the SPIR-V OpMemoryModel with `operands` and updates `module`.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  // Processes an OpMemberDecorate instruction.181  LogicalResult processMemberDecoration(ArrayRef<uint32_t> words);182 183  /// Processes an OpMemberName instruction.184  LogicalResult processMemberName(ArrayRef<uint32_t> words);185 186  /// Gets the function op associated with a result <id> of OpFunction.187  spirv::FuncOp getFunction(uint32_t id) { return funcMap.lookup(id); }188 189  /// Processes the SPIR-V function at the current `offset` into `binary`.190  /// The operands to the OpFunction instruction is passed in as ``operands`.191  /// This method processes each instruction inside the function and dispatches192  /// them to their handler method accordingly.193  LogicalResult processFunction(ArrayRef<uint32_t> operands);194 195  /// Processes OpFunctionEnd and finalizes function. This wires up block196  /// argument created from OpPhi instructions and also structurizes control197  /// flow.198  LogicalResult processFunctionEnd(ArrayRef<uint32_t> operands);199 200  /// Gets the constant's attribute and type associated with the given <id>.201  std::optional<std::pair<Attribute, Type>> getConstant(uint32_t id);202 203  /// Gets the replicated composite constant's attribute and type associated204  /// with the given <id>.205  std::optional<std::pair<Attribute, Type>>206  getConstantCompositeReplicate(uint32_t id);207 208  /// Gets the info needed to materialize the spec constant operation op209  /// associated with the given <id>.210  std::optional<SpecConstOperationMaterializationInfo>211  getSpecConstantOperation(uint32_t id);212 213  /// Gets the constant's integer attribute with the given <id>. Returns a214  /// null IntegerAttr if the given is not registered or does not correspond215  /// to an integer constant.216  IntegerAttr getConstantInt(uint32_t id);217 218  /// Returns a symbol to be used for the function name with the given219  /// result <id>. This tries to use the function's OpName if220  /// exists; otherwise creates one based on the <id>.221  std::string getFunctionSymbol(uint32_t id);222 223  /// Returns a symbol to be used for the graph name with the given224  /// result <id>. This tries to use the graph's OpName if225  /// exists; otherwise creates one based on the <id>.226  std::string getGraphSymbol(uint32_t id);227 228  /// Returns a symbol to be used for the specialization constant with the229  /// given result <id>. This tries to use the specialization constant's230  /// OpName if exists; otherwise creates one based on the <id>.231  std::string getSpecConstantSymbol(uint32_t id);232 233  /// Gets the specialization constant with the given result <id>.234  spirv::SpecConstantOp getSpecConstant(uint32_t id) {235    return specConstMap.lookup(id);236  }237 238  /// Gets the composite specialization constant with the given result <id>.239  spirv::SpecConstantCompositeOp getSpecConstantComposite(uint32_t id) {240    return specConstCompositeMap.lookup(id);241  }242 243  /// Gets the replicated composite specialization constant with the given244  /// result <id>.245  spirv::EXTSpecConstantCompositeReplicateOp246  getSpecConstantCompositeReplicate(uint32_t id) {247    return specConstCompositeReplicateMap.lookup(id);248  }249 250  /// Creates a spirv::SpecConstantOp.251  spirv::SpecConstantOp createSpecConstant(Location loc, uint32_t resultID,252                                           TypedAttr defaultValue);253 254  /// Gets the GraphConstantARM ID attribute and result type with the given255  /// result <id>.256  std::optional<spirv::GraphConstantARMOpMaterializationInfo>257  getGraphConstantARM(uint32_t id);258 259  /// Processes the OpVariable instructions at current `offset` into `binary`.260  /// It is expected that this method is used for variables that are to be261  /// defined at module scope and will be deserialized into a262  /// spirv.GlobalVariable instruction.263  LogicalResult processGlobalVariable(ArrayRef<uint32_t> operands);264 265  /// Gets the global variable associated with a result <id> of OpVariable.266  spirv::GlobalVariableOp getGlobalVariable(uint32_t id) {267    return globalVariableMap.lookup(id);268  }269 270  /// Sets the function argument's attributes. |argID| is the function271  /// argument's result <id>, and |argIndex| is its index in the function's272  /// argument list.273  LogicalResult setFunctionArgAttrs(uint32_t argID,274                                    SmallVectorImpl<Attribute> &argAttrs,275                                    size_t argIndex);276 277  /// Gets the symbol name from the name of decoration.278  StringAttr getSymbolDecoration(StringRef decorationName) {279    auto attrName = llvm::convertToSnakeFromCamelCase(decorationName);280    return opBuilder.getStringAttr(attrName);281  }282 283  /// Move a conditional branch or a switch into a separate basic block to avoid284  /// unnecessary sinking of defs that may be required outside a selection285  /// region. This function also ensures that a single block cannot be a header286  /// block of one selection construct and the merge block of another.287  LogicalResult splitSelectionHeader();288 289  //===--------------------------------------------------------------------===//290  // Type291  //===--------------------------------------------------------------------===//292 293  /// Gets type for a given result <id>.294  Type getType(uint32_t id) { return typeMap.lookup(id); }295 296  /// Get the type associated with the result <id> of an OpUndef.297  Type getUndefType(uint32_t id) { return undefMap.lookup(id); }298 299  /// Returns true if the given `type` is for SPIR-V void type.300  bool isVoidType(Type type) const { return isa<NoneType>(type); }301 302  /// Processes a SPIR-V type instruction with given `opcode` and `operands` and303  /// registers the type into `module`.304  LogicalResult processType(spirv::Opcode opcode, ArrayRef<uint32_t> operands);305 306  LogicalResult processOpTypePointer(ArrayRef<uint32_t> operands);307 308  LogicalResult processArrayType(ArrayRef<uint32_t> operands);309 310  LogicalResult processCooperativeMatrixTypeKHR(ArrayRef<uint32_t> operands);311 312  LogicalResult processCooperativeMatrixTypeNV(ArrayRef<uint32_t> operands);313 314  LogicalResult processFunctionType(ArrayRef<uint32_t> operands);315 316  LogicalResult processImageType(ArrayRef<uint32_t> operands);317 318  LogicalResult processSampledImageType(ArrayRef<uint32_t> operands);319 320  LogicalResult processRuntimeArrayType(ArrayRef<uint32_t> operands);321 322  LogicalResult processStructType(ArrayRef<uint32_t> operands);323 324  LogicalResult processMatrixType(ArrayRef<uint32_t> operands);325 326  LogicalResult processTensorARMType(ArrayRef<uint32_t> operands);327 328  LogicalResult processGraphTypeARM(ArrayRef<uint32_t> operands);329 330  LogicalResult processGraphEntryPointARM(ArrayRef<uint32_t> operands);331 332  LogicalResult processGraphARM(ArrayRef<uint32_t> operands);333 334  LogicalResult processOpGraphSetOutputARM(ArrayRef<uint32_t> operands);335 336  LogicalResult processGraphEndARM(ArrayRef<uint32_t> operands);337 338  LogicalResult processTypeForwardPointer(ArrayRef<uint32_t> operands);339 340  //===--------------------------------------------------------------------===//341  // Constant342  //===--------------------------------------------------------------------===//343 344  /// Processes a SPIR-V Op{|Spec}Constant instruction with the given345  /// `operands`. `isSpec` indicates whether this is a specialization constant.346  LogicalResult processConstant(ArrayRef<uint32_t> operands, bool isSpec);347 348  /// Processes a SPIR-V Op{|Spec}Constant{True|False} instruction with the349  /// given `operands`. `isSpec` indicates whether this is a specialization350  /// constant.351  LogicalResult processConstantBool(bool isTrue, ArrayRef<uint32_t> operands,352                                    bool isSpec);353 354  /// Processes a SPIR-V OpConstantComposite instruction with the given355  /// `operands`.356  LogicalResult processConstantComposite(ArrayRef<uint32_t> operands);357 358  /// Processes a SPIR-V OpConstantCompositeReplicateEXT instruction with359  /// the given `operands`.360  LogicalResult361  processConstantCompositeReplicateEXT(ArrayRef<uint32_t> operands);362 363  /// Processes a SPIR-V OpSpecConstantComposite instruction with the given364  /// `operands`.365  LogicalResult processSpecConstantComposite(ArrayRef<uint32_t> operands);366 367  /// Processes a SPIR-V OpSpecConstantCompositeReplicateEXT instruction with368  /// the given `operands`.369  LogicalResult370  processSpecConstantCompositeReplicateEXT(ArrayRef<uint32_t> operands);371 372  /// Processes a SPIR-V OpSpecConstantOp instruction with the given373  /// `operands`.374  LogicalResult processSpecConstantOperation(ArrayRef<uint32_t> operands);375 376  /// Materializes/emits an OpSpecConstantOp instruction.377  Value materializeSpecConstantOperation(uint32_t resultID,378                                         spirv::Opcode enclosedOpcode,379                                         uint32_t resultTypeID,380                                         ArrayRef<uint32_t> enclosedOpOperands);381 382  /// Processes a SPIR-V OpConstantNull instruction with the given `operands`.383  LogicalResult processConstantNull(ArrayRef<uint32_t> operands);384 385  /// Processes a SPIR-V OpGraphConstantARM instruction with the given386  /// `operands`.387  LogicalResult processGraphConstantARM(ArrayRef<uint32_t> operands);388 389  //===--------------------------------------------------------------------===//390  // Debug391  //===--------------------------------------------------------------------===//392 393  /// Discontinues any source-level location information that might be active394  /// from a previous OpLine instruction.395  void clearDebugLine();396 397  /// Creates a FileLineColLoc with the OpLine location information.398  Location createFileLineColLoc(OpBuilder opBuilder);399 400  /// Processes a SPIR-V OpLine instruction with the given `operands`.401  LogicalResult processDebugLine(ArrayRef<uint32_t> operands);402 403  /// Processes a SPIR-V OpString instruction with the given `operands`.404  LogicalResult processDebugString(ArrayRef<uint32_t> operands);405 406  //===--------------------------------------------------------------------===//407  // Control flow408  //===--------------------------------------------------------------------===//409 410  /// Returns the block for the given label <id>.411  Block *getBlock(uint32_t id) const { return blockMap.lookup(id); }412 413  // In SPIR-V, structured control flow is explicitly declared using merge414  // instructions (OpSelectionMerge and OpLoopMerge). In the SPIR-V dialect,415  // we use spirv.mlir.selection and spirv.mlir.loop to group structured control416  // flow. The deserializer need to turn structured control flow marked with417  // merge instructions into using spirv.mlir.selection/spirv.mlir.loop ops.418  //419  // Because structured control flow can nest and the basic block order have420  // flexibility, we cannot isolate a structured selection/loop without421  // deserializing all the blocks. So we use the following approach:422  //423  // 1. Deserialize all basic blocks in a function and create MLIR blocks for424  //    them into the function's region. In the meanwhile, keep a map between425  //    selection/loop header blocks to their corresponding merge (and continue)426  //    target blocks.427  // 2. For each selection/loop header block, recursively get all basic blocks428  //    reachable (except the merge block) and put them in a newly created429  //    spirv.mlir.selection/spirv.mlir.loop's region. Structured control flow430  //    guarantees that we enter and exit in structured ways and the construct431  //    is nestable.432  // 3. Put the new spirv.mlir.selection/spirv.mlir.loop op at the beginning of433  // the434  //    old merge block and redirect all branches to the old header block to the435  //    old merge block (which contains the spirv.mlir.selection/spirv.mlir.loop436  //    op now).437 438  /// For OpPhi instructions, we use block arguments to represent them. OpPhi439  /// encodes a list of (value, predecessor) pairs. At the time of handling the440  /// block containing an OpPhi instruction, the predecessor block might not be441  /// processed yet, also the value sent by it. So we need to defer handling442  /// the block argument from the predecessors. We use the following approach:443  ///444  /// 1. For each OpPhi instruction, add a block argument to the current block445  ///    in construction. Record the block argument in `valueMap` so its uses446  ///    can be resolved. For the list of (value, predecessor) pairs, update447  ///    `blockPhiInfo` for bookkeeping.448  /// 2. After processing all blocks, loop over `blockPhiInfo` to fix up each449  ///    block recorded there to create the proper block arguments on their450  ///    terminators.451 452  /// A data structure for containing a SPIR-V block's phi info. It will be453  /// represented as block argument in SPIR-V dialect.454  using BlockPhiInfo =455      SmallVector<uint32_t, 2>; // The result <id> of the values sent456 457  /// Gets or creates the block corresponding to the given label <id>. The newly458  /// created block will always be placed at the end of the current function.459  Block *getOrCreateBlock(uint32_t id);460 461  LogicalResult processBranch(ArrayRef<uint32_t> operands);462 463  LogicalResult processBranchConditional(ArrayRef<uint32_t> operands);464 465  /// Processes a SPIR-V OpLabel instruction with the given `operands`.466  LogicalResult processLabel(ArrayRef<uint32_t> operands);467 468  /// Processes a SPIR-V OpSelectionMerge instruction with the given `operands`.469  LogicalResult processSelectionMerge(ArrayRef<uint32_t> operands);470 471  /// Processes a SPIR-V OpLoopMerge instruction with the given `operands`.472  LogicalResult processLoopMerge(ArrayRef<uint32_t> operands);473 474  /// Processes a SPIR-V OpPhi instruction with the given `operands`.475  LogicalResult processPhi(ArrayRef<uint32_t> operands);476 477  /// Processes a SPIR-V OpSwitch instruction with the given `operands`.478  LogicalResult processSwitch(ArrayRef<uint32_t> operands);479 480  /// Creates block arguments on predecessors previously recorded when handling481  /// OpPhi instructions.482  LogicalResult wireUpBlockArgument();483 484  /// Extracts blocks belonging to a structured selection/loop into a485  /// spirv.mlir.selection/spirv.mlir.loop op. This method iterates until all486  /// blocks declared as selection/loop headers are handled.487  LogicalResult structurizeControlFlow();488 489  /// Creates a block for graph with the given graphID.490  LogicalResult createGraphBlock(uint32_t graphID);491 492  //===--------------------------------------------------------------------===//493  // Instruction494  //===--------------------------------------------------------------------===//495 496  /// Get the Value associated with a result <id>.497  ///498  /// This method materializes normal constants and inserts "casting" ops499  /// (`spirv.mlir.addressof` and `spirv.mlir.referenceof`) to turn an symbol500  /// into a SSA value for handling uses of module scope constants/variables in501  /// functions.502  Value getValue(uint32_t id);503 504  /// Slices the first instruction out of `binary` and returns its opcode and505  /// operands via `opcode` and `operands` respectively. Returns failure if506  /// there is no more remaining instructions (`expectedOpcode` will be used to507  /// compose the error message) or the next instruction is malformed.508  LogicalResult509  sliceInstruction(spirv::Opcode &opcode, ArrayRef<uint32_t> &operands,510                   std::optional<spirv::Opcode> expectedOpcode = std::nullopt);511 512  /// Processes a SPIR-V instruction with the given `opcode` and `operands`.513  /// This method is the main entrance for handling SPIR-V instruction; it514  /// checks the instruction opcode and dispatches to the corresponding handler.515  /// Processing of Some instructions (like OpEntryPoint and OpExecutionMode)516  /// might need to be deferred, since they contain forward references to <id>s517  /// in the deserialized binary, but module in SPIR-V dialect expects these to518  /// be ssa-uses.519  LogicalResult processInstruction(spirv::Opcode opcode,520                                   ArrayRef<uint32_t> operands,521                                   bool deferInstructions = true);522 523  /// Processes a SPIR-V instruction from the given `operands`. It should524  /// deserialize into an op with the given `opName` and `numOperands`.525  /// This method is a generic one for dispatching any SPIR-V ops without526  /// variadic operands and attributes in TableGen definitions.527  LogicalResult processOpWithoutGrammarAttr(ArrayRef<uint32_t> words,528                                            StringRef opName, bool hasResult,529                                            unsigned numOperands);530 531  /// Processes a OpUndef instruction. Adds a spirv.Undef operation at the532  /// current insertion point.533  LogicalResult processUndef(ArrayRef<uint32_t> operands);534 535  /// Method to dispatch to the specialized deserialization function for an536  /// operation in SPIR-V dialect that is a mirror of an instruction in the537  /// SPIR-V spec. This is auto-generated from ODS. Dispatch is handled for538  /// all operations in SPIR-V dialect that have hasOpcode == 1.539  LogicalResult dispatchToAutogenDeserialization(spirv::Opcode opcode,540                                                 ArrayRef<uint32_t> words);541 542  /// Processes a SPIR-V OpExtInst with given `operands`. This slices the543  /// entries of `operands` that specify the extended instruction set <id> and544  /// the instruction opcode. The op deserializer is then invoked using the545  /// other entries.546  LogicalResult processExtInst(ArrayRef<uint32_t> operands);547 548  /// Dispatches the deserialization of extended instruction set operation based549  /// on the extended instruction set name, and instruction opcode. This is550  /// autogenerated from ODS.551  LogicalResult552  dispatchToExtensionSetAutogenDeserialization(StringRef extensionSetName,553                                               uint32_t instructionID,554                                               ArrayRef<uint32_t> words);555 556  /// Method to deserialize an operation in the SPIR-V dialect that is a mirror557  /// of an instruction in the SPIR-V spec. This is auto generated if hasOpcode558  /// == 1 and autogenSerialization == 1 in ODS.559  template <typename OpTy>560  LogicalResult processOp(ArrayRef<uint32_t> words) {561    return emitError(unknownLoc, "unsupported deserialization for ")562           << OpTy::getOperationName() << " op";563  }564 565private:566  /// The SPIR-V binary module.567  ArrayRef<uint32_t> binary;568 569  /// Contains the data of the OpLine instruction which precedes the current570  /// processing instruction.571  std::optional<DebugLine> debugLine;572 573  /// The current word offset into the binary module.574  unsigned curOffset = 0;575 576  /// MLIRContext to create SPIR-V ModuleOp into.577  MLIRContext *context;578 579  // TODO: create Location subclass for binary blob580  Location unknownLoc;581 582  /// The SPIR-V ModuleOp.583  OwningOpRef<spirv::ModuleOp> module;584 585  /// The current function under construction.586  std::optional<spirv::FuncOp> curFunction;587 588  /// The current graph under construction.589  std::optional<spirv::GraphARMOp> curGraph;590 591  /// The current block under construction.592  Block *curBlock = nullptr;593 594  OpBuilder opBuilder;595 596  spirv::Version version = spirv::Version::V_1_0;597 598  /// The list of capabilities used by the module.599  llvm::SmallSetVector<spirv::Capability, 4> capabilities;600 601  /// The list of extensions used by the module.602  llvm::SmallSetVector<spirv::Extension, 2> extensions;603 604  // Result <id> to type mapping.605  DenseMap<uint32_t, Type> typeMap;606 607  // Result <id> to constant attribute and type mapping.608  ///609  /// In the SPIR-V binary format, all constants are placed in the module and610  /// shared by instructions at module level and in subsequent functions. But in611  /// the SPIR-V dialect, we materialize the constant to where it's used in the612  /// function. So when seeing a constant instruction in the binary format, we613  /// don't immediately emit a constant op into the module, we keep its value614  /// (and type) here. Later when it's used, we materialize the constant.615  DenseMap<uint32_t, std::pair<Attribute, Type>> constantMap;616 617  // Result <id> to replicated constant attribute and type mapping.618  ///619  /// In the SPIR-V binary format, OpConstantCompositeReplicateEXT is placed in620  /// the module and shared by instructions at module level and in subsequent621  /// functions. But in the SPIR-V dialect, this is materialized to where622  /// it's used in the function. So when seeing a623  /// OpConstantCompositeReplicateEXT in the binary format, we don't immediately624  /// emit a `spirv.EXT.ConstantCompositeReplicate` op into the module, we keep625  /// the id of its value and type here. Later when it's used, we materialize626  /// the `spirv.EXT.ConstantCompositeReplicate`.627  DenseMap<uint32_t, std::pair<Attribute, Type>> constantCompositeReplicateMap;628 629  // Result <id> to spec constant mapping.630  DenseMap<uint32_t, spirv::SpecConstantOp> specConstMap;631 632  // Result <id> to composite spec constant mapping.633  DenseMap<uint32_t, spirv::SpecConstantCompositeOp> specConstCompositeMap;634 635  // Result <id> to replicated composite spec constant mapping.636  DenseMap<uint32_t, spirv::EXTSpecConstantCompositeReplicateOp>637      specConstCompositeReplicateMap;638 639  /// Result <id> to info needed to materialize an OpSpecConstantOp640  /// mapping.641  DenseMap<uint32_t, SpecConstOperationMaterializationInfo>642      specConstOperationMap;643 644  // Result <id> to GraphConstantARM ID attribute and result type.645  DenseMap<uint32_t, spirv::GraphConstantARMOpMaterializationInfo>646      graphConstantMap;647 648  // Result <id> to variable mapping.649  DenseMap<uint32_t, spirv::GlobalVariableOp> globalVariableMap;650 651  // Result <id> to function mapping.652  DenseMap<uint32_t, spirv::FuncOp> funcMap;653 654  // Result <id> to function mapping.655  DenseMap<uint32_t, spirv::GraphARMOp> graphMap;656 657  // Result <id> to block mapping.658  DenseMap<uint32_t, Block *> blockMap;659 660  // Header block to its merge (and continue) target mapping.661  BlockMergeInfoMap blockMergeInfo;662 663  // For each pair of {predecessor, target} blocks, maps the pair of blocks to664  // the list of phi arguments passed from predecessor to target.665  DenseMap<std::pair<Block * /*predecessor*/, Block * /*target*/>, BlockPhiInfo>666      blockPhiInfo;667 668  // Result <id> to value mapping.669  DenseMap<uint32_t, Value> valueMap;670 671  // Mapping from result <id> to undef value of a type.672  DenseMap<uint32_t, Type> undefMap;673 674  // Result <id> to name mapping.675  DenseMap<uint32_t, StringRef> nameMap;676 677  // Result <id> to debug info mapping.678  DenseMap<uint32_t, StringRef> debugInfoMap;679 680  // Result <id> to decorations mapping.681  DenseMap<uint32_t, NamedAttrList> decorations;682 683  // Result <id> to type decorations.684  DenseMap<uint32_t, uint32_t> typeDecorations;685 686  // Result <id> to member decorations.687  // decorated-struct-type-<id> ->688  //    (struct-member-index -> (decoration -> decoration-operands))689  DenseMap<uint32_t,690           DenseMap<uint32_t, DenseMap<spirv::Decoration, ArrayRef<uint32_t>>>>691      memberDecorationMap;692 693  // Result <id> to member name.694  // struct-type-<id> -> (struct-member-index -> name)695  DenseMap<uint32_t, DenseMap<uint32_t, StringRef>> memberNameMap;696 697  // Result <id> to extended instruction set name.698  DenseMap<uint32_t, StringRef> extendedInstSets;699 700  // List of instructions that are processed in a deferred fashion (after an701  // initial processing of the entire binary). Some operations like702  // OpEntryPoint, and OpExecutionMode use forward references to function703  // <id>s. In SPIR-V dialect the corresponding operations (spirv.EntryPoint and704  // spirv.ExecutionMode) need these references resolved. So these instructions705  // are deserialized and stored for processing once the entire binary is706  // processed.707  SmallVector<std::pair<spirv::Opcode, ArrayRef<uint32_t>>, 4>708      deferredInstructions;709 710  /// A list of IDs for all types forward-declared through OpTypeForwardPointer711  /// instructions.712  SetVector<uint32_t> typeForwardPointerIDs;713 714  /// A list of all structs which have unresolved member types.715  SmallVector<DeferredStructTypeInfo, 0> deferredStructTypesInfos;716 717  /// Deserialization options.718  DeserializationOptions options;719 720  /// List of IDs assigned to graph outputs.721  SmallVector<Value> graphOutputs;722 723#ifndef NDEBUG724  /// A logger used to emit information during the deserialzation process.725  llvm::ScopedPrinter logger;726#endif727};728 729} // namespace spirv730} // namespace mlir731 732#endif // MLIR_TARGET_SPIRV_DESERIALIZER_H733