1 //===- SerializeOps.cpp - MLIR SPIR-V Serialization (Ops) -----------------===//
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 defines the serialization methods for MLIR SPIR-V module ops.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "Serializer.h"
14 
15 #include "mlir/Dialect/SPIRV/IR/SPIRVAttributes.h"
16 #include "mlir/IR/RegionGraphTraits.h"
17 #include "mlir/Support/LogicalResult.h"
18 #include "mlir/Target/SPIRV/SPIRVBinaryUtils.h"
19 #include "llvm/ADT/DepthFirstIterator.h"
20 #include "llvm/Support/Debug.h"
21 
22 #define DEBUG_TYPE "spirv-serialization"
23 
24 using namespace mlir;
25 
26 /// A pre-order depth-first visitor function for processing basic blocks.
27 ///
28 /// Visits the basic blocks starting from the given `headerBlock` in pre-order
29 /// depth-first manner and calls `blockHandler` on each block. Skips handling
30 /// blocks in the `skipBlocks` list. If `skipHeader` is true, `blockHandler`
31 /// will not be invoked in `headerBlock` but still handles all `headerBlock`'s
32 /// successors.
33 ///
34 /// SPIR-V spec "2.16.1. Universal Validation Rules" requires that "the order
35 /// of blocks in a function must satisfy the rule that blocks appear before
36 /// all blocks they dominate." This can be achieved by a pre-order CFG
37 /// traversal algorithm. To make the serialization output more logical and
38 /// readable to human, we perform depth-first CFG traversal and delay the
39 /// serialization of the merge block and the continue block, if exists, until
40 /// after all other blocks have been processed.
41 static LogicalResult
42 visitInPrettyBlockOrder(Block *headerBlock,
43                         function_ref<LogicalResult(Block *)> blockHandler,
44                         bool skipHeader = false, BlockRange skipBlocks = {}) {
45   llvm::df_iterator_default_set<Block *, 4> doneBlocks;
46   doneBlocks.insert(skipBlocks.begin(), skipBlocks.end());
47 
48   for (Block *block : llvm::depth_first_ext(headerBlock, doneBlocks)) {
49     if (skipHeader && block == headerBlock)
50       continue;
51     if (failed(blockHandler(block)))
52       return failure();
53   }
54   return success();
55 }
56 
57 namespace mlir {
58 namespace spirv {
59 LogicalResult Serializer::processConstantOp(spirv::ConstantOp op) {
60   if (auto resultID = prepareConstant(op.getLoc(), op.getType(), op.value())) {
61     valueIDMap[op.getResult()] = resultID;
62     return success();
63   }
64   return failure();
65 }
66 
67 LogicalResult Serializer::processSpecConstantOp(spirv::SpecConstantOp op) {
68   if (auto resultID = prepareConstantScalar(op.getLoc(), op.default_value(),
69                                             /*isSpec=*/true)) {
70     // Emit the OpDecorate instruction for SpecId.
71     if (auto specID = op->getAttrOfType<IntegerAttr>("spec_id")) {
72       auto val = static_cast<uint32_t>(specID.getInt());
73       if (failed(emitDecoration(resultID, spirv::Decoration::SpecId, {val})))
74         return failure();
75     }
76 
77     specConstIDMap[op.sym_name()] = resultID;
78     return processName(resultID, op.sym_name());
79   }
80   return failure();
81 }
82 
83 LogicalResult
84 Serializer::processSpecConstantCompositeOp(spirv::SpecConstantCompositeOp op) {
85   uint32_t typeID = 0;
86   if (failed(processType(op.getLoc(), op.type(), typeID))) {
87     return failure();
88   }
89 
90   auto resultID = getNextID();
91 
92   SmallVector<uint32_t, 8> operands;
93   operands.push_back(typeID);
94   operands.push_back(resultID);
95 
96   auto constituents = op.constituents();
97 
98   for (auto index : llvm::seq<uint32_t>(0, constituents.size())) {
99     auto constituent = constituents[index].dyn_cast<FlatSymbolRefAttr>();
100 
101     auto constituentName = constituent.getValue();
102     auto constituentID = getSpecConstID(constituentName);
103 
104     if (!constituentID) {
105       return op.emitError("unknown result <id> for specialization constant ")
106              << constituentName;
107     }
108 
109     operands.push_back(constituentID);
110   }
111 
112   encodeInstructionInto(typesGlobalValues,
113                         spirv::Opcode::OpSpecConstantComposite, operands);
114   specConstIDMap[op.sym_name()] = resultID;
115 
116   return processName(resultID, op.sym_name());
117 }
118 
119 LogicalResult
120 Serializer::processSpecConstantOperationOp(spirv::SpecConstantOperationOp op) {
121   uint32_t typeID = 0;
122   if (failed(processType(op.getLoc(), op.getType(), typeID))) {
123     return failure();
124   }
125 
126   auto resultID = getNextID();
127 
128   SmallVector<uint32_t, 8> operands;
129   operands.push_back(typeID);
130   operands.push_back(resultID);
131 
132   Block &block = op.getRegion().getBlocks().front();
133   Operation &enclosedOp = block.getOperations().front();
134 
135   std::string enclosedOpName;
136   llvm::raw_string_ostream rss(enclosedOpName);
137   rss << "Op" << enclosedOp.getName().stripDialect();
138   auto enclosedOpcode = spirv::symbolizeOpcode(rss.str());
139 
140   if (!enclosedOpcode) {
141     op.emitError("Couldn't find op code for op ")
142         << enclosedOp.getName().getStringRef();
143     return failure();
144   }
145 
146   operands.push_back(static_cast<uint32_t>(enclosedOpcode.getValue()));
147 
148   // Append operands to the enclosed op to the list of operands.
149   for (Value operand : enclosedOp.getOperands()) {
150     uint32_t id = getValueID(operand);
151     assert(id && "use before def!");
152     operands.push_back(id);
153   }
154 
155   encodeInstructionInto(typesGlobalValues, spirv::Opcode::OpSpecConstantOp,
156                         operands);
157   valueIDMap[op.getResult()] = resultID;
158 
159   return success();
160 }
161 
162 LogicalResult Serializer::processUndefOp(spirv::UndefOp op) {
163   auto undefType = op.getType();
164   auto &id = undefValIDMap[undefType];
165   if (!id) {
166     id = getNextID();
167     uint32_t typeID = 0;
168     if (failed(processType(op.getLoc(), undefType, typeID)))
169       return failure();
170     encodeInstructionInto(typesGlobalValues, spirv::Opcode::OpUndef,
171                           {typeID, id});
172   }
173   valueIDMap[op.getResult()] = id;
174   return success();
175 }
176 
177 LogicalResult Serializer::processFuncOp(spirv::FuncOp op) {
178   LLVM_DEBUG(llvm::dbgs() << "-- start function '" << op.getName() << "' --\n");
179   assert(functionHeader.empty() && functionBody.empty());
180 
181   uint32_t fnTypeID = 0;
182   // Generate type of the function.
183   if (failed(processType(op.getLoc(), op.getType(), fnTypeID)))
184     return failure();
185 
186   // Add the function definition.
187   SmallVector<uint32_t, 4> operands;
188   uint32_t resTypeID = 0;
189   auto resultTypes = op.getType().getResults();
190   if (resultTypes.size() > 1) {
191     return op.emitError("cannot serialize function with multiple return types");
192   }
193   if (failed(processType(op.getLoc(),
194                          (resultTypes.empty() ? getVoidType() : resultTypes[0]),
195                          resTypeID))) {
196     return failure();
197   }
198   operands.push_back(resTypeID);
199   auto funcID = getOrCreateFunctionID(op.getName());
200   operands.push_back(funcID);
201   operands.push_back(static_cast<uint32_t>(op.function_control()));
202   operands.push_back(fnTypeID);
203   encodeInstructionInto(functionHeader, spirv::Opcode::OpFunction, operands);
204 
205   // Add function name.
206   if (failed(processName(funcID, op.getName()))) {
207     return failure();
208   }
209 
210   // Declare the parameters.
211   for (auto arg : op.getArguments()) {
212     uint32_t argTypeID = 0;
213     if (failed(processType(op.getLoc(), arg.getType(), argTypeID))) {
214       return failure();
215     }
216     auto argValueID = getNextID();
217     valueIDMap[arg] = argValueID;
218     encodeInstructionInto(functionHeader, spirv::Opcode::OpFunctionParameter,
219                           {argTypeID, argValueID});
220   }
221 
222   // Process the body.
223   if (op.isExternal()) {
224     return op.emitError("external function is unhandled");
225   }
226 
227   // Some instructions (e.g., OpVariable) in a function must be in the first
228   // block in the function. These instructions will be put in functionHeader.
229   // Thus, we put the label in functionHeader first, and omit it from the first
230   // block.
231   encodeInstructionInto(functionHeader, spirv::Opcode::OpLabel,
232                         {getOrCreateBlockID(&op.front())});
233   if (failed(processBlock(&op.front(), /*omitLabel=*/true)))
234     return failure();
235   if (failed(visitInPrettyBlockOrder(
236           &op.front(), [&](Block *block) { return processBlock(block); },
237           /*skipHeader=*/true))) {
238     return failure();
239   }
240 
241   // There might be OpPhi instructions who have value references needing to fix.
242   for (const auto &deferredValue : deferredPhiValues) {
243     Value value = deferredValue.first;
244     uint32_t id = getValueID(value);
245     LLVM_DEBUG(llvm::dbgs() << "[phi] fix reference of value " << value
246                             << " to id = " << id << '\n');
247     assert(id && "OpPhi references undefined value!");
248     for (size_t offset : deferredValue.second)
249       functionBody[offset] = id;
250   }
251   deferredPhiValues.clear();
252 
253   LLVM_DEBUG(llvm::dbgs() << "-- completed function '" << op.getName()
254                           << "' --\n");
255   // Insert OpFunctionEnd.
256   encodeInstructionInto(functionBody, spirv::Opcode::OpFunctionEnd, {});
257 
258   functions.append(functionHeader.begin(), functionHeader.end());
259   functions.append(functionBody.begin(), functionBody.end());
260   functionHeader.clear();
261   functionBody.clear();
262 
263   return success();
264 }
265 
266 LogicalResult Serializer::processVariableOp(spirv::VariableOp op) {
267   SmallVector<uint32_t, 4> operands;
268   SmallVector<StringRef, 2> elidedAttrs;
269   uint32_t resultID = 0;
270   uint32_t resultTypeID = 0;
271   if (failed(processType(op.getLoc(), op.getType(), resultTypeID))) {
272     return failure();
273   }
274   operands.push_back(resultTypeID);
275   resultID = getNextID();
276   valueIDMap[op.getResult()] = resultID;
277   operands.push_back(resultID);
278   auto attr = op->getAttr(spirv::attributeName<spirv::StorageClass>());
279   if (attr) {
280     operands.push_back(static_cast<uint32_t>(
281         attr.cast<IntegerAttr>().getValue().getZExtValue()));
282   }
283   elidedAttrs.push_back(spirv::attributeName<spirv::StorageClass>());
284   for (auto arg : op.getODSOperands(0)) {
285     auto argID = getValueID(arg);
286     if (!argID) {
287       return emitError(op.getLoc(), "operand 0 has a use before def");
288     }
289     operands.push_back(argID);
290   }
291   if (failed(emitDebugLine(functionHeader, op.getLoc())))
292     return failure();
293   encodeInstructionInto(functionHeader, spirv::Opcode::OpVariable, operands);
294   for (auto attr : op->getAttrs()) {
295     if (llvm::any_of(elidedAttrs, [&](StringRef elided) {
296           return attr.getName() == elided;
297         })) {
298       continue;
299     }
300     if (failed(processDecoration(op.getLoc(), resultID, attr))) {
301       return failure();
302     }
303   }
304   return success();
305 }
306 
307 LogicalResult
308 Serializer::processGlobalVariableOp(spirv::GlobalVariableOp varOp) {
309   // Get TypeID.
310   uint32_t resultTypeID = 0;
311   SmallVector<StringRef, 4> elidedAttrs;
312   if (failed(processType(varOp.getLoc(), varOp.type(), resultTypeID))) {
313     return failure();
314   }
315 
316   elidedAttrs.push_back("type");
317   SmallVector<uint32_t, 4> operands;
318   operands.push_back(resultTypeID);
319   auto resultID = getNextID();
320 
321   // Encode the name.
322   auto varName = varOp.sym_name();
323   elidedAttrs.push_back(SymbolTable::getSymbolAttrName());
324   if (failed(processName(resultID, varName))) {
325     return failure();
326   }
327   globalVarIDMap[varName] = resultID;
328   operands.push_back(resultID);
329 
330   // Encode StorageClass.
331   operands.push_back(static_cast<uint32_t>(varOp.storageClass()));
332 
333   // Encode initialization.
334   if (auto initializer = varOp.initializer()) {
335     auto initializerID = getVariableID(initializer.getValue());
336     if (!initializerID) {
337       return emitError(varOp.getLoc(),
338                        "invalid usage of undefined variable as initializer");
339     }
340     operands.push_back(initializerID);
341     elidedAttrs.push_back("initializer");
342   }
343 
344   if (failed(emitDebugLine(typesGlobalValues, varOp.getLoc())))
345     return failure();
346   encodeInstructionInto(typesGlobalValues, spirv::Opcode::OpVariable, operands);
347   elidedAttrs.push_back("initializer");
348 
349   // Encode decorations.
350   for (auto attr : varOp->getAttrs()) {
351     if (llvm::any_of(elidedAttrs, [&](StringRef elided) {
352           return attr.getName() == elided;
353         })) {
354       continue;
355     }
356     if (failed(processDecoration(varOp.getLoc(), resultID, attr))) {
357       return failure();
358     }
359   }
360   return success();
361 }
362 
363 LogicalResult Serializer::processSelectionOp(spirv::SelectionOp selectionOp) {
364   // Assign <id>s to all blocks so that branches inside the SelectionOp can
365   // resolve properly.
366   auto &body = selectionOp.body();
367   for (Block &block : body)
368     getOrCreateBlockID(&block);
369 
370   auto *headerBlock = selectionOp.getHeaderBlock();
371   auto *mergeBlock = selectionOp.getMergeBlock();
372   auto mergeID = getBlockID(mergeBlock);
373   auto loc = selectionOp.getLoc();
374 
375   // Emit the selection header block, which dominates all other blocks, first.
376   // We need to emit an OpSelectionMerge instruction before the selection header
377   // block's terminator.
378   auto emitSelectionMerge = [&]() {
379     if (failed(emitDebugLine(functionBody, loc)))
380       return failure();
381     lastProcessedWasMergeInst = true;
382     encodeInstructionInto(
383         functionBody, spirv::Opcode::OpSelectionMerge,
384         {mergeID, static_cast<uint32_t>(selectionOp.selection_control())});
385     return success();
386   };
387   // For structured selection, we cannot have blocks in the selection construct
388   // branching to the selection header block. Entering the selection (and
389   // reaching the selection header) must be from the block containing the
390   // spv.mlir.selection op. If there are ops ahead of the spv.mlir.selection op
391   // in the block, we can "merge" them into the selection header. So here we
392   // don't need to emit a separate block; just continue with the existing block.
393   if (failed(processBlock(headerBlock, /*omitLabel=*/true, emitSelectionMerge)))
394     return failure();
395 
396   // Process all blocks with a depth-first visitor starting from the header
397   // block. The selection header block and merge block are skipped by this
398   // visitor.
399   if (failed(visitInPrettyBlockOrder(
400           headerBlock, [&](Block *block) { return processBlock(block); },
401           /*skipHeader=*/true, /*skipBlocks=*/{mergeBlock})))
402     return failure();
403 
404   // There is nothing to do for the merge block in the selection, which just
405   // contains a spv.mlir.merge op, itself. But we need to have an OpLabel
406   // instruction to start a new SPIR-V block for ops following this SelectionOp.
407   // The block should use the <id> for the merge block.
408   encodeInstructionInto(functionBody, spirv::Opcode::OpLabel, {mergeID});
409   LLVM_DEBUG(llvm::dbgs() << "done merge ");
410   LLVM_DEBUG(printBlock(mergeBlock, llvm::dbgs()));
411   LLVM_DEBUG(llvm::dbgs() << "\n");
412   return success();
413 }
414 
415 LogicalResult Serializer::processLoopOp(spirv::LoopOp loopOp) {
416   // Assign <id>s to all blocks so that branches inside the LoopOp can resolve
417   // properly. We don't need to assign for the entry block, which is just for
418   // satisfying MLIR region's structural requirement.
419   auto &body = loopOp.body();
420   for (Block &block : llvm::make_range(std::next(body.begin(), 1), body.end()))
421     getOrCreateBlockID(&block);
422 
423   auto *headerBlock = loopOp.getHeaderBlock();
424   auto *continueBlock = loopOp.getContinueBlock();
425   auto *mergeBlock = loopOp.getMergeBlock();
426   auto headerID = getBlockID(headerBlock);
427   auto continueID = getBlockID(continueBlock);
428   auto mergeID = getBlockID(mergeBlock);
429   auto loc = loopOp.getLoc();
430 
431   // This LoopOp is in some MLIR block with preceding and following ops. In the
432   // binary format, it should reside in separate SPIR-V blocks from its
433   // preceding and following ops. So we need to emit unconditional branches to
434   // jump to this LoopOp's SPIR-V blocks and jumping back to the normal flow
435   // afterwards.
436   encodeInstructionInto(functionBody, spirv::Opcode::OpBranch, {headerID});
437 
438   // LoopOp's entry block is just there for satisfying MLIR's structural
439   // requirements so we omit it and start serialization from the loop header
440   // block.
441 
442   // Emit the loop header block, which dominates all other blocks, first. We
443   // need to emit an OpLoopMerge instruction before the loop header block's
444   // terminator.
445   auto emitLoopMerge = [&]() {
446     if (failed(emitDebugLine(functionBody, loc)))
447       return failure();
448     lastProcessedWasMergeInst = true;
449     encodeInstructionInto(
450         functionBody, spirv::Opcode::OpLoopMerge,
451         {mergeID, continueID, static_cast<uint32_t>(loopOp.loop_control())});
452     return success();
453   };
454   if (failed(processBlock(headerBlock, /*omitLabel=*/false, emitLoopMerge)))
455     return failure();
456 
457   // Process all blocks with a depth-first visitor starting from the header
458   // block. The loop header block, loop continue block, and loop merge block are
459   // skipped by this visitor and handled later in this function.
460   if (failed(visitInPrettyBlockOrder(
461           headerBlock, [&](Block *block) { return processBlock(block); },
462           /*skipHeader=*/true, /*skipBlocks=*/{continueBlock, mergeBlock})))
463     return failure();
464 
465   // We have handled all other blocks. Now get to the loop continue block.
466   if (failed(processBlock(continueBlock)))
467     return failure();
468 
469   // There is nothing to do for the merge block in the loop, which just contains
470   // a spv.mlir.merge op, itself. But we need to have an OpLabel instruction to
471   // start a new SPIR-V block for ops following this LoopOp. The block should
472   // use the <id> for the merge block.
473   encodeInstructionInto(functionBody, spirv::Opcode::OpLabel, {mergeID});
474   LLVM_DEBUG(llvm::dbgs() << "done merge ");
475   LLVM_DEBUG(printBlock(mergeBlock, llvm::dbgs()));
476   LLVM_DEBUG(llvm::dbgs() << "\n");
477   return success();
478 }
479 
480 LogicalResult Serializer::processBranchConditionalOp(
481     spirv::BranchConditionalOp condBranchOp) {
482   auto conditionID = getValueID(condBranchOp.condition());
483   auto trueLabelID = getOrCreateBlockID(condBranchOp.getTrueBlock());
484   auto falseLabelID = getOrCreateBlockID(condBranchOp.getFalseBlock());
485   SmallVector<uint32_t, 5> arguments{conditionID, trueLabelID, falseLabelID};
486 
487   if (auto weights = condBranchOp.branch_weights()) {
488     for (auto val : weights->getValue())
489       arguments.push_back(val.cast<IntegerAttr>().getInt());
490   }
491 
492   if (failed(emitDebugLine(functionBody, condBranchOp.getLoc())))
493     return failure();
494   encodeInstructionInto(functionBody, spirv::Opcode::OpBranchConditional,
495                         arguments);
496   return success();
497 }
498 
499 LogicalResult Serializer::processBranchOp(spirv::BranchOp branchOp) {
500   if (failed(emitDebugLine(functionBody, branchOp.getLoc())))
501     return failure();
502   encodeInstructionInto(functionBody, spirv::Opcode::OpBranch,
503                         {getOrCreateBlockID(branchOp.getTarget())});
504   return success();
505 }
506 
507 LogicalResult Serializer::processAddressOfOp(spirv::AddressOfOp addressOfOp) {
508   auto varName = addressOfOp.variable();
509   auto variableID = getVariableID(varName);
510   if (!variableID) {
511     return addressOfOp.emitError("unknown result <id> for variable ")
512            << varName;
513   }
514   valueIDMap[addressOfOp.pointer()] = variableID;
515   return success();
516 }
517 
518 LogicalResult
519 Serializer::processReferenceOfOp(spirv::ReferenceOfOp referenceOfOp) {
520   auto constName = referenceOfOp.spec_const();
521   auto constID = getSpecConstID(constName);
522   if (!constID) {
523     return referenceOfOp.emitError(
524                "unknown result <id> for specialization constant ")
525            << constName;
526   }
527   valueIDMap[referenceOfOp.reference()] = constID;
528   return success();
529 }
530 
531 template <>
532 LogicalResult
533 Serializer::processOp<spirv::EntryPointOp>(spirv::EntryPointOp op) {
534   SmallVector<uint32_t, 4> operands;
535   // Add the ExecutionModel.
536   operands.push_back(static_cast<uint32_t>(op.execution_model()));
537   // Add the function <id>.
538   auto funcID = getFunctionID(op.fn());
539   if (!funcID) {
540     return op.emitError("missing <id> for function ")
541            << op.fn()
542            << "; function needs to be defined before spv.EntryPoint is "
543               "serialized";
544   }
545   operands.push_back(funcID);
546   // Add the name of the function.
547   spirv::encodeStringLiteralInto(operands, op.fn());
548 
549   // Add the interface values.
550   if (auto interface = op.interface()) {
551     for (auto var : interface.getValue()) {
552       auto id = getVariableID(var.cast<FlatSymbolRefAttr>().getValue());
553       if (!id) {
554         return op.emitError("referencing undefined global variable."
555                             "spv.EntryPoint is at the end of spv.module. All "
556                             "referenced variables should already be defined");
557       }
558       operands.push_back(id);
559     }
560   }
561   encodeInstructionInto(entryPoints, spirv::Opcode::OpEntryPoint, operands);
562   return success();
563 }
564 
565 template <>
566 LogicalResult
567 Serializer::processOp<spirv::ControlBarrierOp>(spirv::ControlBarrierOp op) {
568   StringRef argNames[] = {"execution_scope", "memory_scope",
569                           "memory_semantics"};
570   SmallVector<uint32_t, 3> operands;
571 
572   for (auto argName : argNames) {
573     auto argIntAttr = op->getAttrOfType<IntegerAttr>(argName);
574     auto operand = prepareConstantInt(op.getLoc(), argIntAttr);
575     if (!operand) {
576       return failure();
577     }
578     operands.push_back(operand);
579   }
580 
581   encodeInstructionInto(functionBody, spirv::Opcode::OpControlBarrier,
582                         operands);
583   return success();
584 }
585 
586 template <>
587 LogicalResult
588 Serializer::processOp<spirv::ExecutionModeOp>(spirv::ExecutionModeOp op) {
589   SmallVector<uint32_t, 4> operands;
590   // Add the function <id>.
591   auto funcID = getFunctionID(op.fn());
592   if (!funcID) {
593     return op.emitError("missing <id> for function ")
594            << op.fn()
595            << "; function needs to be serialized before ExecutionModeOp is "
596               "serialized";
597   }
598   operands.push_back(funcID);
599   // Add the ExecutionMode.
600   operands.push_back(static_cast<uint32_t>(op.execution_mode()));
601 
602   // Serialize values if any.
603   auto values = op.values();
604   if (values) {
605     for (auto &intVal : values.getValue()) {
606       operands.push_back(static_cast<uint32_t>(
607           intVal.cast<IntegerAttr>().getValue().getZExtValue()));
608     }
609   }
610   encodeInstructionInto(executionModes, spirv::Opcode::OpExecutionMode,
611                         operands);
612   return success();
613 }
614 
615 template <>
616 LogicalResult
617 Serializer::processOp<spirv::MemoryBarrierOp>(spirv::MemoryBarrierOp op) {
618   StringRef argNames[] = {"memory_scope", "memory_semantics"};
619   SmallVector<uint32_t, 2> operands;
620 
621   for (auto argName : argNames) {
622     auto argIntAttr = op->getAttrOfType<IntegerAttr>(argName);
623     auto operand = prepareConstantInt(op.getLoc(), argIntAttr);
624     if (!operand) {
625       return failure();
626     }
627     operands.push_back(operand);
628   }
629 
630   encodeInstructionInto(functionBody, spirv::Opcode::OpMemoryBarrier, operands);
631   return success();
632 }
633 
634 template <>
635 LogicalResult
636 Serializer::processOp<spirv::FunctionCallOp>(spirv::FunctionCallOp op) {
637   auto funcName = op.callee();
638   uint32_t resTypeID = 0;
639 
640   Type resultTy = op.getNumResults() ? *op.result_type_begin() : getVoidType();
641   if (failed(processType(op.getLoc(), resultTy, resTypeID)))
642     return failure();
643 
644   auto funcID = getOrCreateFunctionID(funcName);
645   auto funcCallID = getNextID();
646   SmallVector<uint32_t, 8> operands{resTypeID, funcCallID, funcID};
647 
648   for (auto value : op.arguments()) {
649     auto valueID = getValueID(value);
650     assert(valueID && "cannot find a value for spv.FunctionCall");
651     operands.push_back(valueID);
652   }
653 
654   if (!resultTy.isa<NoneType>())
655     valueIDMap[op.getResult(0)] = funcCallID;
656 
657   encodeInstructionInto(functionBody, spirv::Opcode::OpFunctionCall, operands);
658   return success();
659 }
660 
661 template <>
662 LogicalResult
663 Serializer::processOp<spirv::CopyMemoryOp>(spirv::CopyMemoryOp op) {
664   SmallVector<uint32_t, 4> operands;
665   SmallVector<StringRef, 2> elidedAttrs;
666 
667   for (Value operand : op->getOperands()) {
668     auto id = getValueID(operand);
669     assert(id && "use before def!");
670     operands.push_back(id);
671   }
672 
673   if (auto attr = op->getAttr("memory_access")) {
674     operands.push_back(static_cast<uint32_t>(
675         attr.cast<IntegerAttr>().getValue().getZExtValue()));
676   }
677 
678   elidedAttrs.push_back("memory_access");
679 
680   if (auto attr = op->getAttr("alignment")) {
681     operands.push_back(static_cast<uint32_t>(
682         attr.cast<IntegerAttr>().getValue().getZExtValue()));
683   }
684 
685   elidedAttrs.push_back("alignment");
686 
687   if (auto attr = op->getAttr("source_memory_access")) {
688     operands.push_back(static_cast<uint32_t>(
689         attr.cast<IntegerAttr>().getValue().getZExtValue()));
690   }
691 
692   elidedAttrs.push_back("source_memory_access");
693 
694   if (auto attr = op->getAttr("source_alignment")) {
695     operands.push_back(static_cast<uint32_t>(
696         attr.cast<IntegerAttr>().getValue().getZExtValue()));
697   }
698 
699   elidedAttrs.push_back("source_alignment");
700   if (failed(emitDebugLine(functionBody, op.getLoc())))
701     return failure();
702   encodeInstructionInto(functionBody, spirv::Opcode::OpCopyMemory, operands);
703 
704   return success();
705 }
706 
707 // Pull in auto-generated Serializer::dispatchToAutogenSerialization() and
708 // various Serializer::processOp<...>() specializations.
709 #define GET_SERIALIZATION_FNS
710 #include "mlir/Dialect/SPIRV/IR/SPIRVSerialization.inc"
711 
712 } // namespace spirv
713 } // namespace mlir
714