MLIR 23.0.0git
Serializer.h
Go to the documentation of this file.
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
17#include "mlir/IR/Builders.h"
19#include "llvm/ADT/SetVector.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/Support/raw_ostream.h"
22
23namespace mlir {
24namespace spirv {
25
26void encodeInstructionInto(SmallVectorImpl<uint32_t> &binary, 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.
43public:
44 /// Creates a serializer for the given SPIR-V `module`.
45 explicit Serializer(spirv::ModuleOp module,
46 const SerializationOptions &options);
47
48 /// Serializes the remembered SPIR-V module.
49 LogicalResult serialize();
50
51 /// Collects the final SPIR-V `binary`.
53
54#ifndef NDEBUG
55 /// (For debugging) prints each value and its corresponding result <id>.
57#endif
58
59private:
60 // Note that there are two main categories of methods in this class:
61 // * process*() methods are meant to fully serialize a SPIR-V module entity
62 // (header, type, op, etc.). They update internal vectors containing
63 // different binary sections. They are not meant to be called except the
64 // top-level serialization loop.
65 // * prepare*() methods are meant to be helpers that prepare for serializing
66 // certain entity. They may or may not update internal vectors containing
67 // different binary sections. They are meant to be called among themselves
68 // or by other process*() methods for subtasks.
69
70 //===--------------------------------------------------------------------===//
71 // <id>
72 //===--------------------------------------------------------------------===//
73
74 // Note that it is illegal to use id <0> in SPIR-V binary module. Various
75 // methods in this class, if using SPIR-V word (uint32_t) as interface,
76 // check or return id <0> to indicate error in processing.
77
78 /// Consumes the next unused <id>. This method will never return 0.
79 uint32_t getNextID() { return nextID++; }
80
81 //===--------------------------------------------------------------------===//
82 // Module structure
83 //===--------------------------------------------------------------------===//
84
85 uint32_t getSpecConstID(StringRef constName) const {
86 return specConstIDMap.lookup(constName);
87 }
88
89 uint32_t getVariableID(StringRef varName) const {
90 return globalVarIDMap.lookup(varName);
91 }
92
93 uint32_t getFunctionID(StringRef fnName) const {
94 return funcIDMap.lookup(fnName);
95 }
96
97 /// Gets the <id> for the function with the given name. Assigns the next
98 /// available <id> if the function haven't been deserialized.
99 uint32_t getOrCreateFunctionID(StringRef fnName);
100
101 void processCapability();
102
103 void processDebugInfo();
104
105 LogicalResult processExtension();
106
107 /// Encodes `op` + `operands` into `binary`, splitting via the
108 /// SPV_INTEL_long_composites continuation opcode when the total word count
109 /// would exceed kMaxWordCount. `op` must be a splittable composite/struct
110 /// opcode (see getContinuationOpcode). The capability and extension are
111 /// emitted lazily on first split.
112 void encodeInstructionWithContinuationInto(SmallVectorImpl<uint32_t> &binary,
113 spirv::Opcode op,
114 ArrayRef<uint32_t> operands);
115
116 void addLongCompositesCapability();
117
118 void processMemoryModel();
119
120 LogicalResult processConstantOp(spirv::ConstantOp op);
121
122 LogicalResult processCompositeConstructOp(spirv::CompositeConstructOp op);
123
124 LogicalResult processConstantCompositeReplicateOp(
125 spirv::EXTConstantCompositeReplicateOp op);
126
127 LogicalResult processSpecConstantOp(spirv::SpecConstantOp op);
128
129 LogicalResult
130 processSpecConstantCompositeOp(spirv::SpecConstantCompositeOp op);
131
132 LogicalResult processSpecConstantCompositeReplicateOp(
133 spirv::EXTSpecConstantCompositeReplicateOp op);
134
135 LogicalResult
136 processSpecConstantOperationOp(spirv::SpecConstantOperationOp op);
137
138 LogicalResult processGraphConstantARMOp(spirv::GraphConstantARMOp op);
139
140 /// SPIR-V dialect supports OpUndef using spirv.UndefOp that produces a SSA
141 /// value to use with other operations. The SPIR-V spec recommends that
142 /// OpUndef be generated at module level. The serialization generates an
143 /// OpUndef for each type needed at module level.
144 LogicalResult processUndefOp(spirv::UndefOp op);
145
146 /// Emit OpName for the given `resultID`.
147 LogicalResult processName(uint32_t resultID, StringRef name);
148
149 /// Processes a SPIR-V function op.
150 LogicalResult processFuncOp(spirv::FuncOp op);
151 LogicalResult processFuncParameter(spirv::FuncOp op);
152
153 /// Processes a SPIR-V GraphARM op.
154 LogicalResult processGraphARMOp(spirv::GraphARMOp op);
155
156 /// Processes a SPIR-V GraphEntryPointARM op.
157 LogicalResult processGraphEntryPointARMOp(spirv::GraphEntryPointARMOp op);
158
159 /// Processes a SPIR-V GraphOutputsARMOp op.
160 LogicalResult processGraphOutputsARMOp(spirv::GraphOutputsARMOp op);
161
162 LogicalResult processVariableOp(spirv::VariableOp op);
163
164 /// Process a SPIR-V GlobalVariableOp
165 LogicalResult processGlobalVariableOp(spirv::GlobalVariableOp varOp);
166
167 /// Process attributes that translate to decorations on the result <id>
168 LogicalResult processDecorationAttr(Location loc, uint32_t resultID,
169 Decoration decoration, Attribute attr);
170 LogicalResult processDecoration(Location loc, uint32_t resultID,
171 NamedAttribute attr);
172
173 template <typename DType>
174 LogicalResult processTypeDecoration(Location loc, DType type,
175 uint32_t resultId) {
176 return emitError(loc, "unhandled decoration for type:") << type;
177 }
178
179 /// Process member decoration
180 LogicalResult processMemberDecoration(
181 uint32_t structID,
182 const spirv::StructType::MemberDecorationInfo &memberDecorationInfo);
183
184 //===--------------------------------------------------------------------===//
185 // Types
186 //===--------------------------------------------------------------------===//
187
188 uint32_t getTypeID(Type type) const { return typeIDMap.lookup(type); }
189
190 Type getVoidType() { return mlirBuilder.getNoneType(); }
191
192 bool isVoidType(Type type) const { return isa<NoneType>(type); }
193
194 /// Returns true if the given type is a pointer type to a struct in some
195 /// interface storage class.
196 bool isInterfaceStructPtrType(Type type) const;
197
198 /// Main dispatch method for serializing a type. The result <id> of the
199 /// serialized type will be returned as `typeID`.
200 LogicalResult processType(Location loc, Type type, uint32_t &typeID);
201 LogicalResult processTypeImpl(Location loc, Type type, uint32_t &typeID,
202 SetVector<StringRef> &serializationCtx);
203
204 /// Method for preparing basic SPIR-V type serialization. Returns the type's
205 /// opcode and operands for the instruction via `typeEnum` and `operands`.
206 LogicalResult prepareBasicType(Location loc, Type type, uint32_t resultID,
207 spirv::Opcode &typeEnum,
209 bool &deferSerialization,
210 SetVector<StringRef> &serializationCtx);
211
212 LogicalResult prepareFunctionType(Location loc, FunctionType type,
213 spirv::Opcode &typeEnum,
214 SmallVectorImpl<uint32_t> &operands);
215
216 LogicalResult prepareGraphType(Location loc, GraphType type,
217 spirv::Opcode &typeEnum,
218 SmallVectorImpl<uint32_t> &operands);
219
220 //===--------------------------------------------------------------------===//
221 // Constant
222 //===--------------------------------------------------------------------===//
223
224 uint32_t getConstantID(Attribute value) const {
225 return constIDMap.lookup(value);
226 }
227
228 uint32_t getConstantCompositeReplicateID(
229 std::pair<Attribute, Type> valueTypePair) const {
230 return constCompositeReplicateIDMap.lookup(valueTypePair);
231 }
232
233 /// Main dispatch method for processing a constant with the given `constType`
234 /// and `valueAttr`. `constType` is needed here because we can interpret the
235 /// `valueAttr` as a different type than the type of `valueAttr` itself; for
236 /// example, ArrayAttr, whose type is NoneType, is used for spirv::ArrayType
237 /// constants.
238 uint32_t prepareConstant(Location loc, Type constType, Attribute valueAttr);
239
240 /// Prepares array attribute serialization. This method emits corresponding
241 /// OpConstant* and returns the result <id> associated with it. Returns 0 if
242 /// failed.
243 uint32_t prepareArrayConstant(Location loc, Type constType, ArrayAttr attr);
244
245 /// Prepares bool/int/float DenseElementsAttr serialization. This method
246 /// iterates the DenseElementsAttr to construct the constant array, and
247 /// returns the result <id> associated with it. Returns 0 if failed. Note
248 /// that the size of `index` must match the rank.
249 /// TODO: Consider to enhance splat elements cases. For splat cases,
250 /// we don't need to loop over all elements, especially when the splat value
251 /// is zero. We can use OpConstantNull when the value is zero.
252 uint32_t prepareDenseElementsConstant(Location loc, Type constType,
253 DenseElementsAttr valueAttr, int dim,
255
256 /// Prepares scalar attribute serialization. This method emits corresponding
257 /// OpConstant* and returns the result <id> associated with it. Returns 0 if
258 /// the attribute is not for a scalar bool/integer/float value. If `isSpec` is
259 /// true, then the constant will be serialized as a specialization constant.
260 uint32_t prepareConstantScalar(Location loc, Attribute valueAttr,
261 bool isSpec = false);
262
263 uint32_t prepareConstantBool(Location loc, BoolAttr boolAttr,
264 bool isSpec = false);
265
266 uint32_t prepareConstantInt(Location loc, IntegerAttr intAttr,
267 bool isSpec = false);
268
269 uint32_t getGraphConstantARMId(Attribute value) const {
270 return graphConstIDMap.lookup(value);
271 }
272
273 uint32_t prepareGraphConstantId(Location loc, Type graphConstType,
274 IntegerAttr intAttr);
275
276 uint32_t prepareConstantFp(Location loc, FloatAttr floatAttr,
277 bool isSpec = false);
278
279 /// Prepares `spirv.EXTConstantCompositeReplicateOp` serialization. This
280 /// method emits OpConstantCompositeReplicateEXT and returns the result <id>
281 /// associated with it.
282 uint32_t prepareConstantCompositeReplicate(Location loc, Type resultType,
283 Attribute valueAttr);
284
285 //===--------------------------------------------------------------------===//
286 // Control flow
287 //===--------------------------------------------------------------------===//
288
289 /// Returns the result <id> for the given block.
290 uint32_t getBlockID(Block *block) const { return blockIDMap.lookup(block); }
291
292 /// Returns the result <id> for the given block. If no <id> has been assigned,
293 /// assigns the next available <id>
294 uint32_t getOrCreateBlockID(Block *block);
295
296#ifndef NDEBUG
297 /// (For debugging) prints the block with its result <id>.
298 void printBlock(Block *block, raw_ostream &os);
299#endif
300
301 /// Processes the given `block` and emits SPIR-V instructions for all ops
302 /// inside. Does not emit OpLabel for this block if `omitLabel` is true.
303 /// `emitMerge` is a callback that will be invoked before handling the
304 /// terminator op to inject the Op*Merge instruction if this is a SPIR-V
305 /// selection/loop header block.
306 LogicalResult processBlock(Block *block, bool omitLabel = false,
307 function_ref<LogicalResult()> emitMerge = nullptr);
308
309 /// Emits OpPhi instructions for the given block if it has block arguments.
310 LogicalResult emitPhiForBlockArguments(Block *block);
311
312 LogicalResult processSelectionOp(spirv::SelectionOp selectionOp);
313
314 LogicalResult processLoopOp(spirv::LoopOp loopOp);
315
316 LogicalResult processBranchConditionalOp(spirv::BranchConditionalOp);
317
318 LogicalResult processBranchOp(spirv::BranchOp branchOp);
319
320 LogicalResult processSwitchOp(spirv::SwitchOp switchOp);
321
322 //===--------------------------------------------------------------------===//
323 // Operations
324 //===--------------------------------------------------------------------===//
325
326 LogicalResult encodeExtensionInstruction(Operation *op,
327 StringRef extensionSetName,
328 uint32_t opcode,
329 ArrayRef<uint32_t> operands);
330
331 uint32_t getValueID(Value val) const { return valueIDMap.lookup(val); }
332
333 LogicalResult processAddressOfOp(spirv::AddressOfOp addressOfOp);
334
335 LogicalResult processReferenceOfOp(spirv::ReferenceOfOp referenceOfOp);
336
337 /// Main dispatch method for serializing an operation.
338 LogicalResult processOperation(Operation *op);
339
340 /// Serializes an operation `op` as core instruction with `opcode` if
341 /// `extInstSet` is empty. Otherwise serializes it as an extended instruction
342 /// with `opcode` from `extInstSet`.
343 /// This method is a generic one for dispatching any SPIR-V ops that has no
344 /// variadic operands and attributes in TableGen definitions.
345 LogicalResult processOpWithoutGrammarAttr(Operation *op, StringRef extInstSet,
346 uint32_t opcode);
347
348 /// Dispatches to the serialization function for an operation in SPIR-V
349 /// dialect that is a mirror of an instruction in the SPIR-V spec. This is
350 /// auto-generated from ODS. Dispatch is handled for all operations in SPIR-V
351 /// dialect that have hasOpcode == 1.
352 LogicalResult dispatchToAutogenSerialization(Operation *op);
353
354 /// Serializes an operation in the SPIR-V dialect that is a mirror of an
355 /// instruction in the SPIR-V spec. This is auto generated if hasOpcode == 1
356 /// and autogenSerialization == 1 in ODS.
357 template <typename OpTy>
358 LogicalResult processOp(OpTy op) {
359 return op.emitError("unsupported op serialization");
360 }
361
362 //===--------------------------------------------------------------------===//
363 // Utilities
364 //===--------------------------------------------------------------------===//
365
366 /// Emits an OpDecorate instruction to decorate the given `target` with the
367 /// given `decoration`.
368 LogicalResult emitDecoration(uint32_t target, spirv::Decoration decoration,
369 ArrayRef<uint32_t> params = {});
370
371 /// Emits an OpDecorateId instruction to decorate the given `target` with the
372 /// given `decoration` whose extra operands are SPIR-V <id>s.
373 LogicalResult emitDecorationId(uint32_t target, spirv::Decoration decoration,
374 ArrayRef<uint32_t> operandIds);
375
376 /// Emits an OpLine instruction with the given `loc` location information into
377 /// the given `binary` vector.
378 LogicalResult emitDebugLine(SmallVectorImpl<uint32_t> &binary, Location loc);
379
380private:
381 /// The SPIR-V module to be serialized.
382 spirv::ModuleOp module;
383
384 /// An MLIR builder for getting MLIR constructs.
385 mlir::Builder mlirBuilder;
386
387 /// Serialization options.
388 SerializationOptions options;
389
390 /// A flag which indicates if the last processed instruction was a merge
391 /// instruction.
392 /// According to SPIR-V spec: "If a branch merge instruction is used, the last
393 /// OpLine in the block must be before its merge instruction".
394 bool lastProcessedWasMergeInst = false;
395
396 /// The <id> of the OpString instruction, which specifies a file name, for
397 /// use by other debug instructions.
398 uint32_t fileID = 0;
399
400 /// The next available result <id>.
401 uint32_t nextID = 1;
402
403 bool longCompositesEmitted = false;
404
405 // The following are for different SPIR-V instruction sections. They follow
406 // the logical layout of a SPIR-V module.
407
408 SmallVector<uint32_t, 4> capabilities;
409 SmallVector<uint32_t, 0> extensions;
410 SmallVector<uint32_t, 0> extendedSets;
411 SmallVector<uint32_t, 3> memoryModel;
412 SmallVector<uint32_t, 0> entryPoints;
413 SmallVector<uint32_t, 4> executionModes;
416 SmallVector<uint32_t, 0> decorations;
417 SmallVector<uint32_t, 0> typesGlobalValues;
418 SmallVector<uint32_t, 0> functions;
420
421 /// Recursive struct references are serialized as OpTypePointer instructions
422 /// to the recursive struct type. However, the OpTypePointer instruction
423 /// cannot be emitted before the recursive struct's OpTypeStruct.
424 /// RecursiveStructPointerInfo stores the data needed to emit such
425 /// OpTypePointer instructions after forward references to such types.
426 struct RecursiveStructPointerInfo {
427 uint32_t pointerTypeID;
428 spirv::StorageClass storageClass;
429 };
430
431 // Maps spirv::StructType to its recursive reference member info.
433 recursiveStructInfos;
434
435 /// `functionHeader` contains all the instructions that must be in the first
436 /// block in the function or graph, and `functionBody` contains the rest.
437 /// After processing FuncOp/GraphARMOp, the encoded instructions of a function
438 /// or graph are appended to `functions` or `graphs` respectively. Examples of
439 /// instructions in `functionHeader` in order:
440 ///
441 /// For a FuncOp:
442 /// OpFunction ...
443 /// OpFunctionParameter ...
444 /// OpFunctionParameter ...
445 /// OpLabel ...
446 /// OpVariable ...
447 /// OpVariable ...
448 ///
449 /// For a GraphARMOp
450 /// OpGraphARM ...
451 /// OpGraphInputARM ...
452 SmallVector<uint32_t, 0> functionHeader;
453 SmallVector<uint32_t, 0> functionBody;
454
455 /// Map from type used in SPIR-V module to their <id>s.
456 DenseMap<Type, uint32_t> typeIDMap;
457
458 /// Map from constant values to their <id>s.
460
461 /// Map from a replicated composite constant's value and type to their <id>s.
462 DenseMap<std::pair<Attribute, Type>, uint32_t> constCompositeReplicateIDMap;
463
464 /// Map from specialization constant names to their <id>s.
465 llvm::StringMap<uint32_t> specConstIDMap;
466
467 /// Map from graph constant ID value to their <id>s.
468 DenseMap<Attribute, uint32_t> graphConstIDMap;
469
470 /// Map from GlobalVariableOps name to <id>s.
471 llvm::StringMap<uint32_t> globalVarIDMap;
472
473 /// Map from FuncOps name to <id>s.
474 llvm::StringMap<uint32_t> funcIDMap;
475
476 /// Map from blocks to their <id>s.
478
479 /// Map from the Type to the <id> that represents undef value of that type.
480 DenseMap<Type, uint32_t> undefValIDMap;
481
482 /// Map from results of normal operations to their <id>s.
483 DenseMap<Value, uint32_t> valueIDMap;
484
485 /// Map from extended instruction set name to <id>s.
486 llvm::StringMap<uint32_t> extendedInstSetIDMap;
487
488 /// Map from values used in OpPhi instructions to their offset in the
489 /// `functions` section.
490 ///
491 /// When processing a block with arguments, we need to emit OpPhi
492 /// instructions to record the predecessor block <id>s and the values they
493 /// send to the block in question. But it's not guaranteed all values are
494 /// visited and thus assigned result <id>s. So we need this list to capture
495 /// the offsets into `functions` where a value is used so that we can fix it
496 /// up later after processing all the blocks in a function.
497 ///
498 /// More concretely, say if we are visiting the following blocks:
499 ///
500 /// ```mlir
501 /// ^phi(%arg0: i32):
502 /// ...
503 /// ^parent1:
504 /// ...
505 /// spirv.Branch ^phi(%val0: i32)
506 /// ^parent2:
507 /// ...
508 /// spirv.Branch ^phi(%val1: i32)
509 /// ```
510 ///
511 /// When we are serializing the `^phi` block, we need to emit at the beginning
512 /// of the block OpPhi instructions which has the following parameters:
513 ///
514 /// OpPhi id-for-i32 id-for-%arg0 id-for-%val0 id-for-^parent1
515 /// id-for-%val1 id-for-^parent2
516 ///
517 /// But we don't know the <id> for %val0 and %val1 yet. One way is to visit
518 /// all the blocks twice and use the first visit to assign an <id> to each
519 /// value. But it's paying the overheads just for OpPhi emission. Instead,
520 /// we still visit the blocks once for emission. When we emit the OpPhi
521 /// instructions, we use 0 as a placeholder for the <id>s for %val0 and %val1.
522 /// At the same time, we record their offsets in the emitted binary (which is
523 /// placed inside `functions`) here. And then after emitting all blocks, we
524 /// replace the dummy <id> 0 with the real result <id> by overwriting
525 /// `functions[offset]`.
527};
528} // namespace spirv
529} // namespace mlir
530
531#endif // MLIR_LIB_TARGET_SPIRV_SERIALIZATION_SERIALIZER_H
ArrayAttr()
Attributes are known-constant values of operations.
Definition Attributes.h:25
Block represents an ordered list of Operations.
Definition Block.h:33
Special case of IntegerAttr to represent boolean integers, i.e., signless i1 integers.
This class is a general helper class for creating context-global objects like types,...
Definition Builders.h:51
An attribute that represents a reference to a dense vector or tensor object.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:164
Operation is the basic unit of execution within MLIR.
Definition Operation.h:88
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
void printValueIDMap(raw_ostream &os)
(For debugging) prints each value and its corresponding result <id>.
Serializer(spirv::ModuleOp module, const SerializationOptions &options)
Creates a serializer for the given SPIR-V module.
LogicalResult serialize()
Serializes the remembered SPIR-V module.
void collect(SmallVectorImpl< uint32_t > &binary)
Collects the final SPIR-V binary.
void encodeInstructionInto(SmallVectorImpl< uint32_t > &binary, spirv::Opcode op, ArrayRef< uint32_t > operands)
Encodes an SPIR-V instruction with the given opcode and operands into the given binary vector.
Include the generated interface declarations.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
llvm::SetVector< T, Vector, Set, N > SetVector
Definition LLVM.h:125
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:120
llvm::function_ref< Fn > function_ref
Definition LLVM.h:147