LLVM 22.0.0git
SPIRVInstPrinter.cpp
Go to the documentation of this file.
1//===-- SPIRVInstPrinter.cpp - Output SPIR-V MCInsts as ASM -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This class prints a SPIR-V MCInst to a .s file.
10//
11//===----------------------------------------------------------------------===//
12
13#include "SPIRVInstPrinter.h"
14#include "SPIRV.h"
15#include "SPIRVBaseInfo.h"
16#include "llvm/ADT/APFloat.h"
17#include "llvm/MC/MCAsmInfo.h"
18#include "llvm/MC/MCExpr.h"
19#include "llvm/MC/MCInst.h"
20#include "llvm/MC/MCInstrInfo.h"
21#include "llvm/MC/MCSymbol.h"
23
24using namespace llvm;
25using namespace llvm::SPIRV;
26
27#define DEBUG_TYPE "asm-printer"
28
29// Include the auto-generated portion of the assembly writer.
30#include "SPIRVGenAsmWriter.inc"
31
33 unsigned StartIndex,
34 raw_ostream &O,
35 bool SkipFirstSpace,
36 bool SkipImmediates) {
37 const unsigned NumOps = MI->getNumOperands();
38 for (unsigned i = StartIndex; i < NumOps; ++i) {
39 if (!SkipImmediates || !MI->getOperand(i).isImm()) {
40 if (!SkipFirstSpace || i != StartIndex)
41 O << ' ';
42 printOperand(MI, i, O);
43 }
44 }
45}
46
48 unsigned StartIndex,
49 raw_ostream &O) {
50 unsigned IsBitwidth16 = MI->getFlags() & SPIRV::INST_PRINTER_WIDTH16;
51 const unsigned NumVarOps = MI->getNumOperands() - StartIndex;
52
53 assert((NumVarOps == 1 || NumVarOps == 2) &&
54 "Unsupported number of bits for literal variable");
55
56 O << ' ';
57
58 uint64_t Imm = MI->getOperand(StartIndex).getImm();
59
60 // Handle 64 bit literals.
61 if (NumVarOps == 2) {
62 Imm |= (MI->getOperand(StartIndex + 1).getImm() << 32);
63 }
64
65 // Format and print float values.
66 if (MI->getOpcode() == SPIRV::OpConstantF && IsBitwidth16 == 0) {
67 APFloat FP = NumVarOps == 1 ? APFloat(APInt(32, Imm).bitsToFloat())
68 : APFloat(APInt(64, Imm).bitsToDouble());
69
70 // Print infinity and NaN as hex floats.
71 // TODO: Make sure subnormal numbers are handled correctly as they may also
72 // require hex float notation.
73 if (FP.isInfinity()) {
74 if (FP.isNegative())
75 O << '-';
76 O << "0x1p+128";
77 return;
78 }
79 if (FP.isNaN()) {
80 O << "0x1.8p+128";
81 return;
82 }
83
84 // Format val as a decimal floating point or scientific notation (whichever
85 // is shorter), with enough digits of precision to produce the exact value.
86 O << format("%.*g", std::numeric_limits<double>::max_digits10,
87 FP.convertToDouble());
88
89 return;
90 }
91
92 // Print integer values directly.
93 O << Imm;
94}
95
96void SPIRVInstPrinter::recordOpExtInstImport(const MCInst *MI) {
97 MCRegister Reg = MI->getOperand(0).getReg();
98 auto Name = getSPIRVStringOperand(*MI, 1);
99 auto Set = getExtInstSetFromString(std::move(Name));
100 ExtInstSetIDs.insert({Reg, Set});
101}
102
104 StringRef Annot, const MCSubtargetInfo &STI,
105 raw_ostream &OS) {
106 const unsigned OpCode = MI->getOpcode();
108
109 if (OpCode == SPIRV::OpDecorate) {
110 printOpDecorate(MI, OS);
111 } else if (OpCode == SPIRV::OpExtInstImport) {
112 recordOpExtInstImport(MI);
113 } else if (OpCode == SPIRV::OpExtInst) {
114 printOpExtInst(MI, OS);
115 } else if (OpCode == SPIRV::UNKNOWN_type) {
116 printUnknownType(MI, OS);
117 } else {
118 // Print any extra operands for variadic instructions.
119 const MCInstrDesc &MCDesc = MII.get(OpCode);
120 if (MCDesc.isVariadic()) {
121 const unsigned NumFixedOps = MCDesc.getNumOperands();
122 const unsigned LastFixedIndex = NumFixedOps - 1;
123 const int FirstVariableIndex = NumFixedOps;
124 if (NumFixedOps > 0 && MCDesc.operands()[LastFixedIndex].OperandType ==
126 // For instructions where a custom type (not reg or immediate) comes as
127 // the last operand before the variable_ops. This is usually a StringImm
128 // operand, but there are a few other cases.
129 switch (OpCode) {
130 case SPIRV::OpTypeImage:
131 OS << ' ';
133 MI, FirstVariableIndex, OS);
134 break;
135 case SPIRV::OpVariable:
136 OS << ' ';
137 printOperand(MI, FirstVariableIndex, OS);
138 break;
139 case SPIRV::OpEntryPoint: {
140 // Print the interface ID operands, skipping the name's string
141 // literal.
142 printRemainingVariableOps(MI, NumFixedOps, OS, false, true);
143 break;
144 }
145 case SPIRV::OpMemberDecorate:
146 printRemainingVariableOps(MI, NumFixedOps, OS);
147 break;
148 case SPIRV::OpExecutionMode:
149 case SPIRV::OpExecutionModeId:
150 case SPIRV::OpLoopMerge: {
151 // Print any literals after the OPERAND_UNKNOWN argument normally.
152 printRemainingVariableOps(MI, NumFixedOps, OS);
153 break;
154 }
155 default:
156 break; // printStringImm has already been handled.
157 }
158 } else {
159 // For instructions with no fixed ops or a reg/immediate as the final
160 // fixed operand, we can usually print the rest with "printOperand", but
161 // check for a few cases with custom types first.
162 switch (OpCode) {
163 case SPIRV::OpLoad:
164 case SPIRV::OpStore:
165 OS << ' ';
167 MI, FirstVariableIndex, OS);
168 printRemainingVariableOps(MI, FirstVariableIndex + 1, OS);
169 break;
170 case SPIRV::OpImageSampleImplicitLod:
171 case SPIRV::OpImageSampleDrefImplicitLod:
172 case SPIRV::OpImageSampleProjImplicitLod:
173 case SPIRV::OpImageSampleProjDrefImplicitLod:
174 case SPIRV::OpImageFetch:
175 case SPIRV::OpImageGather:
176 case SPIRV::OpImageDrefGather:
177 case SPIRV::OpImageRead:
178 case SPIRV::OpImageWrite:
179 case SPIRV::OpImageSparseSampleImplicitLod:
180 case SPIRV::OpImageSparseSampleDrefImplicitLod:
181 case SPIRV::OpImageSparseSampleProjImplicitLod:
182 case SPIRV::OpImageSparseSampleProjDrefImplicitLod:
183 case SPIRV::OpImageSparseFetch:
184 case SPIRV::OpImageSparseGather:
185 case SPIRV::OpImageSparseDrefGather:
186 case SPIRV::OpImageSparseRead:
187 case SPIRV::OpImageSampleFootprintNV:
188 OS << ' ';
190 MI, FirstVariableIndex, OS);
191 printRemainingVariableOps(MI, NumFixedOps + 1, OS);
192 break;
193 case SPIRV::OpCopyMemory:
194 case SPIRV::OpCopyMemorySized: {
195 const unsigned NumOps = MI->getNumOperands();
196 for (unsigned i = NumFixedOps; i < NumOps; ++i) {
197 OS << ' ';
199 OS);
200 if (MI->getOperand(i).getImm() & MemoryOperand::Aligned) {
201 assert(i + 1 < NumOps && "Missing alignment operand");
202 OS << ' ';
203 printOperand(MI, i + 1, OS);
204 i += 1;
205 }
206 }
207 break;
208 }
209 case SPIRV::OpConstantI:
210 case SPIRV::OpConstantF:
211 // The last fixed operand along with any variadic operands that follow
212 // are part of the variable value.
213 assert(NumFixedOps > 0 && "Expected at least one fixed operand");
214 printOpConstantVarOps(MI, NumFixedOps - 1, OS);
215 break;
216 case SPIRV::OpCooperativeMatrixMulAddKHR: {
217 const unsigned NumOps = MI->getNumOperands();
218 if (NumFixedOps == NumOps)
219 break;
220
221 OS << ' ';
222 const unsigned MulAddOp = MI->getOperand(FirstVariableIndex).getImm();
223 if (MulAddOp == 0) {
225 OperandCategory::CooperativeMatrixOperandsOperand>(
226 MI, FirstVariableIndex, OS);
227 } else {
228 std::string Buffer;
229 for (unsigned Mask = 0x1;
230 Mask != SPIRV::CooperativeMatrixOperands::
231 MatrixResultBFloat16ComponentsINTEL;
232 Mask <<= 1) {
233 if (MulAddOp & Mask) {
234 if (!Buffer.empty())
235 Buffer += '|';
237 OperandCategory::CooperativeMatrixOperandsOperand, Mask);
238 }
239 }
240 OS << Buffer;
241 }
242 break;
243 }
244 case SPIRV::OpSubgroupMatrixMultiplyAccumulateINTEL: {
245 const unsigned NumOps = MI->getNumOperands();
246 if (NumFixedOps >= NumOps)
247 break;
248 OS << ' ';
249 const unsigned Flags = MI->getOperand(NumOps - 1).getImm();
250 if (Flags == 0) {
252 OperandCategory::MatrixMultiplyAccumulateOperandsOperand>(
253 MI, NumOps - 1, OS);
254 } else {
255 std::string Buffer;
256 for (unsigned Mask = 0x1;
257 Mask <= SPIRV::MatrixMultiplyAccumulateOperands::
258 MatrixBPackedBFloat16INTEL;
259 Mask <<= 1) {
260 if (Flags & Mask) {
261 if (!Buffer.empty())
262 Buffer += '|';
264 OperandCategory::MatrixMultiplyAccumulateOperandsOperand,
265 Mask);
266 }
267 }
268 OS << Buffer;
269 }
270 break;
271 }
272 case SPIRV::OpSDot:
273 case SPIRV::OpUDot:
274 case SPIRV::OpSUDot:
275 case SPIRV::OpSDotAccSat:
276 case SPIRV::OpUDotAccSat:
277 case SPIRV::OpSUDotAccSat: {
278 const unsigned NumOps = MI->getNumOperands();
279 if (NumOps > NumFixedOps) {
280 OS << ' ';
282 MI, NumOps - 1, OS);
283 break;
284 }
285 break;
286 }
287 case SPIRV::OpPredicatedLoadINTEL:
288 case SPIRV::OpPredicatedStoreINTEL: {
289 const unsigned NumOps = MI->getNumOperands();
290 if (NumOps > NumFixedOps) {
291 OS << ' ';
293 MI, NumOps - 1, OS);
294 break;
295 }
296 break;
297 }
298 default:
299 printRemainingVariableOps(MI, NumFixedOps, OS);
300 break;
301 }
302 }
303 }
304 }
305
306 printAnnotation(OS, Annot);
307}
308
310 // The fixed operands have already been printed, so just need to decide what
311 // type of ExtInst operands to print based on the instruction set and number.
312 const MCInstrDesc &MCDesc = MII.get(MI->getOpcode());
313 unsigned NumFixedOps = MCDesc.getNumOperands();
314 const auto NumOps = MI->getNumOperands();
315 if (NumOps == NumFixedOps)
316 return;
317
318 O << ' ';
319
320 // TODO: implement special printing for OpenCLExtInst::vstor*.
321 printRemainingVariableOps(MI, NumFixedOps, O, true);
322}
323
325 // The fixed operands have already been printed, so just need to decide what
326 // type of decoration operands to print based on the Decoration type.
327 const MCInstrDesc &MCDesc = MII.get(MI->getOpcode());
328 unsigned NumFixedOps = MCDesc.getNumOperands();
329
330 if (NumFixedOps != MI->getNumOperands()) {
331 auto DecOp = MI->getOperand(NumFixedOps - 1);
332 auto Dec = static_cast<Decoration::Decoration>(DecOp.getImm());
333
334 O << ' ';
335
336 switch (Dec) {
337 case Decoration::BuiltIn:
339 break;
340 case Decoration::UniformId:
342 break;
343 case Decoration::FuncParamAttr:
345 MI, NumFixedOps, O);
346 break;
347 case Decoration::FPRoundingMode:
349 MI, NumFixedOps, O);
350 break;
351 case Decoration::FPFastMathMode:
353 MI, NumFixedOps, O);
354 break;
355 case Decoration::LinkageAttributes:
356 case Decoration::UserSemantic:
357 printStringImm(MI, NumFixedOps, O);
358 break;
359 case Decoration::HostAccessINTEL:
360 printOperand(MI, NumFixedOps, O);
361 if (NumFixedOps + 1 < MI->getNumOperands()) {
362 O << ' ';
363 printStringImm(MI, NumFixedOps + 1, O);
364 }
365 break;
366 default:
367 printRemainingVariableOps(MI, NumFixedOps, O, true);
368 break;
369 }
370 }
371}
372
374 const auto EnumOperand = MI->getOperand(1);
375 assert(EnumOperand.isImm() &&
376 "second operand of UNKNOWN_type must be opcode!");
377
378 const auto Enumerant = EnumOperand.getImm();
379 const auto NumOps = MI->getNumOperands();
380
381 // Print the opcode using the spirv-as unknown opcode syntax
382 O << "OpUnknown(" << Enumerant << ", " << NumOps << ") ";
383
384 // The result ID must be printed after the opcode when using this syntax
385 printOperand(MI, 0, O);
386
387 O << " ";
388
389 const MCInstrDesc &MCDesc = MII.get(MI->getOpcode());
390 unsigned NumFixedOps = MCDesc.getNumOperands();
391 if (NumOps == NumFixedOps)
392 return;
393
394 // Print the rest of the operands
395 printRemainingVariableOps(MI, NumFixedOps, O, true);
396}
397
398void SPIRVInstPrinter::printOperand(const MCInst *MI, unsigned OpNo,
399 raw_ostream &O) {
400 if (OpNo < MI->getNumOperands()) {
401 const MCOperand &Op = MI->getOperand(OpNo);
402 if (Op.isReg())
403 O << '%' << (getIDFromRegister(Op.getReg().id()) + 1);
404 else if (Op.isImm()) {
405 int64_t Imm = Op.getImm();
406 // For OpVectorShuffle:
407 // A Component literal may also be FFFFFFFF, which means the corresponding
408 // result component has no source and is undefined.
409 // LLVM representation of poison/undef becomes -1 when lowered to MI.
410 if (MI->getOpcode() == SPIRV::OpVectorShuffle && Imm == -1)
411 O << "0xFFFFFFFF";
412 else
413 O << formatImm(Imm);
414 } else if (Op.isDFPImm())
415 O << formatImm((double)Op.getDFPImm());
416 else if (Op.isExpr())
417 MAI.printExpr(O, *Op.getExpr());
418 else
419 llvm_unreachable("Unexpected operand type");
420 }
421}
422
423void SPIRVInstPrinter::printStringImm(const MCInst *MI, unsigned OpNo,
424 raw_ostream &O) {
425 const unsigned NumOps = MI->getNumOperands();
426 unsigned StrStartIndex = OpNo;
427 while (StrStartIndex < NumOps) {
428 if (MI->getOperand(StrStartIndex).isReg())
429 break;
430
431 std::string Str = getSPIRVStringOperand(*MI, StrStartIndex);
432 if (StrStartIndex != OpNo)
433 O << ' '; // Add a space if we're starting a new string/argument.
434 O << '"';
435 for (char c : Str) {
436 // Escape ", \n characters (might break for complex UTF-8).
437 if (c == '\n') {
438 O.write("\\n", 2);
439 } else {
440 if (c == '"')
441 O.write('\\');
442 O.write(c);
443 }
444 }
445 O << '"';
446
447 unsigned numOpsInString = (Str.size() / 4) + 1;
448 StrStartIndex += numOpsInString;
449
450 // Check for final Op of "OpDecorate %x %stringImm %linkageAttribute".
451 if (MI->getOpcode() == SPIRV::OpDecorate &&
452 MI->getOperand(1).getImm() ==
453 static_cast<unsigned>(Decoration::LinkageAttributes)) {
454 O << ' ';
456 MI, StrStartIndex, O);
457 break;
458 }
459 }
460}
461
462void SPIRVInstPrinter::printExtension(const MCInst *MI, unsigned OpNo,
463 raw_ostream &O) {
464 auto SetReg = MI->getOperand(2).getReg();
465 auto Set = ExtInstSetIDs[SetReg];
466 auto Op = MI->getOperand(OpNo).getImm();
467 O << getExtInstName(Set, Op);
468}
469
470template <OperandCategory::OperandCategory category>
472 raw_ostream &O) {
473 if (OpNo < MI->getNumOperands()) {
474 O << getSymbolicOperandMnemonic(category, MI->getOperand(OpNo).getImm());
475 }
476}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file declares a class to represent arbitrary precision floating point values and provide a varie...
IRTranslator LLVM IR MI
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
Class for arbitrary precision integers.
Definition APInt.h:78
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:222
const MCInstrInfo & MII
void printAnnotation(raw_ostream &OS, StringRef Annot)
Utility function for printing annotations.
const MCAsmInfo & MAI
format_object< int64_t > formatImm(int64_t Value) const
Utility function to print immediates in decimal or hex.
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:188
Describe properties that are true of each instruction in the target description file.
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
ArrayRef< MCOperandInfo > operands() const
bool isVariadic() const
Return true if this instruction can have a variable number of operands.
Instances of this class represent operands of the MCInst class.
Definition MCInst.h:40
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:33
Generic base class for all target subtargets.
void printExtension(const MCInst *MI, unsigned OpNo, raw_ostream &O)
void printStringImm(const MCInst *MI, unsigned OpNo, raw_ostream &O)
void printInstruction(const MCInst *MI, uint64_t Address, raw_ostream &O)
void printInst(const MCInst *MI, uint64_t Address, StringRef Annot, const MCSubtargetInfo &STI, raw_ostream &OS) override
Print the specified MCInst to the specified raw_ostream.
void printOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O)
void printOpExtInst(const MCInst *MI, raw_ostream &O)
void printOpConstantVarOps(const MCInst *MI, unsigned StartIndex, raw_ostream &O)
void printSymbolicOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O)
void printRemainingVariableOps(const MCInst *MI, unsigned StartIndex, raw_ostream &O, bool SkipFirstSpace=false, bool SkipImmediates=false)
void printOpDecorate(const MCInst *MI, raw_ostream &O)
void printUnknownType(const MCInst *MI, raw_ostream &O)
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned getIDFromRegister(unsigned Reg)
This is an optimization pass for GlobalISel generic memory operations.
std::string getExtInstName(SPIRV::InstructionSet::InstructionSet Set, uint32_t InstructionNumber)
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
std::string getSPIRVStringOperand(const InstType &MI, unsigned StartIndex)
SPIRV::InstructionSet::InstructionSet getExtInstSetFromString(std::string SetName)
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:118
std::string getSymbolicOperandMnemonic(SPIRV::OperandCategory::OperandCategory Category, int32_t Value)
DWARFExpression::Operation Op