1 #include <msp/core/algorithm.h>
2 #include <msp/core/maputils.h>
3 #include <msp/core/raii.h>
13 const SpirVGenerator::BuiltinFunctionInfo SpirVGenerator::builtin_functions[] =
15 { "radians", "f", "GLSL.std.450", GLSL450_RADIANS, { 1 }, 0, 0 },
16 { "degrees", "f", "GLSL.std.450", GLSL450_DEGREES, { 1 }, 0, 0 },
17 { "sin", "f", "GLSL.std.450", GLSL450_SIN, { 1 }, 0, 0 },
18 { "cos", "f", "GLSL.std.450", GLSL450_COS, { 1 }, 0, 0 },
19 { "tan", "f", "GLSL.std.450", GLSL450_TAN, { 1 }, 0, 0 },
20 { "asin", "f", "GLSL.std.450", GLSL450_ASIN, { 1 }, 0, 0 },
21 { "acos", "f", "GLSL.std.450", GLSL450_ACOS, { 1 }, 0, 0 },
22 { "atan", "f", "GLSL.std.450", GLSL450_ATAN, { 1 }, 0, 0 },
23 { "atan", "ff", "GLSL.std.450", GLSL450_ATAN2, { 1, 2 }, 0, 0 },
24 { "sinh", "f", "GLSL.std.450", GLSL450_SINH, { 1 }, 0, 0 },
25 { "cosh", "f", "GLSL.std.450", GLSL450_COSH, { 1 }, 0, 0 },
26 { "tanh", "f", "GLSL.std.450", GLSL450_TANH, { 1 }, 0, 0 },
27 { "asinh", "f", "GLSL.std.450", GLSL450_ASINH, { 1 }, 0, 0 },
28 { "acosh", "f", "GLSL.std.450", GLSL450_ACOSH, { 1 }, 0, 0 },
29 { "atanh", "f", "GLSL.std.450", GLSL450_ATANH, { 1 }, 0, 0 },
30 { "pow", "ff", "GLSL.std.450", GLSL450_POW, { 1, 2 }, 0, 0 },
31 { "exp", "f", "GLSL.std.450", GLSL450_EXP, { 1 }, 0, 0 },
32 { "log", "f", "GLSL.std.450", GLSL450_LOG, { 1 }, 0, 0 },
33 { "exp2", "f", "GLSL.std.450", GLSL450_EXP2, { 1 }, 0, 0 },
34 { "log2", "f", "GLSL.std.450", GLSL450_LOG2, { 1 }, 0, 0 },
35 { "sqrt", "f", "GLSL.std.450", GLSL450_SQRT, { 1 }, 0, 0 },
36 { "inversesqrt", "f", "GLSL.std.450", GLSL450_INVERSE_SQRT, { 1 }, 0, 0 },
37 { "abs", "f", "GLSL.std.450", GLSL450_F_ABS, { 1 }, 0, 0 },
38 { "abs", "i", "GLSL.std.450", GLSL450_S_ABS, { 1 }, 0, 0 },
39 { "sign", "f", "GLSL.std.450", GLSL450_F_SIGN, { 1 }, 0, 0 },
40 { "sign", "i", "GLSL.std.450", GLSL450_S_SIGN, { 1 }, 0, 0 },
41 { "floor", "f", "GLSL.std.450", GLSL450_FLOOR, { 1 }, 0, 0 },
42 { "trunc", "f", "GLSL.std.450", GLSL450_TRUNC, { 1 }, 0, 0 },
43 { "round", "f", "GLSL.std.450", GLSL450_ROUND, { 1 }, 0, 0 },
44 { "roundEven", "f", "GLSL.std.450", GLSL450_ROUND_EVEN, { 1 }, 0, 0 },
45 { "ceil", "f", "GLSL.std.450", GLSL450_CEIL, { 1 }, 0, 0 },
46 { "fract", "f", "GLSL.std.450", GLSL450_FRACT, { 1 }, 0, 0 },
47 { "mod", "f", "", OP_F_MOD, { 1, 2 }, 0, 0 },
48 { "min", "ff", "GLSL.std.450", GLSL450_F_MIN, { 1, 2 }, 0, 0 },
49 { "min", "ii", "GLSL.std.450", GLSL450_S_MIN, { 1, 2 }, 0, 0 },
50 { "min", "uu", "GLSL.std.450", GLSL450_U_MIN, { 1, 2 }, 0, 0 },
51 { "max", "ff", "GLSL.std.450", GLSL450_F_MAX, { 1, 2 }, 0, 0 },
52 { "max", "ii", "GLSL.std.450", GLSL450_S_MAX, { 1, 2 }, 0, 0 },
53 { "max", "uu", "GLSL.std.450", GLSL450_U_MAX, { 1, 2 }, 0, 0 },
54 { "clamp", "fff", "GLSL.std.450", GLSL450_F_CLAMP, { 1, 2, 3 }, 0, 0 },
55 { "clamp", "iii", "GLSL.std.450", GLSL450_S_CLAMP, { 1, 2, 3 }, 0, 0 },
56 { "clamp", "uuu", "GLSL.std.450", GLSL450_U_CLAMP, { 1, 2, 3 }, 0, 0 },
57 { "mix", "fff", "GLSL.std.450", GLSL450_F_MIX, { 1, 2, 3 }, 0, 0 },
58 { "mix", "ffb", "", OP_SELECT, { 3, 2, 1 }, 0, 0 },
59 { "mix", "iib", "", OP_SELECT, { 3, 2, 1 }, 0, 0 },
60 { "mix", "uub", "", OP_SELECT, { 3, 2, 1 }, 0, 0 },
61 { "step", "ff", "GLSL.std.450", GLSL450_F_STEP, { 1, 2 }, 0, 0 },
62 { "smoothstep", "fff", "GLSL.std.450", GLSL450_F_SMOOTH_STEP, { 1, 2, 3 }, 0, 0 },
63 { "isnan", "f", "", OP_IS_NAN, { 1 }, 0, 0 },
64 { "isinf", "f", "", OP_IS_INF, { 1 }, 0, 0 },
65 { "fma", "fff", "GLSL.std.450", GLSL450_F_FMA, { 1, 2, 3 }, 0, 0 },
66 { "length", "f", "GLSL.std.450", GLSL450_LENGTH, { 1 }, 0, 0 },
67 { "distance", "ff", "GLSL.std.450", GLSL450_DISTANCE, { 1, 2 }, 0, 0 },
68 { "dot", "ff", "", OP_DOT, { 1, 2 }, 0, 0 },
69 { "cross", "ff", "GLSL.std.450", GLSL450_CROSS, { 1, 2 }, 0, 0 },
70 { "normalize", "f", "GLSL.std.450", GLSL450_NORMALIZE, { 1 }, 0, 0 },
71 { "faceforward", "fff", "GLSL.std.450", GLSL450_FACE_FORWARD, { 1, 2, 3 }, 0, 0 },
72 { "reflect", "ff", "GLSL.std.450", GLSL450_REFLECT, { 1, 2 }, 0, 0 },
73 { "refract", "fff", "GLSL.std.450", GLSL450_REFRACT, { 1, 2, 3 }, 0, 0 },
74 { "matrixCompMult", "ff", "", 0, { 0 }, 0, &SpirVGenerator::visit_builtin_matrix_comp_mult },
75 { "outerProduct", "ff", "", OP_OUTER_PRODUCT, { 1, 2 }, 0, 0 },
76 { "transpose", "f", "", OP_TRANSPOSE, { 1 }, 0, 0 },
77 { "determinant", "f", "GLSL.std.450", GLSL450_DETERMINANT, { 1 }, 0, 0 },
78 { "inverse", "f", "GLSL.std.450", GLSL450_MATRIX_INVERSE, { 1 }, 0, 0 },
79 { "lessThan", "ff", "", OP_F_ORD_LESS_THAN, { 1, 2 }, 0, 0 },
80 { "lessThan", "ii", "", OP_S_LESS_THAN, { 1, 2 }, 0, 0 },
81 { "lessThan", "uu", "", OP_U_LESS_THAN, { 1, 2 }, 0, 0 },
82 { "lessThanEqual", "ff", "", OP_F_ORD_LESS_THAN_EQUAL, { 1, 2 }, 0, 0 },
83 { "lessThanEqual", "ii", "", OP_S_LESS_THAN_EQUAL, { 1, 2 }, 0, 0 },
84 { "lessThanEqual", "uu", "", OP_U_LESS_THAN_EQUAL, { 1, 2 }, 0, 0 },
85 { "greaterThan", "ff", "", OP_F_ORD_GREATER_THAN, { 1, 2 }, 0, 0 },
86 { "greaterThan", "ii", "", OP_S_GREATER_THAN, { 1, 2 }, 0, 0 },
87 { "greaterThan", "uu", "", OP_U_GREATER_THAN, { 1, 2 }, 0, 0 },
88 { "greaterThanEqual", "ff", "", OP_F_ORD_GREATER_THAN_EQUAL, { 1, 2 }, 0, 0 },
89 { "greaterThanEqual", "ii", "", OP_S_GREATER_THAN_EQUAL, { 1, 2 }, 0, 0 },
90 { "greaterThanEqual", "uu", "", OP_U_GREATER_THAN_EQUAL, { 1, 2 }, 0, 0 },
91 { "equal", "ff", "", OP_F_ORD_EQUAL, { 1, 2 }, 0, 0 },
92 { "equal", "ii", "", OP_I_EQUAL, { 1, 2 }, 0, 0 },
93 { "equal", "uu", "", OP_I_EQUAL, { 1, 2 }, 0, 0 },
94 { "notEqual", "ff", "", OP_F_ORD_NOT_EQUAL, { 1, 2 }, 0, 0 },
95 { "notEqual", "ii", "", OP_I_NOT_EQUAL, { 1, 2 }, 0, 0 },
96 { "notEqual", "uu", "", OP_I_NOT_EQUAL, { 1, 2 }, 0, 0 },
97 { "any", "b", "", OP_ANY, { 1 }, 0, 0 },
98 { "all", "b", "", OP_ALL, { 1 }, 0, 0 },
99 { "not", "b", "", OP_LOGICAL_NOT, { 1 }, 0, 0 },
100 { "bitfieldExtract", "iii", "", OP_BIT_FIELD_S_EXTRACT, { 1, 2, 3 }, 0, 0 },
101 { "bitfieldExtract", "uii", "", OP_BIT_FIELD_U_EXTRACT, { 1, 2, 3 }, 0, 0 },
102 { "bitfieldInsert", "iiii", "", OP_BIT_FIELD_INSERT, { 1, 2, 3, 4 }, 0, 0 },
103 { "bitfieldInsert", "uuii", "", OP_BIT_FIELD_INSERT, { 1, 2, 3, 4 }, 0, 0 },
104 { "bitfieldReverse", "i", "", OP_BIT_REVERSE, { 1 }, 0, 0 },
105 { "bitfieldReverse", "u", "", OP_BIT_REVERSE, { 1 }, 0, 0 },
106 { "bitCount", "i", "", OP_BIT_COUNT, { 1 }, 0, 0 },
107 { "findLSB", "i", "GLSL.std.450", GLSL450_FIND_I_LSB, { 1 }, 0, 0 },
108 { "findLSB", "u", "GLSL.std.450", GLSL450_FIND_I_LSB, { 1 }, 0, 0 },
109 { "findMSB", "i", "GLSL.std.450", GLSL450_FIND_S_MSB, { 1 }, 0, 0 },
110 { "findMSB", "u", "GLSL.std.450", GLSL450_FIND_U_MSB, { 1 }, 0, 0 },
111 { "textureSize", "", "", 0, { }, CAP_IMAGE_QUERY, &SpirVGenerator::visit_builtin_texture_query },
112 { "textureQueryLod", "", "", 0, { }, CAP_IMAGE_QUERY, &SpirVGenerator::visit_builtin_texture_query },
113 { "textureQueryLevels", "", "", 0, { }, CAP_IMAGE_QUERY, &SpirVGenerator::visit_builtin_texture_query },
114 { "texture", "", "", 0, { }, 0, &SpirVGenerator::visit_builtin_texture },
115 { "textureLod", "", "", 0, { }, 0, &SpirVGenerator::visit_builtin_texture },
116 { "texelFetch", "", "", 0, { }, 0, &SpirVGenerator::visit_builtin_texel_fetch },
117 { "EmitVertex", "", "", OP_EMIT_VERTEX, { }, 0, 0 },
118 { "EndPrimitive", "", "", OP_END_PRIMITIVE, { }, 0, 0 },
119 { "dFdx", "f", "", OP_DP_DX, { 1 }, 0, 0 },
120 { "dFdy", "f", "", OP_DP_DY, { 1 }, 0, 0 },
121 { "dFdxFine", "f", "", OP_DP_DX_FINE, { 1 }, CAP_DERIVATIVE_CONTROL, 0 },
122 { "dFdyFine", "f", "", OP_DP_DY_FINE, { 1 }, CAP_DERIVATIVE_CONTROL, 0 },
123 { "dFdxCoarse", "f", "", OP_DP_DX_COARSE, { 1 }, CAP_DERIVATIVE_CONTROL, 0 },
124 { "dFdyCoarse", "f", "", OP_DP_DY_COARSE, { 1 }, CAP_DERIVATIVE_CONTROL, 0 },
125 { "fwidth", "f", "", OP_FWIDTH, { 1 }, 0, 0 },
126 { "fwidthFine", "f", "", OP_FWIDTH_FINE, { 1 }, CAP_DERIVATIVE_CONTROL, 0 },
127 { "fwidthCoarse", "f", "", OP_FWIDTH_COARSE, { 1 }, CAP_DERIVATIVE_CONTROL, 0 },
128 { "interpolateAtCentroid", "", "", 0, { }, CAP_INTERPOLATION_FUNCTION, &SpirVGenerator::visit_builtin_interpolate },
129 { "interpolateAtSample", "", "", 0, { }, CAP_INTERPOLATION_FUNCTION, &SpirVGenerator::visit_builtin_interpolate },
130 { "interpolateAtOffset", "", "", 0, { }, CAP_INTERPOLATION_FUNCTION, &SpirVGenerator::visit_builtin_interpolate },
131 { "", "", "", 0, { }, 0, 0 }
134 SpirVGenerator::SpirVGenerator():
138 void SpirVGenerator::apply(Module &module)
140 use_capability(CAP_SHADER);
142 for(Stage &s: module.stages)
145 interface_layouts.clear();
146 s.content.visit(*this);
149 writer.finalize(SPIRV_GENERATOR_MSP, next_id);
152 SpirVGenerator::StorageClass SpirVGenerator::get_interface_storage(const string &iface, bool block)
155 return STORAGE_INPUT;
156 else if(iface=="out")
157 return STORAGE_OUTPUT;
158 else if(iface=="uniform")
159 return (block ? STORAGE_UNIFORM : STORAGE_UNIFORM_CONSTANT);
160 else if(iface.empty())
161 return STORAGE_PRIVATE;
163 throw invalid_argument("SpirVGenerator::get_interface_storage");
166 SpirVGenerator::BuiltinSemantic SpirVGenerator::get_builtin_semantic(const string &name)
168 if(name=="gl_Position")
169 return BUILTIN_POSITION;
170 else if(name=="gl_PointSize")
171 return BUILTIN_POINT_SIZE;
172 else if(name=="gl_ClipDistance")
173 return BUILTIN_CLIP_DISTANCE;
174 else if(name=="gl_VertexID")
175 return BUILTIN_VERTEX_ID;
176 else if(name=="gl_InstanceID")
177 return BUILTIN_INSTANCE_ID;
178 else if(name=="gl_PrimitiveID" || name=="gl_PrimitiveIDIn")
179 return BUILTIN_PRIMITIVE_ID;
180 else if(name=="gl_InvocationID")
181 return BUILTIN_INVOCATION_ID;
182 else if(name=="gl_Layer")
183 return BUILTIN_LAYER;
184 else if(name=="gl_FragCoord")
185 return BUILTIN_FRAG_COORD;
186 else if(name=="gl_PointCoord")
187 return BUILTIN_POINT_COORD;
188 else if(name=="gl_FrontFacing")
189 return BUILTIN_FRONT_FACING;
190 else if(name=="gl_SampleId")
191 return BUILTIN_SAMPLE_ID;
192 else if(name=="gl_SamplePosition")
193 return BUILTIN_SAMPLE_POSITION;
194 else if(name=="gl_FragDepth")
195 return BUILTIN_FRAG_DEPTH;
197 throw invalid_argument("SpirVGenerator::get_builtin_semantic");
200 void SpirVGenerator::use_capability(Capability cap)
202 if(used_capabilities.count(cap))
205 used_capabilities.insert(cap);
206 writer.write_op(content.capabilities, OP_CAPABILITY, cap);
209 SpirVGenerator::Id SpirVGenerator::import_extension(const string &name)
211 Id &ext_id = imported_extension_ids[name];
215 writer.begin_op(content.extensions, OP_EXT_INST_IMPORT);
216 writer.write(ext_id);
217 writer.write_string(name);
218 writer.end_op(OP_EXT_INST_IMPORT);
223 SpirVGenerator::Id SpirVGenerator::get_id(Node &node) const
225 return get_item(declared_ids, &node).id;
228 SpirVGenerator::Id SpirVGenerator::allocate_id(Node &node, Id type_id)
230 auto i = declared_ids.find(&node);
231 if(i!=declared_ids.end())
233 if(i->second.type_id)
234 throw key_error(&node);
235 i->second.type_id = type_id;
240 declared_ids.insert(make_pair(&node, Declaration(id, type_id)));
244 SpirVGenerator::Id SpirVGenerator::allocate_forward_id(Node &node)
246 auto i = declared_ids.find(&node);
247 if(i!=declared_ids.end())
251 declared_ids.insert(make_pair(&node, Declaration(id, 0)));
255 SpirVGenerator::Id SpirVGenerator::write_constant(Id type_id, Word value, bool spec)
257 Id const_id = next_id++;
258 if(is_scalar_type(type_id, BasicTypeDeclaration::BOOL))
260 Opcode opcode = (value ? (spec ? OP_SPEC_CONSTANT_TRUE : OP_CONSTANT_TRUE) :
261 (spec ? OP_SPEC_CONSTANT_FALSE : OP_CONSTANT_FALSE));
262 writer.write_op(content.globals, opcode, type_id, const_id);
266 Opcode opcode = (spec ? OP_SPEC_CONSTANT : OP_CONSTANT);
267 writer.write_op(content.globals, opcode, type_id, const_id, value);
272 SpirVGenerator::ConstantKey SpirVGenerator::get_constant_key(Id type_id, const Variant &value)
274 if(value.check_type<bool>())
275 return ConstantKey(type_id, value.value<bool>());
276 else if(value.check_type<int>())
277 return ConstantKey(type_id, value.value<int>());
278 else if(value.check_type<unsigned>())
279 return ConstantKey(type_id, value.value<unsigned>());
280 else if(value.check_type<float>())
281 return ConstantKey(type_id, value.value<float>());
283 throw invalid_argument("SpirVGenerator::get_constant_key");
286 SpirVGenerator::Id SpirVGenerator::get_constant_id(Id type_id, const Variant &value)
288 ConstantKey key = get_constant_key(type_id, value);
289 Id &const_id = constant_ids[key];
291 const_id = write_constant(type_id, key.int_value, false);
295 SpirVGenerator::Id SpirVGenerator::get_vector_constant_id(Id type_id, unsigned size, Id scalar_id)
297 Id &const_id = constant_ids[get_constant_key(type_id, static_cast<int>(scalar_id))];
300 const_id = next_id++;
301 writer.begin_op(content.globals, OP_CONSTANT_COMPOSITE, 3+size);
302 writer.write(type_id);
303 writer.write(const_id);
304 for(unsigned i=0; i<size; ++i)
305 writer.write(scalar_id);
306 writer.end_op(OP_CONSTANT_COMPOSITE);
311 SpirVGenerator::Id SpirVGenerator::get_standard_type_id(BasicTypeDeclaration::Kind kind, unsigned size, bool sign)
313 Id base_id = (size>1 ? get_standard_type_id(kind, 1, sign) : 0);
314 Id &type_id = standard_type_ids[base_id ? TypeKey(base_id, size) : TypeKey(kind, sign)];
319 writer.write_op(content.globals, OP_TYPE_VECTOR, type_id, base_id, size);
320 else if(kind==BasicTypeDeclaration::VOID)
321 writer.write_op(content.globals, OP_TYPE_VOID, type_id);
322 else if(kind==BasicTypeDeclaration::BOOL)
323 writer.write_op(content.globals, OP_TYPE_BOOL, type_id);
324 else if(kind==BasicTypeDeclaration::INT)
325 writer.write_op(content.globals, OP_TYPE_INT, type_id, 32, sign);
326 else if(kind==BasicTypeDeclaration::FLOAT)
327 writer.write_op(content.globals, OP_TYPE_FLOAT, type_id, 32);
329 throw invalid_argument("SpirVGenerator::get_standard_type_id");
334 bool SpirVGenerator::is_scalar_type(Id type_id, BasicTypeDeclaration::Kind kind) const
336 auto i = standard_type_ids.find(TypeKey(kind, true));
337 return (i!=standard_type_ids.end() && i->second==type_id);
340 SpirVGenerator::Id SpirVGenerator::get_array_type_id(TypeDeclaration &base_type, Id size_id)
342 Id base_type_id = get_id(base_type);
343 Id &array_type_id = array_type_ids[TypeKey(base_type_id, size_id)];
346 array_type_id = next_id++;
348 writer.write_op(content.globals, OP_TYPE_ARRAY, array_type_id, base_type_id, size_id);
350 writer.write_op(content.globals, OP_TYPE_RUNTIME_ARRAY, array_type_id, base_type_id);
352 unsigned stride = MemoryRequirementsCalculator().apply(base_type).stride;
353 writer.write_op_decorate(array_type_id, DECO_ARRAY_STRIDE, stride);
356 return array_type_id;
359 SpirVGenerator::Id SpirVGenerator::get_pointer_type_id(Id type_id, StorageClass storage)
361 Id &ptr_type_id = pointer_type_ids[TypeKey(type_id, storage)];
364 ptr_type_id = next_id++;
365 writer.write_op(content.globals, OP_TYPE_POINTER, ptr_type_id, storage, type_id);
370 SpirVGenerator::Id SpirVGenerator::get_variable_type_id(const VariableDeclaration &var)
372 if(const BasicTypeDeclaration *basic = dynamic_cast<const BasicTypeDeclaration *>(var.type_declaration))
373 if(basic->kind==BasicTypeDeclaration::ARRAY)
378 SetFlag set_const(constant_expression);
379 r_expression_result_id = 0;
380 var.array_size->visit(*this);
381 size_id = r_expression_result_id;
384 size_id = get_constant_id(get_standard_type_id(BasicTypeDeclaration::INT, 1), 1);
385 return get_array_type_id(*basic->base_type, size_id);
388 return get_id(*var.type_declaration);
391 SpirVGenerator::Id SpirVGenerator::get_load_id(VariableDeclaration &var)
393 Id &load_result_id = variable_load_ids[&var];
396 load_result_id = next_id++;
397 writer.write_op(content.function_body, OP_LOAD, get_variable_type_id(var), load_result_id, get_id(var));
399 return load_result_id;
402 void SpirVGenerator::prune_loads(Id min_id)
404 for(auto i=variable_load_ids.begin(); i!=variable_load_ids.end(); )
406 if(i->second>=min_id)
407 variable_load_ids.erase(i++);
413 SpirVGenerator::Id SpirVGenerator::begin_expression(Opcode opcode, Id type_id, unsigned n_args)
415 bool has_result = (opcode==OP_FUNCTION_CALL || !is_scalar_type(type_id, BasicTypeDeclaration::VOID));
416 if(!constant_expression)
418 if(!current_function)
419 throw internal_error("non-constant expression outside a function");
421 writer.begin_op(content.function_body, opcode, (n_args ? 1+has_result*2+n_args : 0));
423 else if(opcode==OP_COMPOSITE_CONSTRUCT)
424 writer.begin_op(content.globals, (spec_constant ? OP_SPEC_CONSTANT_COMPOSITE : OP_CONSTANT_COMPOSITE),
425 (n_args ? 1+has_result*2+n_args : 0));
426 else if(!spec_constant)
427 throw internal_error("invalid non-specialization constant expression");
429 writer.begin_op(content.globals, OP_SPEC_CONSTANT_OP, (n_args ? 2+has_result*2+n_args : 0));
431 Id result_id = next_id++;
434 writer.write(type_id);
435 writer.write(result_id);
437 if(spec_constant && opcode!=OP_COMPOSITE_CONSTRUCT)
438 writer.write(opcode);
443 void SpirVGenerator::end_expression(Opcode opcode)
445 if(constant_expression)
446 opcode = (opcode==OP_COMPOSITE_CONSTRUCT ? spec_constant ? OP_SPEC_CONSTANT_COMPOSITE : OP_CONSTANT_COMPOSITE : OP_SPEC_CONSTANT_OP);
447 writer.end_op(opcode);
450 SpirVGenerator::Id SpirVGenerator::write_expression(Opcode opcode, Id type_id, Id arg_id)
452 Id result_id = begin_expression(opcode, type_id, 1);
453 writer.write(arg_id);
454 end_expression(opcode);
458 SpirVGenerator::Id SpirVGenerator::write_expression(Opcode opcode, Id type_id, Id left_id, Id right_id)
460 Id result_id = begin_expression(opcode, type_id, 2);
461 writer.write(left_id);
462 writer.write(right_id);
463 end_expression(opcode);
467 void SpirVGenerator::write_deconstruct(Id elem_type_id, Id composite_id, Id *elem_ids, unsigned n_elems)
469 for(unsigned i=0; i<n_elems; ++i)
471 elem_ids[i] = begin_expression(OP_COMPOSITE_EXTRACT, elem_type_id, 2);
472 writer.write(composite_id);
474 end_expression(OP_COMPOSITE_EXTRACT);
478 SpirVGenerator::Id SpirVGenerator::write_construct(Id type_id, const Id *elem_ids, unsigned n_elems)
480 Id result_id = begin_expression(OP_COMPOSITE_CONSTRUCT, type_id, n_elems);
481 for(unsigned i=0; i<n_elems; ++i)
482 writer.write(elem_ids[i]);
483 end_expression(OP_COMPOSITE_CONSTRUCT);
488 void SpirVGenerator::visit(Block &block)
490 for(const RefPtr<Statement> &s: block.body)
494 void SpirVGenerator::visit(Literal &literal)
496 Id type_id = get_id(*literal.type);
498 r_expression_result_id = write_constant(type_id, get_constant_key(type_id, literal.value).int_value, true);
500 r_expression_result_id = get_constant_id(type_id, literal.value);
501 r_constant_result = true;
504 void SpirVGenerator::visit(VariableReference &var)
506 if(constant_expression || var.declaration->constant)
508 if(!var.declaration->constant)
509 throw internal_error("reference to non-constant variable in constant context");
511 r_expression_result_id = get_id(*var.declaration);
512 r_constant_result = true;
515 else if(!current_function)
516 throw internal_error("non-constant context outside a function");
518 r_constant_result = false;
521 r_composite_base = var.declaration;
522 r_expression_result_id = 0;
524 else if(assignment_source_id)
526 writer.write_op(content.function_body, OP_STORE, get_id(*var.declaration), assignment_source_id);
527 variable_load_ids[var.declaration] = assignment_source_id;
528 r_expression_result_id = assignment_source_id;
531 r_expression_result_id = get_load_id(*var.declaration);
534 void SpirVGenerator::visit(InterfaceBlockReference &iface)
536 if(!composite_access || !current_function)
537 throw internal_error("invalid interface block reference");
539 r_composite_base = iface.declaration;
540 r_expression_result_id = 0;
541 r_constant_result = false;
544 void SpirVGenerator::generate_composite_access(TypeDeclaration &result_type)
547 Id result_type_id = get_id(result_type);
548 Id access_type_id = result_type_id;
551 if(constant_expression)
552 throw internal_error("composite access through pointer in constant context");
554 Id int32_type_id = get_standard_type_id(BasicTypeDeclaration::INT, 1);
555 for(unsigned &i: r_composite_chain)
556 i = (i<0x400000 ? get_constant_id(int32_type_id, static_cast<int>(i)) : i&0x3FFFFF);
558 /* Find the storage class of the base and obtain appropriate pointer type
560 const Declaration &base_decl = get_item(declared_ids, r_composite_base);
561 auto i = pointer_type_ids.begin();
562 for(; (i!=pointer_type_ids.end() && i->second!=base_decl.type_id); ++i) ;
563 if(i==pointer_type_ids.end())
564 throw internal_error("could not find storage class");
565 access_type_id = get_pointer_type_id(result_type_id, static_cast<StorageClass>(i->first.detail));
567 opcode = OP_ACCESS_CHAIN;
569 else if(assignment_source_id)
570 throw internal_error("assignment to temporary composite");
573 for(unsigned &i: r_composite_chain)
574 for(auto j=constant_ids.begin(); (i>=0x400000 && j!=constant_ids.end()); ++j)
575 if(j->second==(i&0x3FFFFF))
576 i = j->first.int_value;
578 opcode = OP_COMPOSITE_EXTRACT;
581 Id access_id = begin_expression(opcode, access_type_id, 1+r_composite_chain.size());
582 writer.write(r_composite_base_id);
583 for(unsigned i: r_composite_chain)
585 end_expression(opcode);
587 r_constant_result = false;
590 if(assignment_source_id)
592 writer.write_op(content.function_body, OP_STORE, access_id, assignment_source_id);
593 r_expression_result_id = assignment_source_id;
596 r_expression_result_id = write_expression(OP_LOAD, result_type_id, access_id);
599 r_expression_result_id = access_id;
602 void SpirVGenerator::visit_composite(Expression &base_expr, unsigned index, TypeDeclaration &type)
604 if(!composite_access)
606 r_composite_base = 0;
607 r_composite_base_id = 0;
608 r_composite_chain.clear();
612 SetFlag set_composite(composite_access);
613 base_expr.visit(*this);
616 if(!r_composite_base_id)
617 r_composite_base_id = (r_composite_base ? get_id(*r_composite_base) : r_expression_result_id);
619 r_composite_chain.push_back(index);
620 if(!composite_access)
621 generate_composite_access(type);
623 r_expression_result_id = 0;
626 void SpirVGenerator::visit_isolated(Expression &expr)
628 SetForScope<Id> clear_assign(assignment_source_id, 0);
629 SetFlag clear_composite(composite_access, false);
630 SetForScope<Node *> clear_base(r_composite_base, 0);
631 SetForScope<Id> clear_base_id(r_composite_base_id, 0);
632 vector<unsigned> saved_chain;
633 swap(saved_chain, r_composite_chain);
635 swap(saved_chain, r_composite_chain);
638 void SpirVGenerator::visit(MemberAccess &memacc)
640 visit_composite(*memacc.left, memacc.index, *memacc.type);
643 void SpirVGenerator::visit(Swizzle &swizzle)
646 visit_composite(*swizzle.left, swizzle.components[0], *swizzle.type);
647 else if(assignment_source_id)
649 const BasicTypeDeclaration &basic = dynamic_cast<const BasicTypeDeclaration &>(*swizzle.left->type);
652 for(unsigned i=0; i<swizzle.count; ++i)
653 mask |= 1<<swizzle.components[i];
655 visit_isolated(*swizzle.left);
657 Id combined_id = begin_expression(OP_VECTOR_SHUFFLE, get_id(*swizzle.left->type), 2+basic.size);
658 writer.write(r_expression_result_id);
659 writer.write(assignment_source_id);
660 for(unsigned i=0; i<basic.size; ++i)
661 writer.write(i+((mask>>i)&1)*basic.size);
662 end_expression(OP_VECTOR_SHUFFLE);
664 SetForScope<Id> set_assign(assignment_source_id, combined_id);
665 swizzle.left->visit(*this);
667 r_expression_result_id = combined_id;
671 swizzle.left->visit(*this);
672 Id left_id = r_expression_result_id;
674 r_expression_result_id = begin_expression(OP_VECTOR_SHUFFLE, get_id(*swizzle.type), 2+swizzle.count);
675 writer.write(left_id);
676 writer.write(left_id);
677 for(unsigned i=0; i<swizzle.count; ++i)
678 writer.write(swizzle.components[i]);
679 end_expression(OP_VECTOR_SHUFFLE);
681 r_constant_result = false;
684 void SpirVGenerator::visit(UnaryExpression &unary)
686 unary.expression->visit(*this);
688 char oper = unary.oper->token[0];
689 char oper2 = unary.oper->token[1];
690 if(oper=='+' && !oper2)
693 BasicTypeDeclaration &basic = dynamic_cast<BasicTypeDeclaration &>(*unary.expression->type);
694 BasicTypeDeclaration &elem = *get_element_type(basic);
696 if(constant_expression && elem.kind!=BasicTypeDeclaration::BOOL && elem.kind!=BasicTypeDeclaration::INT)
697 /* SPIR-V allows constant operations on floating-point values only for
699 throw internal_error("invalid operands for constant unary expression");
701 Id result_type_id = get_id(*unary.type);
702 Opcode opcode = OP_NOP;
704 r_constant_result = false;
706 opcode = OP_LOGICAL_NOT;
709 else if(oper=='-' && !oper2)
711 opcode = (elem.kind==BasicTypeDeclaration::INT ? OP_S_NEGATE : OP_F_NEGATE);
713 if(basic.kind==BasicTypeDeclaration::MATRIX)
715 Id column_type_id = get_id(*basic.base_type);
716 unsigned n_columns = basic.size&0xFFFF;
718 write_deconstruct(column_type_id, r_expression_result_id, column_ids, n_columns);
719 for(unsigned i=0; i<n_columns; ++i)
720 column_ids[i] = write_expression(opcode, column_type_id, column_ids[i]);
721 r_expression_result_id = write_construct(result_type_id, column_ids, n_columns);
725 else if((oper=='+' || oper=='-') && oper2==oper)
727 if(constant_expression)
728 throw internal_error("increment or decrement in constant expression");
731 if(elem.kind==BasicTypeDeclaration::INT)
733 opcode = (oper=='+' ? OP_I_ADD : OP_I_SUB);
734 one_id = get_constant_id(get_id(elem), 1);
736 else if(elem.kind==BasicTypeDeclaration::FLOAT)
738 opcode = (oper=='+' ? OP_F_ADD : OP_F_SUB);
739 one_id = get_constant_id(get_id(elem), 1.0f);
742 throw internal_error("invalid increment/decrement");
744 if(basic.kind==BasicTypeDeclaration::VECTOR)
745 one_id = get_vector_constant_id(result_type_id, basic.size, one_id);
747 Id post_value_id = write_expression(opcode, result_type_id, r_expression_result_id, one_id);
749 SetForScope<Id> set_assign(assignment_source_id, post_value_id);
750 unary.expression->visit(*this);
752 r_expression_result_id = (unary.oper->type==Operator::POSTFIX ? r_expression_result_id : post_value_id);
757 throw internal_error("unknown unary operator");
759 r_expression_result_id = write_expression(opcode, result_type_id, r_expression_result_id);
762 void SpirVGenerator::visit(BinaryExpression &binary)
764 char oper = binary.oper->token[0];
767 visit_isolated(*binary.right);
768 return visit_composite(*binary.left, 0x400000|r_expression_result_id, *binary.type);
771 if(assignment_source_id)
772 throw internal_error("invalid binary expression in assignment target");
774 BasicTypeDeclaration &basic_left = dynamic_cast<BasicTypeDeclaration &>(*binary.left->type);
775 BasicTypeDeclaration &basic_right = dynamic_cast<BasicTypeDeclaration &>(*binary.right->type);
776 // Expression resolver ensures that element types are the same
777 BasicTypeDeclaration &elem = *get_element_type(basic_left);
779 if(constant_expression && elem.kind!=BasicTypeDeclaration::BOOL && elem.kind!=BasicTypeDeclaration::INT)
780 /* SPIR-V allows constant operations on floating-point values only for
782 throw internal_error("invalid operands for constant binary expression");
784 binary.left->visit(*this);
785 Id left_id = r_expression_result_id;
786 binary.right->visit(*this);
787 Id right_id = r_expression_result_id;
789 Id result_type_id = get_id(*binary.type);
790 Opcode opcode = OP_NOP;
791 bool swap_operands = false;
793 r_constant_result = false;
795 char oper2 = binary.oper->token[1];
796 if((oper=='<' || oper=='>') && oper2!=oper)
798 if(basic_left.kind==BasicTypeDeclaration::INT)
801 opcode = (oper=='<' ? (oper2=='=' ? OP_S_LESS_THAN_EQUAL : OP_S_LESS_THAN) :
802 (oper2=='=' ? OP_S_GREATER_THAN_EQUAL : OP_S_GREATER_THAN));
804 opcode = (oper=='<' ? (oper2=='=' ? OP_U_LESS_THAN_EQUAL : OP_U_LESS_THAN) :
805 (oper2=='=' ? OP_U_GREATER_THAN_EQUAL : OP_U_GREATER_THAN));
807 else if(basic_left.kind==BasicTypeDeclaration::FLOAT)
808 opcode = (oper=='<' ? (oper2=='=' ? OP_F_ORD_LESS_THAN_EQUAL : OP_F_ORD_LESS_THAN) :
809 (oper2=='=' ? OP_F_ORD_GREATER_THAN_EQUAL : OP_F_ORD_GREATER_THAN));
811 else if((oper=='=' || oper=='!') && oper2=='=')
813 if(elem.kind==BasicTypeDeclaration::BOOL)
814 opcode = (oper=='=' ? OP_LOGICAL_EQUAL : OP_LOGICAL_NOT_EQUAL);
815 else if(elem.kind==BasicTypeDeclaration::INT)
816 opcode = (oper=='=' ? OP_I_EQUAL : OP_I_NOT_EQUAL);
817 else if(elem.kind==BasicTypeDeclaration::FLOAT)
818 opcode = (oper=='=' ? OP_F_ORD_EQUAL : OP_F_ORD_NOT_EQUAL);
820 if(opcode!=OP_NOP && basic_left.base_type)
822 /* The SPIR-V equality operations produce component-wise results, but
823 GLSL operators return a single boolean. Use the any/all operations to
824 combine the results. */
825 Opcode combine_op = (oper=='!' ? OP_ANY : OP_ALL);
826 unsigned n_elems = basic_left.size&0xFFFF;
827 Id bool_vec_type_id = get_standard_type_id(BasicTypeDeclaration::BOOL, n_elems);
830 if(basic_left.kind==BasicTypeDeclaration::VECTOR)
831 compare_id = write_expression(opcode, bool_vec_type_id, left_id, right_id);
832 else if(basic_left.kind==BasicTypeDeclaration::MATRIX)
834 Id column_type_id = get_id(*basic_left.base_type);
836 write_deconstruct(column_type_id, left_id, column_ids, n_elems);
837 write_deconstruct(column_type_id, right_id, column_ids+4, n_elems);
839 Id column_bvec_type_id = get_standard_type_id(BasicTypeDeclaration::BOOL, basic_left.size>>16);
840 for(unsigned i=0; i<n_elems; ++i)
842 compare_id = write_expression(opcode, column_bvec_type_id, column_ids[i], column_ids[4+i]);
843 column_ids[i] = write_expression(combine_op, result_type_id, compare_id);;
846 compare_id = write_construct(bool_vec_type_id, column_ids, n_elems);
850 r_expression_result_id = write_expression(combine_op, result_type_id, compare_id);
854 else if(oper2=='&' && elem.kind==BasicTypeDeclaration::BOOL)
855 opcode = OP_LOGICAL_AND;
856 else if(oper2=='|' && elem.kind==BasicTypeDeclaration::BOOL)
857 opcode = OP_LOGICAL_OR;
858 else if(oper2=='^' && elem.kind==BasicTypeDeclaration::BOOL)
859 opcode = OP_LOGICAL_NOT_EQUAL;
860 else if(oper=='&' && elem.kind==BasicTypeDeclaration::INT)
861 opcode = OP_BITWISE_AND;
862 else if(oper=='|' && elem.kind==BasicTypeDeclaration::INT)
863 opcode = OP_BITWISE_OR;
864 else if(oper=='^' && elem.kind==BasicTypeDeclaration::INT)
865 opcode = OP_BITWISE_XOR;
866 else if(oper=='<' && oper2==oper && elem.kind==BasicTypeDeclaration::INT)
867 opcode = OP_SHIFT_LEFT_LOGICAL;
868 else if(oper=='>' && oper2==oper && elem.kind==BasicTypeDeclaration::INT)
869 opcode = OP_SHIFT_RIGHT_ARITHMETIC;
870 else if(oper=='%' && elem.kind==BasicTypeDeclaration::INT)
871 opcode = (elem.sign ? OP_S_MOD : OP_U_MOD);
872 else if(oper=='+' || oper=='-' || oper=='*' || oper=='/')
874 Opcode elem_op = OP_NOP;
875 if(elem.kind==BasicTypeDeclaration::INT)
878 elem_op = (elem.sign ? OP_S_DIV : OP_U_DIV);
880 elem_op = (oper=='+' ? OP_I_ADD : oper=='-' ? OP_I_SUB : OP_I_MUL);
882 else if(elem.kind==BasicTypeDeclaration::FLOAT)
883 elem_op = (oper=='+' ? OP_F_ADD : oper=='-' ? OP_F_SUB : oper=='*' ? OP_F_MUL : OP_F_DIV);
885 if(oper=='*' && (basic_left.base_type || basic_right.base_type) && elem.kind==BasicTypeDeclaration::FLOAT)
887 /* Multiplication between floating-point vectors and matrices has
888 dedicated operations. */
889 if(basic_left.kind==BasicTypeDeclaration::MATRIX && basic_right.kind==BasicTypeDeclaration::MATRIX)
890 opcode = OP_MATRIX_TIMES_MATRIX;
891 else if(basic_left.kind==BasicTypeDeclaration::MATRIX || basic_right.kind==BasicTypeDeclaration::MATRIX)
893 if(basic_left.kind==BasicTypeDeclaration::VECTOR)
894 opcode = OP_VECTOR_TIMES_MATRIX;
895 else if(basic_right.kind==BasicTypeDeclaration::VECTOR)
896 opcode = OP_MATRIX_TIMES_VECTOR;
899 opcode = OP_MATRIX_TIMES_SCALAR;
900 swap_operands = (basic_right.kind==BasicTypeDeclaration::MATRIX);
903 else if(basic_left.kind==BasicTypeDeclaration::VECTOR && basic_right.kind==BasicTypeDeclaration::VECTOR)
907 opcode = OP_VECTOR_TIMES_SCALAR;
908 swap_operands = (basic_right.kind==BasicTypeDeclaration::VECTOR);
911 else if((basic_left.base_type!=0)!=(basic_right.base_type!=0))
913 /* One operand is scalar and the other is a vector or a matrix.
914 Expand the scalar to a vector of appropriate size. */
915 Id &scalar_id = (basic_left.base_type ? right_id : left_id);
916 BasicTypeDeclaration *vector_type = (basic_left.base_type ? &basic_left : &basic_right);
917 if(vector_type->kind==BasicTypeDeclaration::MATRIX)
918 vector_type = dynamic_cast<BasicTypeDeclaration *>(vector_type->base_type);
919 Id vector_type_id = get_id(*vector_type);
921 Id expanded_id = begin_expression(OP_COMPOSITE_CONSTRUCT, vector_type_id, vector_type->size);
922 for(unsigned i=0; i<vector_type->size; ++i)
923 writer.write(scalar_id);
924 end_expression(OP_COMPOSITE_CONSTRUCT);
926 scalar_id = expanded_id;
928 if(basic_left.kind==BasicTypeDeclaration::MATRIX || basic_right.kind==BasicTypeDeclaration::MATRIX)
930 // Apply matrix operation column-wise.
931 Id matrix_id = (basic_left.base_type ? left_id : right_id);
934 unsigned n_columns = (basic_left.base_type ? basic_left.size : basic_right.size)&0xFFFF;
935 write_deconstruct(vector_type_id, matrix_id, column_ids, n_columns);
937 for(unsigned i=0; i<n_columns; ++i)
938 column_ids[i] = write_expression(elem_op, vector_type_id, column_ids[i], expanded_id);
940 r_expression_result_id = write_construct(result_type_id, column_ids, n_columns);
946 else if(basic_left.kind==BasicTypeDeclaration::MATRIX && basic_right.kind==BasicTypeDeclaration::MATRIX)
949 throw internal_error("non-float matrix multiplication");
951 /* Other operations involving matrices need to be performed
953 Id column_type_id = get_id(*basic_left.base_type);
956 unsigned n_columns = basic_left.size&0xFFFF;
957 write_deconstruct(column_type_id, left_id, column_ids, n_columns);
958 write_deconstruct(column_type_id, right_id, column_ids+4, n_columns);
960 for(unsigned i=0; i<n_columns; ++i)
961 column_ids[i] = write_expression(elem_op, column_type_id, column_ids[i], column_ids[4+i]);
963 r_expression_result_id = write_construct(result_type_id, column_ids, n_columns);
966 else if(basic_left.kind==basic_right.kind)
967 // Both operands are either scalars or vectors.
972 throw internal_error("unknown binary operator");
975 swap(left_id, right_id);
977 r_expression_result_id = write_expression(opcode, result_type_id, left_id, right_id);
980 void SpirVGenerator::visit(Assignment &assign)
982 if(assign.oper->token[0]!='=')
983 visit(static_cast<BinaryExpression &>(assign));
985 assign.right->visit(*this);
987 SetForScope<Id> set_assign(assignment_source_id, r_expression_result_id);
988 assign.left->visit(*this);
989 r_constant_result = false;
992 void SpirVGenerator::visit(TernaryExpression &ternary)
994 if(constant_expression)
996 ternary.condition->visit(*this);
997 Id condition_id = r_expression_result_id;
998 ternary.true_expr->visit(*this);
999 Id true_result_id = r_expression_result_id;
1000 ternary.false_expr->visit(*this);
1001 Id false_result_id = r_expression_result_id;
1003 r_expression_result_id = begin_expression(OP_SELECT, get_id(*ternary.type), 3);
1004 writer.write(condition_id);
1005 writer.write(true_result_id);
1006 writer.write(false_result_id);
1007 end_expression(OP_SELECT);
1012 ternary.condition->visit(*this);
1013 Id condition_id = r_expression_result_id;
1015 Id true_label_id = next_id++;
1016 Id false_label_id = next_id++;
1017 Id merge_block_id = next_id++;
1018 writer.write_op(content.function_body, OP_SELECTION_MERGE, merge_block_id, 0); // Selection control (none)
1019 writer.write_op(content.function_body, OP_BRANCH_CONDITIONAL, condition_id, true_label_id, false_label_id);
1021 writer.write_op_label(true_label_id);
1022 ternary.true_expr->visit(*this);
1023 Id true_result_id = r_expression_result_id;
1024 writer.write_op(content.function_body, OP_BRANCH, merge_block_id);
1026 writer.write_op_label(false_label_id);
1027 ternary.false_expr->visit(*this);
1028 Id false_result_id = r_expression_result_id;
1030 writer.write_op_label(merge_block_id);
1031 r_expression_result_id = begin_expression(OP_PHI, get_id(*ternary.type), 4);
1032 writer.write(true_result_id);
1033 writer.write(true_label_id);
1034 writer.write(false_result_id);
1035 writer.write(false_label_id);
1036 end_expression(OP_PHI);
1038 r_constant_result = false;
1041 void SpirVGenerator::visit(FunctionCall &call)
1043 if(assignment_source_id)
1044 throw internal_error("assignment to function call");
1045 else if(composite_access)
1046 return visit_isolated(call);
1047 else if(call.constructor && call.arguments.size()==1 && call.arguments[0]->type==call.type)
1048 return call.arguments[0]->visit(*this);
1050 vector<Id> argument_ids;
1051 argument_ids.reserve(call.arguments.size());
1052 bool all_args_const = true;
1053 for(const RefPtr<Expression> &a: call.arguments)
1056 argument_ids.push_back(r_expression_result_id);
1057 all_args_const &= r_constant_result;
1060 if(constant_expression && (!call.constructor || !all_args_const))
1061 throw internal_error("function call in constant expression");
1063 Id result_type_id = get_id(*call.type);
1064 r_constant_result = false;
1066 if(call.constructor)
1067 visit_constructor(call, argument_ids, all_args_const);
1068 else if(call.declaration->source==BUILTIN_SOURCE)
1071 for(const RefPtr<Expression> &a: call.arguments)
1072 if(BasicTypeDeclaration *basic_arg = dynamic_cast<BasicTypeDeclaration *>(a->type))
1074 BasicTypeDeclaration &elem_arg = *get_element_type(*basic_arg);
1075 switch(elem_arg.kind)
1077 case BasicTypeDeclaration::BOOL: arg_types += 'b'; break;
1078 case BasicTypeDeclaration::INT: arg_types += (elem_arg.sign ? 'i' : 'u'); break;
1079 case BasicTypeDeclaration::FLOAT: arg_types += 'f'; break;
1080 default: arg_types += '?';
1084 const BuiltinFunctionInfo *builtin_info;
1085 for(builtin_info=builtin_functions; builtin_info->function[0]; ++builtin_info)
1086 if(builtin_info->function==call.name && (!builtin_info->arg_types[0] || builtin_info->arg_types==arg_types))
1089 if(builtin_info->capability)
1090 use_capability(static_cast<Capability>(builtin_info->capability));
1092 if(builtin_info->opcode)
1095 if(builtin_info->extension[0])
1097 opcode = OP_EXT_INST;
1098 Id ext_id = import_extension(builtin_info->extension);
1100 r_expression_result_id = begin_expression(opcode, result_type_id);
1101 writer.write(ext_id);
1102 writer.write(builtin_info->opcode);
1106 opcode = static_cast<Opcode>(builtin_info->opcode);
1107 r_expression_result_id = begin_expression(opcode, result_type_id);
1110 for(unsigned i=0; i<call.arguments.size(); ++i)
1112 if(!builtin_info->arg_order[i] || builtin_info->arg_order[i]>argument_ids.size())
1113 throw internal_error("invalid builtin function info");
1114 writer.write(argument_ids[builtin_info->arg_order[i]-1]);
1117 end_expression(opcode);
1119 else if(builtin_info->handler)
1120 (this->*(builtin_info->handler))(call, argument_ids);
1122 throw internal_error("unknown builtin function "+call.name);
1126 r_expression_result_id = begin_expression(OP_FUNCTION_CALL, result_type_id, 1+call.arguments.size());
1127 writer.write(get_id(*call.declaration->definition));
1128 for(Id i: argument_ids)
1130 end_expression(OP_FUNCTION_CALL);
1132 // Any global variables the called function uses might have changed value
1133 set<Node *> dependencies = DependencyCollector().apply(*call.declaration->definition);
1134 for(Node *n: dependencies)
1135 if(const VariableDeclaration *var = dynamic_cast<const VariableDeclaration *>(n))
1136 variable_load_ids.erase(var);
1140 void SpirVGenerator::visit_constructor(FunctionCall &call, const vector<Id> &argument_ids, bool all_args_const)
1142 Id result_type_id = get_id(*call.type);
1144 BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(call.type);
1147 if(dynamic_cast<const StructDeclaration *>(call.type))
1148 r_expression_result_id = write_construct(result_type_id, &argument_ids[0], argument_ids.size());
1150 throw internal_error("unconstructable type "+call.name);
1154 SetFlag set_const(constant_expression, constant_expression || all_args_const);
1156 BasicTypeDeclaration &elem = *get_element_type(*basic);
1157 BasicTypeDeclaration &basic_arg0 = dynamic_cast<BasicTypeDeclaration &>(*call.arguments[0]->type);
1158 BasicTypeDeclaration &elem_arg0 = *get_element_type(basic_arg0);
1160 if(basic->kind==BasicTypeDeclaration::MATRIX)
1162 Id col_type_id = get_id(*basic->base_type);
1163 unsigned n_columns = basic->size&0xFFFF;
1164 unsigned n_rows = basic->size>>16;
1167 if(call.arguments.size()==1)
1169 // Construct diagonal matrix from a single scalar.
1170 Id zero_id = get_constant_id(get_id(elem), 0.0f);
1171 for(unsigned i=0; i<n_columns; ++i)
1173 column_ids[i] = begin_expression(OP_COMPOSITE_CONSTRUCT, col_type_id, n_rows);
1174 for(unsigned j=0; j<n_rows; ++j)
1175 writer.write(j==i ? argument_ids[0] : zero_id);
1176 end_expression(OP_COMPOSITE_CONSTRUCT);
1180 // Construct a matrix from column vectors
1181 copy(argument_ids.begin(), argument_ids.begin()+n_columns, column_ids);
1183 r_expression_result_id = write_construct(result_type_id, column_ids, n_columns);
1185 else if(basic->kind==BasicTypeDeclaration::VECTOR && (call.arguments.size()>1 || basic_arg0.kind!=BasicTypeDeclaration::VECTOR))
1187 /* There's either a single scalar argument or multiple arguments
1188 which make up the vector's components. */
1189 if(call.arguments.size()==1)
1191 r_expression_result_id = begin_expression(OP_COMPOSITE_CONSTRUCT, result_type_id);
1192 for(unsigned i=0; i<basic->size; ++i)
1193 writer.write(argument_ids[0]);
1194 end_expression(OP_COMPOSITE_CONSTRUCT);
1197 r_expression_result_id = write_construct(result_type_id, &argument_ids[0], argument_ids.size());
1199 else if(elem.kind==BasicTypeDeclaration::BOOL)
1201 if(constant_expression)
1202 throw internal_error("unconverted constant");
1204 // Conversion to boolean is implemented as comparing against zero.
1205 Id number_type_id = get_id(elem_arg0);
1206 Id zero_id = (elem_arg0.kind==BasicTypeDeclaration::FLOAT ?
1207 get_constant_id(number_type_id, 0.0f) : get_constant_id(number_type_id, 0));
1208 if(basic_arg0.kind==BasicTypeDeclaration::VECTOR)
1209 zero_id = get_vector_constant_id(get_id(basic_arg0), basic_arg0.size, zero_id);
1211 Opcode opcode = (elem_arg0.kind==BasicTypeDeclaration::FLOAT ? OP_F_ORD_NOT_EQUAL : OP_I_NOT_EQUAL);
1212 r_expression_result_id = write_expression(opcode, result_type_id, argument_ids[0], zero_id);
1214 else if(elem_arg0.kind==BasicTypeDeclaration::BOOL)
1216 if(constant_expression)
1217 throw internal_error("unconverted constant");
1219 /* Conversion from boolean is implemented as selecting from zero
1221 Id number_type_id = get_id(elem);
1222 Id zero_id = (elem.kind==BasicTypeDeclaration::FLOAT ?
1223 get_constant_id(number_type_id, 0.0f) : get_constant_id(number_type_id, 0));
1224 Id one_id = (elem.kind==BasicTypeDeclaration::FLOAT ?
1225 get_constant_id(number_type_id, 1.0f) : get_constant_id(number_type_id, 1));
1226 if(basic->kind==BasicTypeDeclaration::VECTOR)
1228 zero_id = get_vector_constant_id(get_id(*basic), basic->size, zero_id);
1229 one_id = get_vector_constant_id(get_id(*basic), basic->size, one_id);
1232 r_expression_result_id = begin_expression(OP_SELECT, result_type_id, 3);
1233 writer.write(argument_ids[0]);
1234 writer.write(zero_id);
1235 writer.write(one_id);
1236 end_expression(OP_SELECT);
1240 if(constant_expression)
1241 throw internal_error("unconverted constant");
1243 // Scalar or vector conversion between types of equal size.
1245 if(elem.kind==BasicTypeDeclaration::INT && elem_arg0.kind==BasicTypeDeclaration::FLOAT)
1246 opcode = (elem.sign ? OP_CONVERT_F_TO_S : OP_CONVERT_F_TO_U);
1247 else if(elem.kind==BasicTypeDeclaration::FLOAT && elem_arg0.kind==BasicTypeDeclaration::INT)
1248 opcode = (elem_arg0.sign ? OP_CONVERT_S_TO_F : OP_CONVERT_U_TO_F);
1249 else if(elem.kind==BasicTypeDeclaration::INT && elem_arg0.kind==BasicTypeDeclaration::INT)
1250 opcode = OP_BITCAST;
1252 throw internal_error("invalid conversion");
1254 r_expression_result_id = write_expression(opcode, result_type_id, argument_ids[0]);
1258 void SpirVGenerator::visit_builtin_matrix_comp_mult(FunctionCall &call, const vector<Id> &argument_ids)
1260 if(argument_ids.size()!=2)
1261 throw internal_error("invalid matrixCompMult call");
1263 const BasicTypeDeclaration &basic_arg0 = dynamic_cast<const BasicTypeDeclaration &>(*call.arguments[0]->type);
1264 Id column_type_id = get_id(*basic_arg0.base_type);
1267 unsigned n_columns = basic_arg0.size&0xFFFF;
1268 write_deconstruct(column_type_id, argument_ids[0], column_ids, n_columns);
1269 write_deconstruct(column_type_id, argument_ids[1], column_ids+4, n_columns);
1271 for(unsigned i=0; i<n_columns; ++i)
1272 column_ids[i] = write_expression(OP_F_MUL, column_type_id, column_ids[i], column_ids[4+i]);
1274 r_expression_result_id = write_construct(get_id(*call.type), column_ids, n_columns);
1277 void SpirVGenerator::visit_builtin_texture_query(FunctionCall &call, const vector<Id> &argument_ids)
1279 if(argument_ids.size()<1)
1280 throw internal_error("invalid texture query call");
1283 if(call.name=="textureSize")
1284 opcode = OP_IMAGE_QUERY_SIZE_LOD;
1285 else if(call.name=="textureQueryLod")
1286 opcode = OP_IMAGE_QUERY_LOD;
1287 else if(call.name=="textureQueryLevels")
1288 opcode = OP_IMAGE_QUERY_LEVELS;
1290 throw internal_error("invalid texture query call");
1292 ImageTypeDeclaration &image_arg0 = dynamic_cast<ImageTypeDeclaration &>(*call.arguments[0]->type);
1295 if(image_arg0.sampled)
1297 Id image_type_id = get_item(image_type_ids, get_id(image_arg0));
1298 image_id = write_expression(OP_IMAGE, image_type_id, argument_ids[0]);
1301 image_id = argument_ids[0];
1303 Id result_type_id = get_id(*call.type);
1304 r_expression_result_id = begin_expression(opcode, result_type_id, argument_ids.size());
1305 writer.write(image_id);
1306 for(unsigned i=1; i<argument_ids.size(); ++i)
1307 writer.write(argument_ids[i]);
1308 end_expression(opcode);
1311 void SpirVGenerator::visit_builtin_texture(FunctionCall &call, const vector<Id> &argument_ids)
1313 if(argument_ids.size()<2)
1314 throw internal_error("invalid texture sampling call");
1316 bool explicit_lod = (stage->type!=Stage::FRAGMENT || call.name=="textureLod");
1317 Id lod_id = (!explicit_lod ? 0 : call.name=="textureLod" ? argument_ids.back() :
1318 get_constant_id(get_standard_type_id(BasicTypeDeclaration::FLOAT, 1), 0.0f));
1320 const ImageTypeDeclaration &image = dynamic_cast<const ImageTypeDeclaration &>(*call.arguments[0]->type);
1323 Id result_type_id = get_id(*call.type);
1327 if(argument_ids.size()==2)
1329 const BasicTypeDeclaration &basic_arg1 = dynamic_cast<const BasicTypeDeclaration &>(*call.arguments[1]->type);
1330 dref_id = begin_expression(OP_COMPOSITE_EXTRACT, get_id(*basic_arg1.base_type), 2);
1331 writer.write(argument_ids.back());
1332 writer.write(basic_arg1.size-1);
1333 end_expression(OP_COMPOSITE_EXTRACT);
1336 dref_id = argument_ids[2];
1338 opcode = (explicit_lod ? OP_IMAGE_SAMPLE_DREF_EXPLICIT_LOD : OP_IMAGE_SAMPLE_DREF_IMPLICIT_LOD);
1339 r_expression_result_id = begin_expression(opcode, result_type_id, 3+explicit_lod*2);
1343 opcode = (explicit_lod ? OP_IMAGE_SAMPLE_EXPLICIT_LOD : OP_IMAGE_SAMPLE_IMPLICIT_LOD);
1344 r_expression_result_id = begin_expression(opcode, result_type_id, 2+explicit_lod*2);
1347 for(unsigned i=0; i<2; ++i)
1348 writer.write(argument_ids[i]);
1350 writer.write(dref_id);
1353 writer.write(2); // Lod
1354 writer.write(lod_id);
1357 end_expression(opcode);
1360 void SpirVGenerator::visit_builtin_texel_fetch(FunctionCall &call, const vector<Id> &argument_ids)
1362 if(argument_ids.size()!=3)
1363 throw internal_error("invalid texelFetch call");
1365 r_expression_result_id = begin_expression(OP_IMAGE_FETCH, get_id(*call.type), 4);
1366 for(unsigned i=0; i<2; ++i)
1367 writer.write(argument_ids[i]);
1368 writer.write(2); // Lod
1369 writer.write(argument_ids.back());
1370 end_expression(OP_IMAGE_FETCH);
1373 void SpirVGenerator::visit_builtin_interpolate(FunctionCall &call, const vector<Id> &argument_ids)
1375 if(argument_ids.size()<1)
1376 throw internal_error("invalid interpolate call");
1377 const VariableReference *var = dynamic_cast<const VariableReference *>(call.arguments[0].get());
1378 if(!var || !var->declaration || var->declaration->interface!="in")
1379 throw internal_error("invalid interpolate call");
1381 SpirVGlslStd450Opcode opcode;
1382 if(call.name=="interpolateAtCentroid")
1383 opcode = GLSL450_INTERPOLATE_AT_CENTROID;
1384 else if(call.name=="interpolateAtSample")
1385 opcode = GLSL450_INTERPOLATE_AT_SAMPLE;
1386 else if(call.name=="interpolateAtOffset")
1387 opcode = GLSL450_INTERPOLATE_AT_OFFSET;
1389 throw internal_error("invalid interpolate call");
1391 Id ext_id = import_extension("GLSL.std.450");
1392 r_expression_result_id = begin_expression(OP_EXT_INST, get_id(*call.type));
1393 writer.write(ext_id);
1394 writer.write(opcode);
1395 writer.write(get_id(*var->declaration));
1396 for(auto i=argument_ids.begin(); ++i!=argument_ids.end(); )
1398 end_expression(OP_EXT_INST);
1401 void SpirVGenerator::visit(ExpressionStatement &expr)
1403 expr.expression->visit(*this);
1406 void SpirVGenerator::visit(InterfaceLayout &layout)
1408 interface_layouts.push_back(&layout);
1411 bool SpirVGenerator::check_duplicate_type(TypeDeclaration &type)
1413 for(const auto &kvp: declared_ids)
1414 if(TypeDeclaration *type2 = dynamic_cast<TypeDeclaration *>(kvp.first))
1415 if(TypeComparer().apply(type, *type2))
1417 insert_unique(declared_ids, &type, kvp.second);
1424 bool SpirVGenerator::check_standard_type(BasicTypeDeclaration &basic)
1426 const BasicTypeDeclaration *elem = (basic.kind==BasicTypeDeclaration::VECTOR ?
1427 dynamic_cast<const BasicTypeDeclaration *>(basic.base_type) : &basic);
1428 if(!elem || elem->base_type)
1430 if((elem->kind==BasicTypeDeclaration::INT || elem->kind==BasicTypeDeclaration::FLOAT) && elem->size!=32)
1433 Id standard_id = get_standard_type_id(elem->kind, (basic.kind==BasicTypeDeclaration::VECTOR ? basic.size : 1), elem->sign);
1434 insert_unique(declared_ids, &basic, Declaration(standard_id, 0));
1435 writer.write_op_name(standard_id, basic.name);
1440 void SpirVGenerator::visit(BasicTypeDeclaration &basic)
1442 if(check_standard_type(basic))
1444 if(check_duplicate_type(basic))
1446 // Alias types shouldn't exist at this point and arrays are handled elsewhere
1447 if(basic.kind==BasicTypeDeclaration::ALIAS || basic.kind==BasicTypeDeclaration::ARRAY)
1450 Id type_id = allocate_id(basic, 0);
1451 writer.write_op_name(type_id, basic.name);
1455 case BasicTypeDeclaration::INT:
1456 writer.write_op(content.globals, OP_TYPE_INT, type_id, basic.size, basic.sign);
1458 case BasicTypeDeclaration::FLOAT:
1459 writer.write_op(content.globals, OP_TYPE_FLOAT, type_id, basic.size);
1461 case BasicTypeDeclaration::VECTOR:
1462 writer.write_op(content.globals, OP_TYPE_VECTOR, type_id, get_id(*basic.base_type), basic.size);
1464 case BasicTypeDeclaration::MATRIX:
1465 writer.write_op(content.globals, OP_TYPE_MATRIX, type_id, get_id(*basic.base_type), basic.size&0xFFFF);
1468 throw internal_error("unknown basic type");
1472 void SpirVGenerator::visit(ImageTypeDeclaration &image)
1474 if(check_duplicate_type(image))
1477 Id type_id = allocate_id(image, 0);
1479 Id image_id = (image.sampled ? next_id++ : type_id);
1480 writer.begin_op(content.globals, OP_TYPE_IMAGE, 9);
1481 writer.write(image_id);
1482 writer.write(get_id(*image.base_type));
1483 writer.write(image.dimensions-1);
1484 writer.write(image.shadow);
1485 writer.write(image.array);
1486 writer.write(false); // Multisample
1487 writer.write(image.sampled ? 1 : 2);
1488 writer.write(0); // Format (unknown)
1489 writer.end_op(OP_TYPE_IMAGE);
1493 writer.write_op_name(type_id, image.name);
1494 writer.write_op(content.globals, OP_TYPE_SAMPLED_IMAGE, type_id, image_id);
1495 insert_unique(image_type_ids, type_id, image_id);
1498 if(image.dimensions==ImageTypeDeclaration::ONE)
1499 use_capability(image.sampled ? CAP_SAMPLED_1D : CAP_IMAGE_1D);
1500 else if(image.dimensions==ImageTypeDeclaration::CUBE && image.array)
1501 use_capability(image.sampled ? CAP_SAMPLED_CUBE_ARRAY : CAP_IMAGE_CUBE_ARRAY);
1504 void SpirVGenerator::visit(StructDeclaration &strct)
1506 if(check_duplicate_type(strct))
1509 Id type_id = allocate_id(strct, 0);
1510 writer.write_op_name(type_id, strct.name);
1512 if(strct.interface_block)
1513 writer.write_op_decorate(type_id, DECO_BLOCK);
1515 bool builtin = (strct.interface_block && !strct.interface_block->block_name.compare(0, 3, "gl_"));
1516 vector<Id> member_type_ids;
1517 member_type_ids.reserve(strct.members.body.size());
1518 for(const RefPtr<Statement> &s: strct.members.body)
1520 const VariableDeclaration *var = dynamic_cast<const VariableDeclaration *>(s.get());
1524 unsigned index = member_type_ids.size();
1525 member_type_ids.push_back(get_variable_type_id(*var));
1527 writer.write_op_member_name(type_id, index, var->name);
1531 BuiltinSemantic semantic = get_builtin_semantic(var->name);
1532 writer.write_op_member_decorate(type_id, index, DECO_BUILTIN, semantic);
1538 for(const Layout::Qualifier &q: var->layout->qualifiers)
1540 if(q.name=="offset")
1541 writer.write_op_member_decorate(type_id, index, DECO_OFFSET, q.value);
1542 else if(q.name=="column_major")
1543 writer.write_op_member_decorate(type_id, index, DECO_COL_MAJOR);
1544 else if(q.name=="row_major")
1545 writer.write_op_member_decorate(type_id, index, DECO_ROW_MAJOR);
1549 const BasicTypeDeclaration *basic = dynamic_cast<const BasicTypeDeclaration *>(var->type_declaration);
1550 while(basic && basic->kind==BasicTypeDeclaration::ARRAY)
1551 basic = dynamic_cast<const BasicTypeDeclaration *>(basic->base_type);
1552 if(basic && basic->kind==BasicTypeDeclaration::MATRIX)
1554 unsigned stride = MemoryRequirementsCalculator().apply(*basic->base_type).stride;
1555 writer.write_op_member_decorate(type_id, index, DECO_MATRIX_STRIDE, stride);
1560 writer.begin_op(content.globals, OP_TYPE_STRUCT);
1561 writer.write(type_id);
1562 for(Id i: member_type_ids)
1564 writer.end_op(OP_TYPE_STRUCT);
1567 void SpirVGenerator::visit(VariableDeclaration &var)
1569 const vector<Layout::Qualifier> *layout_ql = (var.layout ? &var.layout->qualifiers : 0);
1574 auto i = find_member(*layout_ql, string("constant_id"), &Layout::Qualifier::name);
1575 if(i!=layout_ql->end())
1579 Id type_id = get_variable_type_id(var);
1584 if(!var.init_expression)
1585 throw internal_error("const variable without initializer");
1587 SetFlag set_const(constant_expression);
1588 SetFlag set_spec(spec_constant, spec_id>=0);
1589 r_expression_result_id = 0;
1590 var.init_expression->visit(*this);
1591 var_id = r_expression_result_id;
1592 insert_unique(declared_ids, &var, Declaration(var_id, type_id));
1593 writer.write_op_decorate(var_id, DECO_SPEC_ID, spec_id);
1595 /* It's unclear what should be done if a specialization constant is
1596 initialized with anything other than a literal. GLSL doesn't seem to
1597 prohibit that but SPIR-V says OpSpecConstantOp can't be updated via
1602 StorageClass storage = (current_function ? STORAGE_FUNCTION : get_interface_storage(var.interface, false));
1603 Id ptr_type_id = get_pointer_type_id(type_id, storage);
1604 if(var.interface=="uniform")
1606 Id &uni_id = declared_uniform_ids["v"+var.name];
1609 insert_unique(declared_ids, &var, Declaration(uni_id, ptr_type_id));
1613 uni_id = var_id = allocate_id(var, ptr_type_id);
1616 var_id = allocate_id(var, (var.constant ? type_id : ptr_type_id));
1619 if(var.init_expression)
1621 SetFlag set_const(constant_expression, !current_function);
1622 r_expression_result_id = 0;
1623 r_constant_result = false;
1624 var.init_expression->visit(*this);
1625 init_id = r_expression_result_id;
1628 vector<Word> &target = (current_function ? content.locals : content.globals);
1629 writer.begin_op(target, OP_VARIABLE, 4+(init_id && !current_function));
1630 writer.write(ptr_type_id);
1631 writer.write(var_id);
1632 writer.write(storage);
1633 if(init_id && !current_function)
1634 writer.write(init_id);
1635 writer.end_op(OP_VARIABLE);
1639 for(const Layout::Qualifier &q: *layout_ql)
1641 if(q.name=="location")
1642 writer.write_op_decorate(var_id, DECO_LOCATION, q.value);
1643 else if(q.name=="set")
1644 writer.write_op_decorate(var_id, DECO_DESCRIPTOR_SET, q.value);
1645 else if(q.name=="binding")
1646 writer.write_op_decorate(var_id, DECO_BINDING, q.value);
1649 if(!var.name.compare(0, 3, "gl_"))
1651 BuiltinSemantic semantic = get_builtin_semantic(var.name);
1652 writer.write_op_decorate(var_id, DECO_BUILTIN, semantic);
1655 if(init_id && current_function)
1657 writer.write_op(content.function_body, OP_STORE, var_id, init_id);
1658 variable_load_ids[&var] = init_id;
1662 writer.write_op_name(var_id, var.name);
1665 void SpirVGenerator::visit(InterfaceBlock &iface)
1667 StorageClass storage = get_interface_storage(iface.interface, true);
1670 type_id = get_array_type_id(*iface.struct_declaration, 0);
1672 type_id = get_id(*iface.struct_declaration);
1673 Id ptr_type_id = get_pointer_type_id(type_id, storage);
1676 if(iface.interface=="uniform")
1678 Id &uni_id = declared_uniform_ids["b"+iface.block_name];
1681 insert_unique(declared_ids, &iface, Declaration(uni_id, ptr_type_id));
1685 uni_id = block_id = allocate_id(iface, ptr_type_id);
1688 block_id = allocate_id(iface, ptr_type_id);
1689 writer.write_op_name(block_id, iface.instance_name);
1691 writer.write_op(content.globals, OP_VARIABLE, ptr_type_id, block_id, storage);
1695 auto i = find_member(iface.layout->qualifiers, string("binding"), &Layout::Qualifier::name);
1696 if(i!=iface.layout->qualifiers.end())
1697 writer.write_op_decorate(block_id, DECO_BINDING, i->value);
1701 void SpirVGenerator::visit_entry_point(FunctionDeclaration &func, Id func_id)
1703 writer.begin_op(content.entry_points, OP_ENTRY_POINT);
1706 case Stage::VERTEX: writer.write(0); break;
1707 case Stage::GEOMETRY: writer.write(3); break;
1708 case Stage::FRAGMENT: writer.write(4); break;
1709 default: throw internal_error("unknown stage");
1711 writer.write(func_id);
1712 writer.write_string(func.name);
1714 set<Node *> dependencies = DependencyCollector().apply(func);
1715 for(Node *n: dependencies)
1717 if(const VariableDeclaration *var = dynamic_cast<const VariableDeclaration *>(n))
1719 if(!var->interface.empty())
1720 writer.write(get_id(*n));
1722 else if(dynamic_cast<InterfaceBlock *>(n))
1723 writer.write(get_id(*n));
1726 writer.end_op(OP_ENTRY_POINT);
1728 if(stage->type==Stage::FRAGMENT)
1729 writer.write_op(content.exec_modes, OP_EXECUTION_MODE, func_id, EXEC_ORIGIN_LOWER_LEFT);
1730 else if(stage->type==Stage::GEOMETRY)
1731 use_capability(CAP_GEOMETRY);
1733 for(const InterfaceLayout *i: interface_layouts)
1735 for(const Layout::Qualifier &q: i->layout.qualifiers)
1738 writer.write_op(content.exec_modes, OP_EXECUTION_MODE, func_id,
1739 (i->interface=="in" ? EXEC_INPUT_POINTS : EXEC_OUTPUT_POINTS));
1740 else if(q.name=="lines")
1741 writer.write_op(content.exec_modes, OP_EXECUTION_MODE, func_id, EXEC_INPUT_LINES);
1742 else if(q.name=="lines_adjacency")
1743 writer.write_op(content.exec_modes, OP_EXECUTION_MODE, func_id, EXEC_INPUT_LINES_ADJACENCY);
1744 else if(q.name=="triangles")
1745 writer.write_op(content.exec_modes, OP_EXECUTION_MODE, func_id, EXEC_TRIANGLES);
1746 else if(q.name=="triangles_adjacency")
1747 writer.write_op(content.exec_modes, OP_EXECUTION_MODE, func_id, EXEC_INPUT_TRIANGLES_ADJACENCY);
1748 else if(q.name=="line_strip")
1749 writer.write_op(content.exec_modes, OP_EXECUTION_MODE, func_id, EXEC_OUTPUT_LINE_STRIP);
1750 else if(q.name=="triangle_strip")
1751 writer.write_op(content.exec_modes, OP_EXECUTION_MODE, func_id, EXEC_OUTPUT_TRIANGLE_STRIP);
1752 else if(q.name=="max_vertices")
1753 writer.write_op(content.exec_modes, OP_EXECUTION_MODE, func_id, EXEC_OUTPUT_VERTICES, q.value);
1758 void SpirVGenerator::visit(FunctionDeclaration &func)
1760 if(func.source==BUILTIN_SOURCE)
1762 else if(func.definition!=&func)
1765 allocate_forward_id(*func.definition);
1769 Id return_type_id = get_id(*func.return_type_declaration);
1770 vector<unsigned> param_type_ids;
1771 param_type_ids.reserve(func.parameters.size());
1772 for(const RefPtr<VariableDeclaration> &p: func.parameters)
1773 param_type_ids.push_back(get_variable_type_id(*p));
1775 string sig_with_return = func.return_type+func.signature;
1776 Id &type_id = function_type_ids[sig_with_return];
1779 type_id = next_id++;
1780 writer.begin_op(content.globals, OP_TYPE_FUNCTION);
1781 writer.write(type_id);
1782 writer.write(return_type_id);
1783 for(unsigned i: param_type_ids)
1785 writer.end_op(OP_TYPE_FUNCTION);
1787 writer.write_op_name(type_id, sig_with_return);
1790 Id func_id = allocate_id(func, type_id);
1791 writer.write_op_name(func_id, func.name+func.signature);
1793 if(func.name=="main")
1794 visit_entry_point(func, func_id);
1796 writer.begin_op(content.functions, OP_FUNCTION, 5);
1797 writer.write(return_type_id);
1798 writer.write(func_id);
1799 writer.write(0); // Function control flags (none)
1800 writer.write(type_id);
1801 writer.end_op(OP_FUNCTION);
1803 for(unsigned i=0; i<func.parameters.size(); ++i)
1805 Id param_id = allocate_id(*func.parameters[i], param_type_ids[i]);
1806 writer.write_op(content.functions, OP_FUNCTION_PARAMETER, param_type_ids[i], param_id);
1807 // TODO This is probably incorrect if the parameter is assigned to.
1808 variable_load_ids[func.parameters[i].get()] = param_id;
1811 writer.begin_function_body(next_id++);
1812 SetForScope<FunctionDeclaration *> set_func(current_function, &func);
1813 func.body.visit(*this);
1815 if(writer.has_current_block())
1818 writer.write_op(content.function_body, OP_UNREACHABLE);
1821 const BasicTypeDeclaration *basic_return = dynamic_cast<const BasicTypeDeclaration *>(func.return_type_declaration);
1822 if(basic_return && basic_return->kind==BasicTypeDeclaration::VOID)
1823 writer.write_op(content.function_body, OP_RETURN);
1825 throw internal_error("missing return in non-void function");
1828 writer.end_function_body();
1829 variable_load_ids.clear();
1832 void SpirVGenerator::visit(Conditional &cond)
1834 cond.condition->visit(*this);
1836 Id true_label_id = next_id++;
1837 Id merge_block_id = next_id++;
1838 Id false_label_id = (cond.else_body.body.empty() ? merge_block_id : next_id++);
1839 writer.write_op(content.function_body, OP_SELECTION_MERGE, merge_block_id, 0); // Selection control (none)
1840 writer.write_op(content.function_body, OP_BRANCH_CONDITIONAL, r_expression_result_id, true_label_id, false_label_id);
1842 writer.write_op_label(true_label_id);
1843 cond.body.visit(*this);
1844 if(writer.has_current_block())
1845 writer.write_op(content.function_body, OP_BRANCH, merge_block_id);
1847 bool reachable_if_true = reachable;
1850 if(!cond.else_body.body.empty())
1852 writer.write_op_label(false_label_id);
1853 cond.else_body.visit(*this);
1854 reachable |= reachable_if_true;
1857 writer.write_op_label(merge_block_id);
1858 prune_loads(true_label_id);
1861 void SpirVGenerator::visit(Iteration &iter)
1863 if(iter.init_statement)
1864 iter.init_statement->visit(*this);
1866 for(VariableDeclaration *v: AssignmentCollector().apply(iter))
1867 variable_load_ids.erase(v);
1869 Id header_id = next_id++;
1870 Id continue_id = next_id++;
1871 Id merge_block_id = next_id++;
1873 SetForScope<Id> set_merge(loop_merge_block_id, merge_block_id);
1874 SetForScope<Id> set_continue(loop_continue_target_id, continue_id);
1876 writer.write_op_label(header_id);
1877 writer.write_op(content.function_body, OP_LOOP_MERGE, merge_block_id, continue_id, 0); // Loop control (none)
1879 Id body_id = next_id++;
1882 writer.write_op_label(next_id++);
1883 iter.condition->visit(*this);
1884 writer.write_op(content.function_body, OP_BRANCH_CONDITIONAL, r_expression_result_id, body_id, merge_block_id);
1887 writer.write_op_label(body_id);
1888 iter.body.visit(*this);
1890 writer.write_op_label(continue_id);
1891 if(iter.loop_expression)
1892 iter.loop_expression->visit(*this);
1893 writer.write_op(content.function_body, OP_BRANCH, header_id);
1895 writer.write_op_label(merge_block_id);
1896 prune_loads(header_id);
1900 void SpirVGenerator::visit(Return &ret)
1904 ret.expression->visit(*this);
1905 writer.write_op(content.function_body, OP_RETURN_VALUE, r_expression_result_id);
1908 writer.write_op(content.function_body, OP_RETURN);
1912 void SpirVGenerator::visit(Jump &jump)
1914 if(jump.keyword=="discard")
1915 writer.write_op(content.function_body, OP_KILL);
1916 else if(jump.keyword=="break")
1917 writer.write_op(content.function_body, OP_BRANCH, loop_merge_block_id);
1918 else if(jump.keyword=="continue")
1919 writer.write_op(content.function_body, OP_BRANCH, loop_continue_target_id);
1921 throw internal_error("unknown jump");
1926 SpirVGenerator::TypeKey::TypeKey(BasicTypeDeclaration::Kind kind, bool sign):
1931 case BasicTypeDeclaration::VOID: detail = 'v'; break;
1932 case BasicTypeDeclaration::BOOL: detail = 'b'; break;
1933 case BasicTypeDeclaration::INT: detail = (sign ? 'i' : 'u'); break;
1934 case BasicTypeDeclaration::FLOAT: detail = 'f'; break;
1935 default: throw invalid_argument("TypeKey::TypeKey");
1939 bool SpirVGenerator::TypeKey::operator<(const TypeKey &other) const
1941 if(type_id!=other.type_id)
1942 return type_id<other.type_id;
1943 return detail<other.detail;
1947 bool SpirVGenerator::ConstantKey::operator<(const ConstantKey &other) const
1949 if(type_id!=other.type_id)
1950 return type_id<other.type_id;
1951 return int_value<other.int_value;