Debian Codegraph @

llvm-project/llvm/projects/llvm-spirv/lib/SPIRV/libSPIRV/SPIRVStream.cpp

raw
1 //===- SPIRVStream.cpp - Class to represent a SPIR-V Stream -----*- C++ -*-===//
2 //
3 // The LLVM/SPIRV Translator
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 // Copyright (c) 2014 Advanced Micro Devices, Inc. All rights reserved.
9 //
10 // Permission is hereby granted, free of charge, to any person obtaining a
11 // copy of this software and associated documentation files (the "Software"),
12 // to deal with the Software without restriction, including without limitation
13 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
14 // and/or sell copies of the Software, and to permit persons to whom the
15 // Software is furnished to do so, subject to the following conditions:
16 //
17 // Redistributions of source code must retain the above copyright notice,
18 // this list of conditions and the following disclaimers.
19 // Redistributions in binary form must reproduce the above copyright notice,
20 // this list of conditions and the following disclaimers in the documentation
21 // and/or other materials provided with the distribution.
22 // Neither the names of Advanced Micro Devices, Inc., nor the names of its
23 // contributors may be used to endorse or promote products derived from this
24 // Software without specific prior written permission.
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28 // CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH
31 // THE SOFTWARE.
32 //
33 //===----------------------------------------------------------------------===//
34 /// \file
35 ///
36 /// This file implements SPIR-V stream class.
37 ///
38 //===----------------------------------------------------------------------===//
39 #include "SPIRVStream.h"
40 #include "SPIRVDebug.h"
41 #include "SPIRVFunction.h"
42 #include "SPIRVInstruction.h"
43 #include "SPIRVNameMapEnum.h"
44 #include "SPIRVOpCode.h"
45
46 #include <limits> // std::numeric_limits
47
48 namespace SPIRV {
49
50 /// Write string with quote. Replace " with \".
51 static void writeQuotedString(spv_ostream &O, const std::string &Str) {
52 O << '"';
53 for (auto I : Str) {
54 if (I == '"')
55 O << '\\';
56 O << I;
57 }
58 O << '"';
59 }
60
61 /// Read quoted string. Replace \" with ".
62 static void readQuotedString(std::istream &IS, std::string &Str) {
63 char Ch = ' ';
64 char PreCh = ' ';
65 while (IS >> Ch && Ch != '"')
66 ;
67
68 if (IS >> PreCh && PreCh != '"') {
69 while (IS >> Ch) {
70 if (Ch == '"') {
71 if (PreCh != '\\') {
72 Str += PreCh;
73 break;
74 } else
75 PreCh = Ch;
76 } else {
77 Str += PreCh;
78 PreCh = Ch;
79 }
80 }
81 }
82 }
83
84 #ifdef _SPIRV_SUPPORT_TEXT_FMT
85 bool SPIRVUseTextFormat = false;
86 #endif
87
88 SPIRVDecoder::SPIRVDecoder(std::istream &InputStream, SPIRVFunction &F)
89 : IS(InputStream), M(*F.getModule()), WordCount(0), OpCode(OpNop),
90 Scope(&F) {}
91
92 SPIRVDecoder::SPIRVDecoder(std::istream &InputStream, SPIRVBasicBlock &BB)
93 : IS(InputStream), M(*BB.getModule()), WordCount(0), OpCode(OpNop),
94 Scope(&BB) {}
95
96 void SPIRVDecoder::setScope(SPIRVEntry *TheScope) {
97 assert(TheScope && (TheScope->getOpCode() == OpFunction ||
98 TheScope->getOpCode() == OpLabel));
99 Scope = TheScope;
100 }
101
102 template <class T> const SPIRVDecoder &decode(const SPIRVDecoder &I, T &V) {
103 #ifdef _SPIRV_SUPPORT_TEXT_FMT
104 if (SPIRVUseTextFormat) {
105 std::string W;
106 I.IS >> W;
107 V = getNameMap(V).rmap(W);
108 SPIRVDBG(spvdbgs() << "Read word: W = " << W << " V = " << V << '\n');
109 return I;
110 }
111 #endif
112 return decodeBinary(I, V);
113 }
114
115 template <class T> const SPIRVEncoder &encode(const SPIRVEncoder &O, T V) {
116 #ifdef _SPIRV_SUPPORT_TEXT_FMT
117 if (SPIRVUseTextFormat) {
118 O.OS << getNameMap(V).map(V) << " ";
119 return O;
120 }
121 #endif
122 return O << static_cast<SPIRVWord>(V);
123 }
124
125 template <>
126 const SPIRVEncoder &operator<<(const SPIRVEncoder &O, SPIRVType *P) {
127 if (!P->hasId() && P->getOpCode() == OpTypeForwardPointer)
128 return O << static_cast<SPIRVTypeForwardPointer *>(
129 static_cast<SPIRVEntry *>(P))
130 ->getPointerId();
131 return O << P->getId();
132 }
133
134 #define SPIRV_DEF_ENCDEC(Type) \
135 const SPIRVDecoder &operator>>(const SPIRVDecoder &I, Type &V) { \
136 return decode(I, V); \
137 } \
138 const SPIRVEncoder &operator<<(const SPIRVEncoder &O, Type V) { \
139 return encode(O, V); \
140 }
141
142 SPIRV_DEF_ENCDEC(Op)
143 SPIRV_DEF_ENCDEC(Capability)
144 SPIRV_DEF_ENCDEC(Decoration)
145 SPIRV_DEF_ENCDEC(OCLExtOpKind)
146 SPIRV_DEF_ENCDEC(SPIRVDebugExtOpKind)
147 SPIRV_DEF_ENCDEC(NonSemanticAuxDataOpKind)
148 SPIRV_DEF_ENCDEC(NamedMaximumNumberOfRegisters)
149 SPIRV_DEF_ENCDEC(InitializationModeQualifier)
150 SPIRV_DEF_ENCDEC(HostAccessQualifier)
151 SPIRV_DEF_ENCDEC(LinkageType)
152
153 // Read a string with padded 0's at the end so that they form a stream of
154 // words.
155 const SPIRVDecoder &operator>>(const SPIRVDecoder &I, std::string &Str) {
156 #ifdef _SPIRV_SUPPORT_TEXT_FMT
157 if (SPIRVUseTextFormat) {
158 readQuotedString(I.IS, Str);
159 SPIRVDBG(spvdbgs() << "Read string: \"" << Str << "\"\n");
160 return I;
161 }
162 #endif
163
164 uint64_t Count = 0;
165 char Ch;
166 while (I.IS.get(Ch) && Ch != '\0') {
167 Str += Ch;
168 ++Count;
169 }
170 Count = (Count + 1) % 4;
171 Count = Count ? 4 - Count : 0;
172 for (; Count; --Count) {
173 I.IS >> Ch;
174 assert(Ch == '\0' && "Invalid string in SPIRV");
175 }
176 SPIRVDBG(spvdbgs() << "Read string: \"" << Str << "\"\n");
177 return I;
178 }
179
180 // Write a string with padded 0's at the end so that they form a stream of
181 // words.
182 const SPIRVEncoder &operator<<(const SPIRVEncoder &O, const std::string &Str) {
183 #ifdef _SPIRV_SUPPORT_TEXT_FMT
184 if (SPIRVUseTextFormat) {
185 writeQuotedString(O.OS, Str);
186 O.OS << " ";
187 return O;
188 }
189 #endif
190
191 size_t L = Str.length();
192 O.OS.write(Str.c_str(), L);
193 char Zeros[4] = {0, 0, 0, 0};
194 O.OS.write(Zeros, 4 - L % 4);
195 return O;
196 }
197
198 bool SPIRVDecoder::getWordCountAndOpCode() {
199 if (IS.eof()) {
200 WordCount = 0;
201 OpCode = OpNop;
202 SPIRVDBG(spvdbgs() << "[SPIRVDecoder] getWordCountAndOpCode EOF "
203 << WordCount << " " << OpCode << '\n');
204 return false;
205 }
206 #ifdef _SPIRV_SUPPORT_TEXT_FMT
207 if (SPIRVUseTextFormat) {
208 *this >> WordCount;
209 assert(!IS.bad() && "SPIRV stream is bad");
210 if (IS.fail()) {
211 WordCount = 0;
212 OpCode = OpNop;
213 SPIRVDBG(spvdbgs() << "[SPIRVDecoder] getWordCountAndOpCode FAIL "
214 << WordCount << " " << OpCode << '\n');
215 return false;
216 }
217 *this >> OpCode;
218 } else {
219 #endif
220 SPIRVWord WordCountAndOpCode;
221 *this >> WordCountAndOpCode;
222 WordCount = WordCountAndOpCode >> 16;
223 OpCode = static_cast<Op>(WordCountAndOpCode & 0xFFFF);
224 #ifdef _SPIRV_SUPPORT_TEXT_FMT
225 }
226 #endif
227 assert(!IS.bad() && "SPIRV stream is bad");
228 if (IS.fail()) {
229 WordCount = 0;
230 OpCode = OpNop;
231 SPIRVDBG(spvdbgs() << "[SPIRVDecoder] getWordCountAndOpCode FAIL "
232 << WordCount << " " << OpCode << '\n');
233 return false;
234 }
235 SPIRVDBG(spvdbgs() << "[SPIRVDecoder] getWordCountAndOpCode " << WordCount
236 << " " << OpCodeNameMap::map(OpCode) << '\n');
237 return true;
238 }
239
240 SPIRVEntry *SPIRVDecoder::getEntry() {
241 if (WordCount == 0 || OpCode == OpNop)
242 return nullptr;
243 SPIRVEntry *Entry = SPIRVEntry::create(OpCode);
244 assert(Entry);
245 Entry->setModule(&M);
246 if (isModuleScopeAllowedOpCode(OpCode) && !Scope) {
247 } else
248 Entry->setScope(Scope);
249 Entry->setWordCount(WordCount);
250 if (OpCode != OpLine)
251 Entry->setLine(M.getCurrentLine());
252 if (!Entry->isExtInst(SPIRVEIS_NonSemantic_Shader_DebugInfo_100,
253 SPIRVDebug::DebugLine) &&
254 !Entry->isExtInst(SPIRVEIS_NonSemantic_Shader_DebugInfo_200,
255 SPIRVDebug::DebugLine))
256 Entry->setDebugLine(M.getCurrentDebugLine());
257
258 IS >> *Entry;
259 if (Entry->isEndOfBlock() || OpCode == OpNoLine)
260 M.setCurrentLine(nullptr);
261 if (Entry->isEndOfBlock() ||
262 Entry->isExtInst(SPIRVEIS_NonSemantic_Shader_DebugInfo_100,
263 SPIRVDebug::DebugNoLine) ||
264 Entry->isExtInst(SPIRVEIS_NonSemantic_Shader_DebugInfo_200,
265 SPIRVDebug::DebugNoLine))
266 M.setCurrentDebugLine(nullptr);
267
268 if (OpExtension == OpCode) {
269 auto *OpExt = static_cast<SPIRVExtension *>(Entry);
270 ExtensionID ExtID = {};
271 bool ExtIsKnown = SPIRVMap<ExtensionID, std::string>::rfind(
272 OpExt->getExtensionName(), &ExtID);
273 if (!M.getErrorLog().checkError(
274 ExtIsKnown, SPIRVEC_InvalidModule,
275 "input SPIR-V module uses unknown extension '" +
276 OpExt->getExtensionName() + "'")) {
277 M.setInvalid();
278 }
279
280 if (!M.getErrorLog().checkError(
281 M.isAllowedToUseExtension(ExtID), SPIRVEC_InvalidModule,
282 "input SPIR-V module uses extension '" + OpExt->getExtensionName() +
283 "' which were disabled by --spirv-ext option")) {
284 M.setInvalid();
285 }
286 }
287
288 if (!M.getErrorLog().checkError(Entry->isImplemented(),
289 SPIRVEC_UnimplementedOpCode,
290 std::to_string(Entry->getOpCode()))) {
291 M.setInvalid();
292 }
293
294 assert(!IS.bad() && !IS.fail() && "SPIRV stream fails");
295 return Entry;
296 }
297
298 void SPIRVDecoder::validate() const {
299 assert(OpCode != OpNop && "Invalid op code");
300 assert(WordCount && "Invalid word count");
301 assert(!IS.bad() && "Bad iInput stream");
302 }
303
304 // Skip \param n words in SPIR-V binary stream.
305 // In case of SPIR-V text format always skip until the end of the line.
306 void SPIRVDecoder::ignore(size_t N) {
307 #ifdef _SPIRV_SUPPORT_TEXT_FMT
308 if (SPIRVUseTextFormat) {
309 IS.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
310 return;
311 }
312 #endif
313 IS.ignore(N * sizeof(SPIRVWord));
314 }
315
316 void SPIRVDecoder::ignoreInstruction() { ignore(WordCount - 1); }
317
318 spv_ostream &operator<<(spv_ostream &O, const SPIRVNL &E) {
319 #ifdef _SPIRV_SUPPORT_TEXT_FMT
320 if (SPIRVUseTextFormat)
321 O << '\n';
322 #endif
323 return O;
324 }
325
326 // Read the next word from the stream and if OpCode matches the argument,
327 // decode the whole instruction. Multiple such instructions are possible. If
328 // OpCode doesn't match the argument, set position of the next character to be
329 // extracted from the stream to the beginning of the non-matching instruction.
330 // Returns vector of extracted instructions.
331 // Used to decode SPIRVTypeStructContinuedINTEL,
332 // SPIRVConstantCompositeContinuedINTEL and
333 // SPIRVSpecConstantCompositeContinuedINTEL.
334 std::vector<SPIRVEntry *>
335 SPIRVDecoder::getContinuedInstructions(const spv::Op ContinuedOpCode) {
336 std::vector<SPIRVEntry *> ContinuedInst;
337 std::streampos Pos = IS.tellg(); // remember position
338 getWordCountAndOpCode();
339 while (OpCode == ContinuedOpCode) {
340 SPIRVEntry *Entry = getEntry();
341 assert(Entry && "Failed to decode entry! Invalid instruction!");
342 M.add(Entry);
343 ContinuedInst.push_back(Entry);
344 Pos = IS.tellg();
345 getWordCountAndOpCode();
346 }
347 IS.seekg(Pos); // restore position
348 return ContinuedInst;
349 }
350
351 std::vector<SPIRVEntry *> SPIRVDecoder::getSourceContinuedInstructions() {
352 std::vector<SPIRVEntry *> ContinuedInst;
353 std::streampos Pos = IS.tellg(); // remember position
354 getWordCountAndOpCode();
355 while (OpCode == OpExtInst) {
356 SPIRVEntry *Entry = getEntry();
357 assert(Entry && "Failed to decode entry! Invalid instruction!");
358 SPIRVExtInst *Inst = static_cast<SPIRVExtInst *>(Entry);
359 if (Inst->getExtOp() != SPIRVDebug::Instruction::SourceContinued) {
360 IS.seekg(Pos); // restore position
361 return ContinuedInst;
362 }
363 M.add(Entry);
364 ContinuedInst.push_back(Entry);
365 Pos = IS.tellg();
366 getWordCountAndOpCode();
367 }
368 IS.seekg(Pos); // restore position
369 return ContinuedInst;
370 }
371
372 } // namespace SPIRV