1 //===- Serializer.h - MLIR SPIR-V Serializer ------------------------------===// 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 MLIR SPIR-V module to SPIR-V binary serializer. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef MLIR_LIB_TARGET_SPIRV_SERIALIZATION_SERIALIZER_H 14 #define MLIR_LIB_TARGET_SPIRV_SERIALIZATION_SERIALIZER_H 15 16 #include "mlir/Dialect/SPIRV/IR/SPIRVOps.h" 17 #include "mlir/IR/Builders.h" 18 #include "llvm/ADT/SetVector.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/Support/raw_ostream.h" 21 22 namespace mlir { 23 namespace spirv { 24 25 LogicalResult encodeInstructionInto(SmallVectorImpl<uint32_t> &binary, 26 spirv::Opcode op, 27 ArrayRef<uint32_t> operands); 28 29 /// A SPIR-V module serializer. 30 /// 31 /// A SPIR-V binary module is a single linear stream of instructions; each 32 /// instruction is composed of 32-bit words with the layout: 33 /// 34 /// | <word-count>|<opcode> | <operand> | <operand> | ... | 35 /// | <------ word -------> | <-- word --> | <-- word --> | ... | 36 /// 37 /// For the first word, the 16 high-order bits are the word count of the 38 /// instruction, the 16 low-order bits are the opcode enumerant. The 39 /// instructions then belong to different sections, which must be laid out in 40 /// the particular order as specified in "2.4 Logical Layout of a Module" of 41 /// the SPIR-V spec. 42 class Serializer { 43 public: 44 /// Creates a serializer for the given SPIR-V `module`. 45 explicit Serializer(spirv::ModuleOp module, bool emitDebugInfo = false); 46 47 /// Serializes the remembered SPIR-V module. 48 LogicalResult serialize(); 49 50 /// Collects the final SPIR-V `binary`. 51 void collect(SmallVectorImpl<uint32_t> &binary); 52 53 #ifndef NDEBUG 54 /// (For debugging) prints each value and its corresponding result <id>. 55 void printValueIDMap(raw_ostream &os); 56 #endif 57 58 private: 59 // Note that there are two main categories of methods in this class: 60 // * process*() methods are meant to fully serialize a SPIR-V module entity 61 // (header, type, op, etc.). They update internal vectors containing 62 // different binary sections. They are not meant to be called except the 63 // top-level serialization loop. 64 // * prepare*() methods are meant to be helpers that prepare for serializing 65 // certain entity. They may or may not update internal vectors containing 66 // different binary sections. They are meant to be called among themselves 67 // or by other process*() methods for subtasks. 68 69 //===--------------------------------------------------------------------===// 70 // <id> 71 //===--------------------------------------------------------------------===// 72 73 // Note that it is illegal to use id <0> in SPIR-V binary module. Various 74 // methods in this class, if using SPIR-V word (uint32_t) as interface, 75 // check or return id <0> to indicate error in processing. 76 77 /// Consumes the next unused <id>. This method will never return 0. 78 uint32_t getNextID() { return nextID++; } 79 80 //===--------------------------------------------------------------------===// 81 // Module structure 82 //===--------------------------------------------------------------------===// 83 84 uint32_t getSpecConstID(StringRef constName) const { 85 return specConstIDMap.lookup(constName); 86 } 87 88 uint32_t getVariableID(StringRef varName) const { 89 return globalVarIDMap.lookup(varName); 90 } 91 92 uint32_t getFunctionID(StringRef fnName) const { 93 return funcIDMap.lookup(fnName); 94 } 95 96 /// Gets the <id> for the function with the given name. Assigns the next 97 /// available <id> if the function haven't been deserialized. 98 uint32_t getOrCreateFunctionID(StringRef fnName); 99 100 void processCapability(); 101 102 void processDebugInfo(); 103 104 void processExtension(); 105 106 void processMemoryModel(); 107 108 LogicalResult processConstantOp(spirv::ConstantOp op); 109 110 LogicalResult processSpecConstantOp(spirv::SpecConstantOp op); 111 112 LogicalResult 113 processSpecConstantCompositeOp(spirv::SpecConstantCompositeOp op); 114 115 LogicalResult 116 processSpecConstantOperationOp(spirv::SpecConstantOperationOp op); 117 118 /// SPIR-V dialect supports OpUndef using spv.UndefOp that produces a SSA 119 /// value to use with other operations. The SPIR-V spec recommends that 120 /// OpUndef be generated at module level. The serialization generates an 121 /// OpUndef for each type needed at module level. 122 LogicalResult processUndefOp(spirv::UndefOp op); 123 124 /// Emit OpName for the given `resultID`. 125 LogicalResult processName(uint32_t resultID, StringRef name); 126 127 /// Processes a SPIR-V function op. 128 LogicalResult processFuncOp(spirv::FuncOp op); 129 130 LogicalResult processVariableOp(spirv::VariableOp op); 131 132 /// Process a SPIR-V GlobalVariableOp 133 LogicalResult processGlobalVariableOp(spirv::GlobalVariableOp varOp); 134 135 /// Process attributes that translate to decorations on the result <id> 136 LogicalResult processDecoration(Location loc, uint32_t resultID, 137 NamedAttribute attr); 138 139 template <typename DType> 140 LogicalResult processTypeDecoration(Location loc, DType type, 141 uint32_t resultId) { 142 return emitError(loc, "unhandled decoration for type:") << type; 143 } 144 145 /// Process member decoration 146 LogicalResult processMemberDecoration( 147 uint32_t structID, 148 const spirv::StructType::MemberDecorationInfo &memberDecorationInfo); 149 150 //===--------------------------------------------------------------------===// 151 // Types 152 //===--------------------------------------------------------------------===// 153 154 uint32_t getTypeID(Type type) const { return typeIDMap.lookup(type); } 155 156 Type getVoidType() { return mlirBuilder.getNoneType(); } 157 158 bool isVoidType(Type type) const { return type.isa<NoneType>(); } 159 160 /// Returns true if the given type is a pointer type to a struct in some 161 /// interface storage class. 162 bool isInterfaceStructPtrType(Type type) const; 163 164 /// Main dispatch method for serializing a type. The result <id> of the 165 /// serialized type will be returned as `typeID`. 166 LogicalResult processType(Location loc, Type type, uint32_t &typeID); 167 LogicalResult processTypeImpl(Location loc, Type type, uint32_t &typeID, 168 SetVector<StringRef> &serializationCtx); 169 170 /// Method for preparing basic SPIR-V type serialization. Returns the type's 171 /// opcode and operands for the instruction via `typeEnum` and `operands`. 172 LogicalResult prepareBasicType(Location loc, Type type, uint32_t resultID, 173 spirv::Opcode &typeEnum, 174 SmallVectorImpl<uint32_t> &operands, 175 bool &deferSerialization, 176 SetVector<StringRef> &serializationCtx); 177 178 LogicalResult prepareFunctionType(Location loc, FunctionType type, 179 spirv::Opcode &typeEnum, 180 SmallVectorImpl<uint32_t> &operands); 181 182 //===--------------------------------------------------------------------===// 183 // Constant 184 //===--------------------------------------------------------------------===// 185 186 uint32_t getConstantID(Attribute value) const { 187 return constIDMap.lookup(value); 188 } 189 190 /// Main dispatch method for processing a constant with the given `constType` 191 /// and `valueAttr`. `constType` is needed here because we can interpret the 192 /// `valueAttr` as a different type than the type of `valueAttr` itself; for 193 /// example, ArrayAttr, whose type is NoneType, is used for spirv::ArrayType 194 /// constants. 195 uint32_t prepareConstant(Location loc, Type constType, Attribute valueAttr); 196 197 /// Prepares array attribute serialization. This method emits corresponding 198 /// OpConstant* and returns the result <id> associated with it. Returns 0 if 199 /// failed. 200 uint32_t prepareArrayConstant(Location loc, Type constType, ArrayAttr attr); 201 202 /// Prepares bool/int/float DenseElementsAttr serialization. This method 203 /// iterates the DenseElementsAttr to construct the constant array, and 204 /// returns the result <id> associated with it. Returns 0 if failed. Note 205 /// that the size of `index` must match the rank. 206 /// TODO: Consider to enhance splat elements cases. For splat cases, 207 /// we don't need to loop over all elements, especially when the splat value 208 /// is zero. We can use OpConstantNull when the value is zero. 209 uint32_t prepareDenseElementsConstant(Location loc, Type constType, 210 DenseElementsAttr valueAttr, int dim, 211 MutableArrayRef<uint64_t> index); 212 213 /// Prepares scalar attribute serialization. This method emits corresponding 214 /// OpConstant* and returns the result <id> associated with it. Returns 0 if 215 /// the attribute is not for a scalar bool/integer/float value. If `isSpec` is 216 /// true, then the constant will be serialized as a specialization constant. 217 uint32_t prepareConstantScalar(Location loc, Attribute valueAttr, 218 bool isSpec = false); 219 220 uint32_t prepareConstantBool(Location loc, BoolAttr boolAttr, 221 bool isSpec = false); 222 223 uint32_t prepareConstantInt(Location loc, IntegerAttr intAttr, 224 bool isSpec = false); 225 226 uint32_t prepareConstantFp(Location loc, FloatAttr floatAttr, 227 bool isSpec = false); 228 229 //===--------------------------------------------------------------------===// 230 // Control flow 231 //===--------------------------------------------------------------------===// 232 233 /// Returns the result <id> for the given block. 234 uint32_t getBlockID(Block *block) const { return blockIDMap.lookup(block); } 235 236 /// Returns the result <id> for the given block. If no <id> has been assigned, 237 /// assigns the next available <id> 238 uint32_t getOrCreateBlockID(Block *block); 239 240 /// Processes the given `block` and emits SPIR-V instructions for all ops 241 /// inside. Does not emit OpLabel for this block if `omitLabel` is true. 242 /// `actionBeforeTerminator` is a callback that will be invoked before 243 /// handling the terminator op. It can be used to inject the Op*Merge 244 /// instruction if this is a SPIR-V selection/loop header block. 245 LogicalResult 246 processBlock(Block *block, bool omitLabel = false, 247 function_ref<void()> actionBeforeTerminator = nullptr); 248 249 /// Emits OpPhi instructions for the given block if it has block arguments. 250 LogicalResult emitPhiForBlockArguments(Block *block); 251 252 LogicalResult processSelectionOp(spirv::SelectionOp selectionOp); 253 254 LogicalResult processLoopOp(spirv::LoopOp loopOp); 255 256 LogicalResult processBranchConditionalOp(spirv::BranchConditionalOp); 257 258 LogicalResult processBranchOp(spirv::BranchOp branchOp); 259 260 //===--------------------------------------------------------------------===// 261 // Operations 262 //===--------------------------------------------------------------------===// 263 264 LogicalResult encodeExtensionInstruction(Operation *op, 265 StringRef extensionSetName, 266 uint32_t opcode, 267 ArrayRef<uint32_t> operands); 268 269 uint32_t getValueID(Value val) const { return valueIDMap.lookup(val); } 270 271 LogicalResult processAddressOfOp(spirv::AddressOfOp addressOfOp); 272 273 LogicalResult processReferenceOfOp(spirv::ReferenceOfOp referenceOfOp); 274 275 /// Main dispatch method for serializing an operation. 276 LogicalResult processOperation(Operation *op); 277 278 /// Serializes an operation `op` as core instruction with `opcode` if 279 /// `extInstSet` is empty. Otherwise serializes it as an extended instruction 280 /// with `opcode` from `extInstSet`. 281 /// This method is a generic one for dispatching any SPIR-V ops that has no 282 /// variadic operands and attributes in TableGen definitions. 283 LogicalResult processOpWithoutGrammarAttr(Operation *op, StringRef extInstSet, 284 uint32_t opcode); 285 286 /// Dispatches to the serialization function for an operation in SPIR-V 287 /// dialect that is a mirror of an instruction in the SPIR-V spec. This is 288 /// auto-generated from ODS. Dispatch is handled for all operations in SPIR-V 289 /// dialect that have hasOpcode == 1. 290 LogicalResult dispatchToAutogenSerialization(Operation *op); 291 292 /// Serializes an operation in the SPIR-V dialect that is a mirror of an 293 /// instruction in the SPIR-V spec. This is auto generated if hasOpcode == 1 294 /// and autogenSerialization == 1 in ODS. 295 template <typename OpTy> LogicalResult processOp(OpTy op) { 296 return op.emitError("unsupported op serialization"); 297 } 298 299 //===--------------------------------------------------------------------===// 300 // Utilities 301 //===--------------------------------------------------------------------===// 302 303 /// Emits an OpDecorate instruction to decorate the given `target` with the 304 /// given `decoration`. 305 LogicalResult emitDecoration(uint32_t target, spirv::Decoration decoration, 306 ArrayRef<uint32_t> params = {}); 307 308 /// Emits an OpLine instruction with the given `loc` location information into 309 /// the given `binary` vector. 310 LogicalResult emitDebugLine(SmallVectorImpl<uint32_t> &binary, Location loc); 311 312 private: 313 /// The SPIR-V module to be serialized. 314 spirv::ModuleOp module; 315 316 /// An MLIR builder for getting MLIR constructs. 317 mlir::Builder mlirBuilder; 318 319 /// A flag which indicates if the debuginfo should be emitted. 320 bool emitDebugInfo = false; 321 322 /// A flag which indicates if the last processed instruction was a merge 323 /// instruction. 324 /// According to SPIR-V spec: "If a branch merge instruction is used, the last 325 /// OpLine in the block must be before its merge instruction". 326 bool lastProcessedWasMergeInst = false; 327 328 /// The <id> of the OpString instruction, which specifies a file name, for 329 /// use by other debug instructions. 330 uint32_t fileID = 0; 331 332 /// The next available result <id>. 333 uint32_t nextID = 1; 334 335 // The following are for different SPIR-V instruction sections. They follow 336 // the logical layout of a SPIR-V module. 337 338 SmallVector<uint32_t, 4> capabilities; 339 SmallVector<uint32_t, 0> extensions; 340 SmallVector<uint32_t, 0> extendedSets; 341 SmallVector<uint32_t, 3> memoryModel; 342 SmallVector<uint32_t, 0> entryPoints; 343 SmallVector<uint32_t, 4> executionModes; 344 SmallVector<uint32_t, 0> debug; 345 SmallVector<uint32_t, 0> names; 346 SmallVector<uint32_t, 0> decorations; 347 SmallVector<uint32_t, 0> typesGlobalValues; 348 SmallVector<uint32_t, 0> functions; 349 350 /// Recursive struct references are serialized as OpTypePointer instructions 351 /// to the recursive struct type. However, the OpTypePointer instruction 352 /// cannot be emitted before the recursive struct's OpTypeStruct. 353 /// RecursiveStructPointerInfo stores the data needed to emit such 354 /// OpTypePointer instructions after forward references to such types. 355 struct RecursiveStructPointerInfo { 356 uint32_t pointerTypeID; 357 spirv::StorageClass storageClass; 358 }; 359 360 // Maps spirv::StructType to its recursive reference member info. 361 DenseMap<Type, SmallVector<RecursiveStructPointerInfo, 0>> 362 recursiveStructInfos; 363 364 /// `functionHeader` contains all the instructions that must be in the first 365 /// block in the function, and `functionBody` contains the rest. After 366 /// processing FuncOp, the encoded instructions of a function are appended to 367 /// `functions`. An example of instructions in `functionHeader` in order: 368 /// OpFunction ... 369 /// OpFunctionParameter ... 370 /// OpFunctionParameter ... 371 /// OpLabel ... 372 /// OpVariable ... 373 /// OpVariable ... 374 SmallVector<uint32_t, 0> functionHeader; 375 SmallVector<uint32_t, 0> functionBody; 376 377 /// Map from type used in SPIR-V module to their <id>s. 378 DenseMap<Type, uint32_t> typeIDMap; 379 380 /// Map from constant values to their <id>s. 381 DenseMap<Attribute, uint32_t> constIDMap; 382 383 /// Map from specialization constant names to their <id>s. 384 llvm::StringMap<uint32_t> specConstIDMap; 385 386 /// Map from GlobalVariableOps name to <id>s. 387 llvm::StringMap<uint32_t> globalVarIDMap; 388 389 /// Map from FuncOps name to <id>s. 390 llvm::StringMap<uint32_t> funcIDMap; 391 392 /// Map from blocks to their <id>s. 393 DenseMap<Block *, uint32_t> blockIDMap; 394 395 /// Map from the Type to the <id> that represents undef value of that type. 396 DenseMap<Type, uint32_t> undefValIDMap; 397 398 /// Map from results of normal operations to their <id>s. 399 DenseMap<Value, uint32_t> valueIDMap; 400 401 /// Map from extended instruction set name to <id>s. 402 llvm::StringMap<uint32_t> extendedInstSetIDMap; 403 404 /// Map from values used in OpPhi instructions to their offset in the 405 /// `functions` section. 406 /// 407 /// When processing a block with arguments, we need to emit OpPhi 408 /// instructions to record the predecessor block <id>s and the values they 409 /// send to the block in question. But it's not guaranteed all values are 410 /// visited and thus assigned result <id>s. So we need this list to capture 411 /// the offsets into `functions` where a value is used so that we can fix it 412 /// up later after processing all the blocks in a function. 413 /// 414 /// More concretely, say if we are visiting the following blocks: 415 /// 416 /// ```mlir 417 /// ^phi(%arg0: i32): 418 /// ... 419 /// ^parent1: 420 /// ... 421 /// spv.Branch ^phi(%val0: i32) 422 /// ^parent2: 423 /// ... 424 /// spv.Branch ^phi(%val1: i32) 425 /// ``` 426 /// 427 /// When we are serializing the `^phi` block, we need to emit at the beginning 428 /// of the block OpPhi instructions which has the following parameters: 429 /// 430 /// OpPhi id-for-i32 id-for-%arg0 id-for-%val0 id-for-^parent1 431 /// id-for-%val1 id-for-^parent2 432 /// 433 /// But we don't know the <id> for %val0 and %val1 yet. One way is to visit 434 /// all the blocks twice and use the first visit to assign an <id> to each 435 /// value. But it's paying the overheads just for OpPhi emission. Instead, 436 /// we still visit the blocks once for emission. When we emit the OpPhi 437 /// instructions, we use 0 as a placeholder for the <id>s for %val0 and %val1. 438 /// At the same time, we record their offsets in the emitted binary (which is 439 /// placed inside `functions`) here. And then after emitting all blocks, we 440 /// replace the dummy <id> 0 with the real result <id> by overwriting 441 /// `functions[offset]`. 442 DenseMap<Value, SmallVector<size_t, 1>> deferredPhiValues; 443 }; 444 } // namespace spirv 445 } // namespace mlir 446 447 #endif // MLIR_LIB_TARGET_SPIRV_SERIALIZATION_SERIALIZER_H 448