1 // Copyright (c) 2014-2018 The Khronos Group Inc.
3 // Permission is hereby granted, free of charge, to any person obtaining a copy
4 // of this software and/or associated documentation files (the "Materials"),
5 // to deal in the Materials without restriction, including without limitation
6 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
7 // and/or sell copies of the Materials, and to permit persons to whom the
8 // Materials are furnished to do so, subject to the following conditions:
10 // The above copyright notice and this permission notice shall be included in
11 // all copies or substantial portions of the Materials.
13 // MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS
14 // STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND
15 // HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/
17 // THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 // FROM,OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS
29 #include <unordered_map>
33 #include "jsoncpp/dist/json/json.h"
35 #include "jsonToSpirv.h"
39 // The set of objects that hold all the instruction/operand
40 // parameterization information.
41 InstructionValues InstructionDesc;
43 // Note: There is no entry for OperandOpcode. Use InstructionDesc instead.
44 EnumDefinition OperandClassParams[OperandOpcode];
45 EnumValues SourceLanguageParams;
46 EnumValues ExecutionModelParams;
47 EnumValues AddressingParams;
48 EnumValues MemoryParams;
49 EnumValues ExecutionModeParams;
50 EnumValues StorageParams;
51 EnumValues SamplerAddressingModeParams;
52 EnumValues SamplerFilterModeParams;
53 EnumValues ImageFormatParams;
54 EnumValues ImageChannelOrderParams;
55 EnumValues ImageChannelDataTypeParams;
56 EnumValues ImageOperandsParams;
57 EnumValues FPFastMathParams;
58 EnumValues FPRoundingModeParams;
59 EnumValues LinkageTypeParams;
60 EnumValues DecorationParams;
61 EnumValues BuiltInParams;
62 EnumValues DimensionalityParams;
63 EnumValues FuncParamAttrParams;
64 EnumValues AccessQualifierParams;
65 EnumValues GroupOperationParams;
66 EnumValues LoopControlParams;
67 EnumValues SelectionControlParams;
68 EnumValues FunctionControlParams;
69 EnumValues MemorySemanticsParams;
70 EnumValues MemoryAccessParams;
71 EnumValues ScopeParams;
72 EnumValues KernelEnqueueFlagsParams;
73 EnumValues KernelProfilingInfoParams;
74 EnumValues CapabilityParams;
76 std::pair<bool, std::string> ReadFile(const std::string& path)
78 std::ifstream fstream(path, std::ios::in);
81 fstream.seekg(0, std::ios::end);
82 contents.reserve((unsigned int)fstream.tellg());
83 fstream.seekg(0, std::ios::beg);
84 contents.assign((std::istreambuf_iterator<char>(fstream)),
85 std::istreambuf_iterator<char>());
86 return std::make_pair(true, contents);
88 return std::make_pair(false, "");
91 struct ClassOptionality {
96 // Converts the |operandKind| and |quantifier| pair used to describe operands
97 // in the JSON grammar to OperandClass and optionality used in this repo.
98 ClassOptionality ToOperandClassAndOptionality(const std::string& operandKind, const std::string& quantifier)
100 assert(quantifier.empty() || quantifier == "?" || quantifier == "*");
102 if (operandKind == "IdRef") {
103 if (quantifier.empty())
104 return {OperandId, false};
105 else if (quantifier == "?")
106 return {OperandId, true};
108 return {OperandVariableIds, false};
109 } else if (operandKind == "LiteralInteger") {
110 if (quantifier.empty())
111 return {OperandLiteralNumber, false};
112 if (quantifier == "?")
113 return {OperandOptionalLiteral, true};
115 return {OperandVariableLiterals, false};
116 } else if (operandKind == "LiteralString") {
117 if (quantifier.empty())
118 return {OperandLiteralString, false};
119 else if (quantifier == "?")
120 return {OperandLiteralString, true};
122 return {OperandVariableLiteralStrings, false};
124 } else if (operandKind == "PairLiteralIntegerIdRef") {
125 // Used by OpSwitch in the grammar
126 return {OperandVariableLiteralId, false};
127 } else if (operandKind == "PairIdRefLiteralInteger") {
128 // Used by OpGroupMemberDecorate in the grammar
129 return {OperandVariableIdLiteral, false};
130 } else if (operandKind == "PairIdRefIdRef") {
131 // Used by OpPhi in the grammar
132 return {OperandVariableIds, false};
134 OperandClass type = OperandNone;
135 if (operandKind == "IdMemorySemantics" || operandKind == "MemorySemantics") {
136 type = OperandMemorySemantics;
137 } else if (operandKind == "IdScope" || operandKind == "Scope") {
139 } else if (operandKind == "LiteralExtInstInteger") {
140 type = OperandLiteralNumber;
141 } else if (operandKind == "LiteralSpecConstantOpInteger") {
142 type = OperandLiteralNumber;
143 } else if (operandKind == "LiteralContextDependentNumber") {
144 type = OperandVariableLiterals;
145 } else if (operandKind == "SourceLanguage") {
146 type = OperandSource;
147 } else if (operandKind == "ExecutionModel") {
148 type = OperandExecutionModel;
149 } else if (operandKind == "AddressingModel") {
150 type = OperandAddressing;
151 } else if (operandKind == "MemoryModel") {
152 type = OperandMemory;
153 } else if (operandKind == "ExecutionMode") {
154 type = OperandExecutionMode;
155 } else if (operandKind == "StorageClass") {
156 type = OperandStorage;
157 } else if (operandKind == "Dim") {
158 type = OperandDimensionality;
159 } else if (operandKind == "SamplerAddressingMode") {
160 type = OperandSamplerAddressingMode;
161 } else if (operandKind == "SamplerFilterMode") {
162 type = OperandSamplerFilterMode;
163 } else if (operandKind == "ImageFormat") {
164 type = OperandSamplerImageFormat;
165 } else if (operandKind == "ImageChannelOrder") {
166 type = OperandImageChannelOrder;
167 } else if (operandKind == "ImageChannelDataType") {
168 type = OperandImageChannelDataType;
169 } else if (operandKind == "FPRoundingMode") {
170 type = OperandFPRoundingMode;
171 } else if (operandKind == "LinkageType") {
172 type = OperandLinkageType;
173 } else if (operandKind == "AccessQualifier") {
174 type = OperandAccessQualifier;
175 } else if (operandKind == "FunctionParameterAttribute") {
176 type = OperandFuncParamAttr;
177 } else if (operandKind == "Decoration") {
178 type = OperandDecoration;
179 } else if (operandKind == "BuiltIn") {
180 type = OperandBuiltIn;
181 } else if (operandKind == "GroupOperation") {
182 type = OperandGroupOperation;
183 } else if (operandKind == "KernelEnqueueFlags") {
184 type = OperandKernelEnqueueFlags;
185 } else if (operandKind == "KernelProfilingInfo") {
186 type = OperandKernelProfilingInfo;
187 } else if (operandKind == "Capability") {
188 type = OperandCapability;
189 } else if (operandKind == "ImageOperands") {
190 type = OperandImageOperands;
191 } else if (operandKind == "FPFastMathMode") {
192 type = OperandFPFastMath;
193 } else if (operandKind == "SelectionControl") {
194 type = OperandSelect;
195 } else if (operandKind == "LoopControl") {
197 } else if (operandKind == "FunctionControl") {
198 type = OperandFunction;
199 } else if (operandKind == "MemoryAccess") {
200 type = OperandMemoryAccess;
203 if (type == OperandNone) {
204 std::cerr << "Unhandled operand kind found: " << operandKind << std::endl;
207 return {type, !quantifier.empty()};
211 bool IsTypeOrResultId(const std::string& str, bool* isType, bool* isResult)
213 if (str == "IdResultType")
214 return *isType = true;
215 if (str == "IdResult")
216 return *isResult = true;
220 // Given a number string, returns the position of the only bits set in the number.
221 // So it requires the number is a power of two.
222 unsigned int NumberStringToBit(const std::string& str)
225 unsigned int value = (unsigned int)std::strtol(str.c_str(), &parseEnd, 16);
226 assert(!(value & (value - 1)) && "input number is not a power of 2");
227 unsigned int bit = 0;
228 for (; value; value >>= 1) ++bit;
232 void jsonToSpirv(const std::string& jsonPath)
234 // only do this once.
235 static bool initialized = false;
240 // Read the JSON grammar file.
241 bool fileReadOk = false;
243 std::tie(fileReadOk, content) = ReadFile(jsonPath);
245 std::cerr << "Failed to read JSON grammar file: "
246 << jsonPath << std::endl;
250 // Decode the JSON grammar file.
253 if (!reader.parse(content, root)) {
254 std::cerr << "Failed to parse JSON grammar:\n"
255 << reader.getFormattedErrorMessages();
259 // Layouts for all instructions.
261 // A lambda for returning capabilities from a JSON object as strings.
262 const auto getCaps = [](const Json::Value& object) {
264 const auto& caps = object["capabilities"];
266 assert(caps.isArray());
267 for (const auto& cap : caps) {
268 result.emplace_back(cap.asString());
274 // A lambda for returning extensions from a JSON object as strings.
275 const auto getExts = [](const Json::Value& object) {
277 const auto& exts = object["extensions"];
279 assert(exts.isArray());
280 for (const auto& ext : exts) {
281 result.emplace_back(ext.asString());
287 const Json::Value insts = root["instructions"];
288 for (const auto& inst : insts) {
289 const unsigned int opcode = inst["opcode"].asUInt();
290 const std::string name = inst["opname"].asString();
291 EnumCaps caps = getCaps(inst);
292 std::string version = inst["version"].asString();
293 Extensions exts = getExts(inst);
294 OperandParameters operands;
295 bool defResultId = false;
296 bool defTypeId = false;
297 for (const auto& operand : inst["operands"]) {
298 const std::string kind = operand["kind"].asString();
299 const std::string quantifier = operand.get("quantifier", "").asString();
300 const std::string doc = operand.get("name", "").asString();
301 if (!IsTypeOrResultId(kind, &defTypeId, &defResultId)) {
302 const auto p = ToOperandClassAndOptionality(kind, quantifier);
303 operands.push(p.type, doc, p.optional);
306 InstructionDesc.emplace_back(
307 std::move(EnumValue(opcode, name,
308 std::move(caps), std::move(version), std::move(exts),
309 std::move(operands))),
310 defTypeId, defResultId);
313 // Specific additional context-dependent operands
315 // Populate dest with EnumValue objects constructed from source.
316 const auto populateEnumValues = [&getCaps,&getExts](EnumValues* dest, const Json::Value& source, bool bitEnum) {
317 // A lambda for determining the numeric value to be used for a given
318 // enumerant in JSON form, and whether that value is a 0 in a bitfield.
319 auto getValue = [&bitEnum](const Json::Value& enumerant) {
320 std::pair<unsigned, bool> result{0u,false};
322 result.first = enumerant["value"].asUInt();
324 const unsigned int bit = NumberStringToBit(enumerant["value"].asString());
326 result.second = true;
328 result.first = bit - 1; // This is the *shift* amount.
333 for (const auto& enumerant : source["enumerants"]) {
335 bool skip_zero_in_bitfield;
336 std::tie(value, skip_zero_in_bitfield) = getValue(enumerant);
337 if (skip_zero_in_bitfield)
339 EnumCaps caps(getCaps(enumerant));
340 std::string version = enumerant["version"].asString();
341 Extensions exts(getExts(enumerant));
342 OperandParameters params;
343 const Json::Value& paramsJson = enumerant["parameters"];
344 if (!paramsJson.empty()) { // This enumerant has parameters.
345 assert(paramsJson.isArray());
346 for (const auto& param : paramsJson) {
347 const std::string kind = param["kind"].asString();
348 const std::string doc = param.get("name", "").asString();
349 const auto p = ToOperandClassAndOptionality(kind, ""); // All parameters are required!
350 params.push(p.type, doc);
354 value, enumerant["enumerant"].asString(),
355 std::move(caps), std::move(version), std::move(exts), std::move(params));
359 const auto establishOperandClass = [&populateEnumValues](
360 const std::string& enumName, spv::OperandClass operandClass,
361 spv::EnumValues* enumValues, const Json::Value& operandEnum, const std::string& category) {
362 assert(category == "BitEnum" || category == "ValueEnum");
363 bool bitEnum = (category == "BitEnum");
364 populateEnumValues(enumValues, operandEnum, bitEnum);
365 OperandClassParams[operandClass].set(enumName, enumValues, bitEnum);
368 const Json::Value operandEnums = root["operand_kinds"];
369 for (const auto& operandEnum : operandEnums) {
370 const std::string enumName = operandEnum["kind"].asString();
371 const std::string category = operandEnum["category"].asString();
372 if (enumName == "SourceLanguage") {
373 establishOperandClass(enumName, OperandSource, &SourceLanguageParams, operandEnum, category);
374 } else if (enumName == "Decoration") {
375 establishOperandClass(enumName, OperandDecoration, &DecorationParams, operandEnum, category);
376 } else if (enumName == "ExecutionMode") {
377 establishOperandClass(enumName, OperandExecutionMode, &ExecutionModeParams, operandEnum, category);
378 } else if (enumName == "Capability") {
379 establishOperandClass(enumName, OperandCapability, &CapabilityParams, operandEnum, category);
380 } else if (enumName == "AddressingModel") {
381 establishOperandClass(enumName, OperandAddressing, &AddressingParams, operandEnum, category);
382 } else if (enumName == "MemoryModel") {
383 establishOperandClass(enumName, OperandMemory, &MemoryParams, operandEnum, category);
384 } else if (enumName == "MemorySemantics") {
385 establishOperandClass(enumName, OperandMemorySemantics, &MemorySemanticsParams, operandEnum, category);
386 } else if (enumName == "ExecutionModel") {
387 establishOperandClass(enumName, OperandExecutionModel, &ExecutionModelParams, operandEnum, category);
388 } else if (enumName == "StorageClass") {
389 establishOperandClass(enumName, OperandStorage, &StorageParams, operandEnum, category);
390 } else if (enumName == "SamplerAddressingMode") {
391 establishOperandClass(enumName, OperandSamplerAddressingMode, &SamplerAddressingModeParams, operandEnum, category);
392 } else if (enumName == "SamplerFilterMode") {
393 establishOperandClass(enumName, OperandSamplerFilterMode, &SamplerFilterModeParams, operandEnum, category);
394 } else if (enumName == "ImageFormat") {
395 establishOperandClass(enumName, OperandSamplerImageFormat, &ImageFormatParams, operandEnum, category);
396 } else if (enumName == "ImageChannelOrder") {
397 establishOperandClass(enumName, OperandImageChannelOrder, &ImageChannelOrderParams, operandEnum, category);
398 } else if (enumName == "ImageChannelDataType") {
399 establishOperandClass(enumName, OperandImageChannelDataType, &ImageChannelDataTypeParams, operandEnum, category);
400 } else if (enumName == "ImageOperands") {
401 establishOperandClass(enumName, OperandImageOperands, &ImageOperandsParams, operandEnum, category);
402 } else if (enumName == "FPFastMathMode") {
403 establishOperandClass(enumName, OperandFPFastMath, &FPFastMathParams, operandEnum, category);
404 } else if (enumName == "FPRoundingMode") {
405 establishOperandClass(enumName, OperandFPRoundingMode, &FPRoundingModeParams, operandEnum, category);
406 } else if (enumName == "LinkageType") {
407 establishOperandClass(enumName, OperandLinkageType, &LinkageTypeParams, operandEnum, category);
408 } else if (enumName == "FunctionParameterAttribute") {
409 establishOperandClass(enumName, OperandFuncParamAttr, &FuncParamAttrParams, operandEnum, category);
410 } else if (enumName == "AccessQualifier") {
411 establishOperandClass(enumName, OperandAccessQualifier, &AccessQualifierParams, operandEnum, category);
412 } else if (enumName == "BuiltIn") {
413 establishOperandClass(enumName, OperandBuiltIn, &BuiltInParams, operandEnum, category);
414 } else if (enumName == "SelectionControl") {
415 establishOperandClass(enumName, OperandSelect, &SelectionControlParams, operandEnum, category);
416 } else if (enumName == "LoopControl") {
417 establishOperandClass(enumName, OperandLoop, &LoopControlParams, operandEnum, category);
418 } else if (enumName == "FunctionControl") {
419 establishOperandClass(enumName, OperandFunction, &FunctionControlParams, operandEnum, category);
420 } else if (enumName == "Dim") {
421 establishOperandClass(enumName, OperandDimensionality, &DimensionalityParams, operandEnum, category);
422 } else if (enumName == "MemoryAccess") {
423 establishOperandClass(enumName, OperandMemoryAccess, &MemoryAccessParams, operandEnum, category);
424 } else if (enumName == "Scope") {
425 establishOperandClass(enumName, OperandScope, &ScopeParams, operandEnum, category);
426 } else if (enumName == "GroupOperation") {
427 establishOperandClass(enumName, OperandGroupOperation, &GroupOperationParams, operandEnum, category);
428 } else if (enumName == "KernelEnqueueFlags") {
429 establishOperandClass(enumName, OperandKernelEnqueueFlags, &KernelEnqueueFlagsParams, operandEnum, category);
430 } else if (enumName == "KernelProfilingInfo") {
431 establishOperandClass(enumName, OperandKernelProfilingInfo, &KernelProfilingInfoParams, operandEnum, category);
436 }; // end namespace spv