1 /*========================== begin_copyright_notice ============================
2 
3 Copyright (C) 2017-2021 Intel Corporation
4 
5 SPDX-License-Identifier: MIT
6 
7 ============================= end_copyright_notice ===========================*/
8 
9 /*========================== begin_copyright_notice ============================
10 
11 This file is distributed under the University of Illinois Open Source License.
12 See LICENSE.TXT for details.
13 
14 ============================= end_copyright_notice ===========================*/
15 
16 /*========================== begin_copyright_notice ============================
17 
18 Copyright (C) 2014 Advanced Micro Devices, Inc. All rights reserved.
19 
20 Permission is hereby granted, free of charge, to any person obtaining a
21 copy of this software and associated documentation files (the "Software"),
22 to deal with the Software without restriction, including without limitation
23 the rights to use, copy, modify, merge, publish, distribute, sublicense,
24 and/or sell copies of the Software, and to permit persons to whom the
25 Software is furnished to do so, subject to the following conditions:
26 
27 Redistributions of source code must retain the above copyright notice,
28 this list of conditions and the following disclaimers.
29 Redistributions in binary form must reproduce the above copyright notice,
30 this list of conditions and the following disclaimers in the documentation
31 and/or other materials provided with the distribution.
32 Neither the names of Advanced Micro Devices, Inc., nor the names of its
33 contributors may be used to endorse or promote products derived from this
34 Software without specific prior written permission.
35 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
36 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
37 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
38 CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
39 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
40 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH
41 THE SOFTWARE.
42 
43 ============================= end_copyright_notice ===========================*/
44 
45 // This file implements SPIR-V stream class.
46 
47 #include "SPIRVDebug.h"
48 #include "SPIRVStream.h"
49 #include "SPIRVFunction.h"
50 #include "SPIRVInstruction.h"
51 #include "SPIRVDebugInfoExt.h"
52 #include "Probe/Assertion.h"
53 
54 namespace igc_spv{
55 
SPIRVDecoder(std::istream & InputStream,SPIRVFunction & F)56 SPIRVDecoder::SPIRVDecoder(std::istream &InputStream, SPIRVFunction &F)
57   :IS(InputStream), M(*F.getModule()), WordCount(0), OpCode(OpNop),
58    Scope(&F){}
59 
SPIRVDecoder(std::istream & InputStream,SPIRVBasicBlock & BB)60 SPIRVDecoder::SPIRVDecoder(std::istream &InputStream, SPIRVBasicBlock &BB)
61   :IS(InputStream), M(*BB.getModule()), WordCount(0), OpCode(OpNop),
62    Scope(&BB){}
63 
64 void
setScope(SPIRVEntry * TheScope)65 SPIRVDecoder::setScope(SPIRVEntry *TheScope) {
66   IGC_ASSERT(TheScope && (TheScope->getOpCode() == OpFunction ||
67       TheScope->getOpCode() == OpLabel));
68   Scope = TheScope;
69 }
70 
71 template<>
DecodeBinary(const SPIRVDecoder & I,bool & V)72 const SPIRVDecoder& DecodeBinary(const SPIRVDecoder& I, bool &V) {
73    SPIRVWord W;
74    I.IS.read(reinterpret_cast<char*>(&W), sizeof(W));
75    V = (W == 0) ? false : true;
76    return I;
77 }
78 
79 template<>
80 const SPIRVDecoder&
DecodeBinary(const SPIRVDecoder & I,SPIRVWord & V)81 DecodeBinary(const SPIRVDecoder& I, SPIRVWord &V) {
82    I.IS.read(reinterpret_cast<char*>(&V), sizeof(V));
83    return I;
84 }
85 
86 template<typename T>
DecodeBinary(const SPIRVDecoder & I,T & V)87 const SPIRVDecoder& DecodeBinary(const SPIRVDecoder& I, T &V) {
88    SPIRVWord W;
89    DecodeBinary(I,W);
90    V = static_cast<T>(W);
91    return I;
92 }
93 
94 //explicitly instantiate DecodeBinary for enum types
95 #define INSTANTIATE_DECODER_BINARY(Type) \
96   template \
97   const SPIRVDecoder& DecodeBinary \
98   (const SPIRVDecoder& I, Type &V);
99 
100 INSTANTIATE_DECODER_BINARY(enum igc_spv::StorageClass)
INSTANTIATE_DECODER_BINARY(enum igc_spv::Dim)101 INSTANTIATE_DECODER_BINARY(enum igc_spv::Dim)
102 INSTANTIATE_DECODER_BINARY(enum igc_spv::AccessQualifier)
103 INSTANTIATE_DECODER_BINARY(enum igc_spv::Scope)
104 INSTANTIATE_DECODER_BINARY(enum igc_spv::ExecutionModel)
105 INSTANTIATE_DECODER_BINARY(enum igc_spv::ExecutionMode)
106 INSTANTIATE_DECODER_BINARY(enum igc_spv::AddressingModel)
107 INSTANTIATE_DECODER_BINARY(enum igc_spv::MemoryModel)
108 INSTANTIATE_DECODER_BINARY(enum igc_spv::SpvSourceLanguage)
109 INSTANTIATE_DECODER_BINARY(enum igc_spv::Capability)
110 INSTANTIATE_DECODER_BINARY(enum igc_spv::SPIRVVersionSupported)
111 INSTANTIATE_DECODER_BINARY(enum igc_spv::SPIRVGeneratorKind)
112 INSTANTIATE_DECODER_BINARY(enum igc_spv::SPIRVInstructionSchemaKind)
113 #undef SPIRV_DEF_DEC
114 
115 
116 template<class T>
117 const SPIRVDecoder&
118 decode(const SPIRVDecoder& I, T &V) {
119   return DecodeBinary(I, V);
120 }
121 
122 #define SPIRV_DEF_DEC(Type)                                      \
123 const SPIRVDecoder& operator>>(const SPIRVDecoder& I, Type &V) { \
124   return decode(I, V);                                           \
125 }
126 
127 SPIRV_DEF_DEC(Op)
SPIRV_DEF_DEC(Decoration)128 SPIRV_DEF_DEC(Decoration)
129 SPIRV_DEF_DEC(OCLExtOpKind)
130 SPIRV_DEF_DEC(OCLExtOpDbgKind)
131 #undef SPIRV_DEF_DEC
132 
133 // Read a string with padded 0's at the end so that they form a stream of
134 // words.
135 const SPIRVDecoder&
136 operator>>(const SPIRVDecoder&I, std::string& Str) {
137   uint64_t Count = 0;
138   char Ch;
139   while ((!I.IS.eof() && I.IS.get(Ch)) && Ch != '\0') {
140     Str += Ch;
141     ++Count;
142   }
143   Count = (Count + 1) % 4;
144   Count = Count ? 4 - Count : 0;
145   for (;Count; --Count) {
146     (!I.IS.eof() && I.IS.get(Ch));
147     IGC_ASSERT(Ch == '\0' && "Invalid string in SPIRV");
148   }
149   return I;
150 }
151 
152 bool
getWordCountAndOpCode()153 SPIRVDecoder::getWordCountAndOpCode() {
154   if (IS.eof()) {
155     WordCount = 0;
156     OpCode = OpNop;
157     return false;
158   }
159 
160   SPIRVWord WordCountAndOpCode;
161   *this >> WordCountAndOpCode;
162   WordCount = WordCountAndOpCode >> 16;
163   OpCode = static_cast<Op>(WordCountAndOpCode & 0xFFFF);
164 
165   IGC_ASSERT_MESSAGE(false == IS.bad(), "SPIRV stream is bad");
166   if (IS.fail()) {
167     WordCount = 0;
168     OpCode = OpNop;
169     return false;
170   }
171   return true;
172 }
173 
174 SPIRVEntry *
getEntry()175 SPIRVDecoder::getEntry() {
176   if (WordCount == 0 || OpCode == OpNop)
177     return NULL;
178   SPIRVEntry *Entry = SPIRVEntry::create(OpCode);
179   if (Entry) {
180     Entry->setModule(&M);
181     Entry->setWordCount(WordCount);
182     IS >> *Entry;
183 
184     if (M.getErrorLog().getErrorCode() == SPIRVEC_UnsupportedSPIRVOpcode)
185       return nullptr;
186 
187     if ((isModuleScopeAllowedOpCode(OpCode) && !Scope) ||
188       // No need to attach scope to debug info extension operations
189       (Entry->hasNoScope()))
190     {}
191     else
192       Entry->setScope(Scope);
193 
194     IGC_ASSERT_MESSAGE(false == IS.bad(), "SPIRV stream fails");
195     IGC_ASSERT_MESSAGE(false == IS.fail(), "SPIRV stream fails");
196     M.add(Entry);
197   }
198   else {
199     M.getErrorLog().setError(SPIRVEC_UnsupportedSPIRVOpcode,
200       "IGC SPIRV Consumer does not support the following opcode: " + std::to_string(OpCode) + "\n");
201   }
202   return Entry;
203 }
204 
205 void
validate() const206 SPIRVDecoder::validate()const {
207   IGC_ASSERT_MESSAGE(OpCode != OpNop, "Invalid op code");
208   IGC_ASSERT_MESSAGE(WordCount, "Invalid word count");
209   IGC_ASSERT_MESSAGE(!IS.bad(), "Bad iInput stream");
210 }
211 
212 // Read the next word from the stream and if OpCode matches the argument,
213 // decode the whole instruction. Multiple such instructions are possible. If
214 // OpCode doesn't match the argument, set position of the next character to be
215 // extracted from the stream to the beginning of the non-matching instruction.
216 // Returns vector of extracted instructions.
217 // Used to decode SPIRVTypeStructContinuedINTEL,
218 // SPIRVConstantCompositeContinuedINTEL and
219 // SPIRVSpecConstantCompositeContinuedINTEL.
220 std::vector<SPIRVEntry*>
getContinuedInstructions(const Op ContinuedOpCode)221 SPIRVDecoder::getContinuedInstructions(const Op ContinuedOpCode) {
222     std::vector<SPIRVEntry*> ContinuedInst;
223     std::streampos Pos = IS.tellg(); // remember position
224     getWordCountAndOpCode();
225     while (OpCode == ContinuedOpCode) {
226         SPIRVEntry* Entry = getEntry();
227         assert(Entry && "Failed to decode entry! Invalid instruction!");
228         M.add(Entry);
229         ContinuedInst.push_back(Entry);
230         Pos = IS.tellg();
231         getWordCountAndOpCode();
232     }
233     IS.seekg(Pos); // restore position
234     return ContinuedInst;
235 }
236 
237 }
238