]> git.tdb.fi Git - libs/gl.git/blob - source/glsl/finalize.cpp
Take care of SPIR-V load IDs in ternary expressions
[libs/gl.git] / source / glsl / finalize.cpp
1 #include <msp/core/algorithm.h>
2 #include <msp/core/hash.h>
3 #include <msp/core/raii.h>
4 #include <msp/strings/lexicalcast.h>
5 #include "finalize.h"
6 #include "glsl_error.h"
7 #include "reflect.h"
8
9 using namespace std;
10
11 namespace Msp {
12 namespace GL {
13 namespace SL {
14
15 void StructOrganizer::visit(StructDeclaration &strct)
16 {
17         SetForScope<int> set_offset(offset, 0);
18         TraversingVisitor::visit(strct);
19 }
20
21 void StructOrganizer::visit(VariableDeclaration &var)
22 {
23         if(offset>=0)
24         {
25                 int *layout_offset = 0;
26                 bool has_matrix_order = false;
27                 if(var.layout)
28                 {
29                         for(Layout::Qualifier &q: var.layout->qualifiers)
30                         {
31                                 if(q.name=="offset" && q.has_value)
32                                 {
33                                         layout_offset = &q.value;
34                                         if(q.value>=offset)
35                                                 offset = q.value;
36                                 }
37                                 else if(q.name=="column_major" || q.name=="row_major")
38                                         has_matrix_order = true;
39                         }
40                 }
41
42                 MemoryRequirementsCalculator::Result mem_reqs = MemoryRequirementsCalculator().apply(var);
43                 offset += mem_reqs.alignment-1;
44                 offset -= offset%mem_reqs.alignment;
45
46                 if(layout_offset)
47                         *layout_offset = offset;
48                 else
49                         add_layout_qualifier(var.layout, Layout::Qualifier("offset", offset));
50
51                 if(!has_matrix_order)
52                 {
53                         const BasicTypeDeclaration *basic = dynamic_cast<const BasicTypeDeclaration *>(var.type_declaration);
54                         while(basic && basic->kind==BasicTypeDeclaration::ARRAY)
55                                 basic = dynamic_cast<const BasicTypeDeclaration *>(basic->base_type);
56                         if(basic && basic->kind==BasicTypeDeclaration::MATRIX)
57                                 add_layout_qualifier(var.layout, Layout::Qualifier("column_major"));
58                 }
59
60                 offset += mem_reqs.size;
61         }
62 }
63
64
65 void LocationAllocator::apply(Module &module, const Features &f, bool a)
66 {
67         features = f;
68         alloc_new = a;
69         for(Stage &s: module.stages)
70                 apply(s);
71
72         if(features.target_api!=VULKAN)
73                 allocate_locations("uniform");
74
75         for(VariableDeclaration *b: unbound_blocks)
76                 bind_uniform(b->layout, b->block_declaration->block_name, features.uniform_binding_range);
77         for(VariableDeclaration *t: unbound_textures)
78                 bind_uniform(t->layout, t->name, features.texture_binding_range);
79 }
80
81 void LocationAllocator::apply(Stage &stage)
82 {
83         swap(used_locations["in"], used_locations["out"]);
84         used_locations["out"].clear();
85
86         stage.content.visit(*this);
87
88         allocate_locations("in");
89         allocate_locations("out");
90 }
91
92 void LocationAllocator::allocate_locations(const string &iface)
93 {
94         auto write = unplaced_variables.begin();
95         unsigned next = 0;
96         for(auto i=unplaced_variables.begin(); i!=unplaced_variables.end(); ++i)
97         {
98                 if((*i)->interface!=iface)
99                 {
100                         if(write!=i)
101                                 *write = *i;
102                         ++write;
103                         continue;
104                 }
105
106                 if((*i)->interface=="uniform")
107                 {
108                         auto j = uniforms.find((*i)->name);
109                         if(j!=uniforms.end() && j->second.location>=0)
110                         {
111                                 add_layout_qualifier((*i)->layout, Layout::Qualifier("location", j->second.location));
112                                 continue;
113                         }
114                 }
115
116                 if(!alloc_new)
117                         continue;
118
119                 set<unsigned> &used = used_locations[(*i)->interface];
120
121                 unsigned size = LocationCounter().apply(**i);
122                 while(1)
123                 {
124                         int blocking = -1;
125                         for(unsigned j=0; j<size; ++j)
126                                 if(used.count(next+j))
127                                         blocking = next+j;
128                         if(blocking<0)
129                                 break;
130                         next = blocking+1;
131                 }
132
133                 add_layout_qualifier((*i)->layout, Layout::Qualifier("location", next));
134                 if((*i)->interface=="uniform")
135                         uniforms[(*i)->name].location = next;
136
137                 for(unsigned j=0; j<size; ++j)
138                         used.insert(next+j);
139                 next += size;
140         }
141
142         unplaced_variables.erase(write, unplaced_variables.end());
143 }
144
145 void LocationAllocator::bind_uniform(RefPtr<Layout> &layout, const string &name, unsigned range)
146 {
147         auto i = uniforms.find(name);
148
149         int desc_set = (i!=uniforms.end() ? i->second.desc_set : 0);
150         if(features.target_api==VULKAN && get_layout_value(layout.get(), "set")<0)
151                 add_layout_qualifier(layout, Layout::Qualifier("set", desc_set));
152
153         if(i!=uniforms.end() && i->second.bind_point>=0)
154                 add_layout_qualifier(layout, Layout::Qualifier("binding", i->second.bind_point));
155         else if(alloc_new)
156         {
157                 set<unsigned> &used = used_bindings[desc_set];
158
159                 unsigned bind_point = hash_fold<32>(hash<64>(name))%range;
160                 while(used.count(bind_point))
161                         bind_point = (bind_point+1)%range;
162
163                 add_layout_qualifier(layout, Layout::Qualifier("binding", bind_point));
164                 uniforms[name].bind_point = bind_point;
165                 used.insert(bind_point);
166         }
167 }
168
169 bool LocationAllocator::visit_uniform(const string &name, RefPtr<Layout> &layout)
170 {
171         int desc_set = 0;
172         int bind_point = get_layout_value(layout.get(), "binding");
173
174         if(features.target_api==VULKAN)
175         {
176                 desc_set = get_layout_value(layout.get(), "set");
177                 if(desc_set<0 && bind_point>=0)
178                 {
179                         desc_set = 0;
180                         add_layout_qualifier(layout, Layout::Qualifier("set", desc_set));
181                 }
182
183                 if(desc_set>=0)
184                         uniforms[name].desc_set = desc_set;
185         }
186
187         if(bind_point>=0)
188         {
189                 used_bindings[desc_set].insert(bind_point);
190                 uniforms[name].bind_point = bind_point;
191         }
192
193         return bind_point>=0;
194 }
195
196 void LocationAllocator::visit(VariableDeclaration &var)
197 {
198         if(!var.name.compare(0, 3, "gl_"))
199                 return;
200
201         if(!var.interface.empty() && !var.block_declaration)
202         {
203                 int location = get_layout_value(var.layout.get(), "location");
204
205                 if(location<0 && var.linked_declaration && var.linked_declaration->layout)
206                 {
207                         location = get_layout_value(var.linked_declaration->layout.get(), "location");
208                         if(location>=0)
209                                 add_layout_qualifier(var.layout, Layout::Qualifier("location", location));
210                 }
211
212                 if(location>=0)
213                 {
214                         unsigned size = LocationCounter().apply(var);
215                         for(unsigned i=0; i<size; ++i)
216                                 used_locations[var.interface].insert(location+i);
217                         if(var.interface=="uniform")
218                                 uniforms[var.name].location = location;
219                 }
220                 else
221                         unplaced_variables.push_back(&var);
222         }
223
224         if(var.interface=="uniform")
225         {
226                 if(var.block_declaration)
227                 {
228                         bool push_constant = has_layout_qualifier(var.layout.get(), "push_constant");
229                         if(!push_constant && !visit_uniform(var.block_declaration->block_name, var.layout))
230                                 unbound_blocks.push_back(&var);
231                 }
232                 else
233                 {
234                         const TypeDeclaration *base_type = get_ultimate_base_type(var.type_declaration);
235                         if(dynamic_cast<const ImageTypeDeclaration *>(base_type) && !visit_uniform(var.name, var.layout))
236                                 unbound_textures.push_back(&var);
237                 }
238         }
239 }
240
241
242 void DepthRangeConverter::apply(Stage &stage, const Features &features)
243 {
244         if(stage.type!=Stage::VERTEX || features.target_api==VULKAN)
245                 return;
246
247         stage.content.visit(*this);
248 }
249
250 void DepthRangeConverter::visit(FunctionDeclaration &func)
251 {
252         if(func.definition==&func && func.name=="main")
253         {
254                 VariableReference *position = new VariableReference;
255                 position->name = "gl_Position";
256
257                 MemberAccess *z = new MemberAccess;
258                 z->left = position;
259                 z->member = "z";
260
261                 Literal *scale = new Literal;
262                 scale->token = "2.0";
263                 scale->value = 2.0f;
264
265                 BinaryExpression *multiply = new BinaryExpression;
266                 multiply->oper = &Operator::get_operator("*", Operator::BINARY);
267                 multiply->left = z;
268                 multiply->right = scale;
269
270                 MemberAccess *w = new MemberAccess;
271                 w->left = position->clone();
272                 w->member = "w";
273
274                 BinaryExpression *subtract = new BinaryExpression;
275                 subtract->oper = &Operator::get_operator("-", Operator::BINARY);
276                 subtract->left = multiply;
277                 subtract->right = w;
278
279                 Assignment *assign = new Assignment;
280                 assign->oper = &Operator::get_operator("=", Operator::BINARY);
281                 assign->left = z->clone();
282                 assign->right = subtract;
283
284                 ExpressionStatement *statement = new ExpressionStatement;
285                 statement->expression = assign;
286
287                 func.body.body.push_back(statement);
288         }
289 }
290
291
292 void PrecisionConverter::apply(Stage &s)
293 {
294         stage = &s;
295         s.content.visit(*this);
296         NodeRemover().apply(s, nodes_to_remove);
297 }
298
299 void PrecisionConverter::visit(Block &block)
300 {
301         for(auto i=block.body.begin(); i!=block.body.end(); ++i)
302         {
303                 if(&block==&stage->content)
304                         insert_point = i;
305                 (*i)->visit(*this);
306         }
307 }
308
309 void PrecisionConverter::visit(Precision &prec)
310 {
311         if(stage->required_features.target_api==OPENGL_ES)
312                 have_default.insert(prec.type);
313         else
314                 nodes_to_remove.insert(&prec);
315 }
316
317 void PrecisionConverter::visit(VariableDeclaration &var)
318 {
319         if(stage->required_features.target_api!=OPENGL_ES)
320         {
321                 var.precision.clear();
322                 return;
323         }
324
325         const char *default_prec = (stage->type==Stage::FRAGMENT ? "mediump" : "highp");
326         const TypeDeclaration *type = var.type_declaration;
327         while(type)
328         {
329                 if(dynamic_cast<const ImageTypeDeclaration *>(type))
330                 {
331                         default_prec = "lowp";
332                         break;
333                 }
334                 else if(const BasicTypeDeclaration *basic = dynamic_cast<const BasicTypeDeclaration *>(type))
335                 {
336                         if(basic->kind==BasicTypeDeclaration::INT || basic->kind==BasicTypeDeclaration::FLOAT)
337                                 break;
338                         type = basic->base_type;
339                 }
340                 else
341                         return;
342         }
343         if(!type)
344                 return;
345
346         if(!have_default.count(type->name))
347         {
348                 Precision *prec = new Precision;
349                 prec->precision = default_prec;
350                 prec->type = type->name;
351                 stage->content.body.insert(insert_point, prec);
352
353                 have_default.insert(type->name);
354         }
355 }
356
357
358 void FeatureConverter::apply(Stage &s, const Features &feat)
359 {
360         stage = &s;
361         features = feat;
362
363         if(!stage->required_features.glsl_version)
364                 stage->required_features.glsl_version = Version(1, (stage->required_features.target_api==OPENGL_ES ? 0 : 10));
365
366         apply();
367 }
368
369 void FeatureConverter::unsupported(const string &reason)
370 {
371         Diagnostic diagnostic;
372         diagnostic.severity = Diagnostic::ERR;
373         diagnostic.source = GENERATED_SOURCE;
374         diagnostic.line = 0;
375         diagnostic.message = reason;
376         stage->diagnostics.push_back(diagnostic);
377 }
378
379 bool FeatureConverter::check_version(const Version &feature_version) const
380 {
381         if(features.glsl_version<feature_version)
382                 return false;
383         else if(stage->required_features.glsl_version<feature_version)
384                 stage->required_features.glsl_version = feature_version;
385
386         return true;
387 }
388
389 bool FeatureConverter::check_extension(bool Features::*extension) const
390 {
391         if(!(features.*extension))
392                 return false;
393
394         stage->required_features.*extension = true;
395
396         return true;
397 }
398
399
400 void StructuralFeatureConverter::apply()
401 {
402         if(supports_stage(stage->type))
403         {
404                 stage->content.visit(*this);
405                 NodeRemover().apply(*stage, nodes_to_remove);
406         }
407         else
408                 unsupported(format("Stage %s is not supported", Stage::get_stage_name(stage->type)));
409 }
410
411 void StructuralFeatureConverter::visit(Block &block)
412 {
413         for(auto i=block.body.begin(); i!=block.body.end(); ++i)
414         {
415                 if(&block==&stage->content)
416                         uniform_insert_point = i;
417                 (*i)->visit(*this);
418         }
419 }
420
421 void StructuralFeatureConverter::visit(RefPtr<Expression> &expr)
422 {
423         r_replaced_reference = 0;
424         expr->visit(*this);
425         if(r_replaced_reference)
426                 expr = r_replaced_reference;
427         r_replaced_reference = 0;
428 }
429
430 bool StructuralFeatureConverter::supports_stage(Stage::Type st) const
431 {
432         if(st==Stage::GEOMETRY)
433         {
434                 if(features.target_api==VULKAN)
435                         return true;
436                 else if(features.target_api==OPENGL_ES)
437                         return check_version(Version(3, 20));
438                 else
439                         return check_version(Version(1, 50));
440         }
441         else
442                 return true;
443 }
444
445 bool StructuralFeatureConverter::supports_unified_interface_syntax() const
446 {
447         if(features.target_api==VULKAN)
448                 return true;
449         else if(features.target_api==OPENGL_ES)
450                 return check_version(Version(3, 0));
451         else
452                 return check_version(Version(1, 30));
453 }
454
455 void StructuralFeatureConverter::visit(VariableReference &var)
456 {
457         if(var.declaration==frag_out && !supports_unified_interface_syntax())
458         {
459                 var.name = "gl_FragColor";
460                 var.declaration = 0;
461         }
462
463         r_flattened_interface = nodes_to_remove.count(var.declaration);
464 }
465
466 void StructuralFeatureConverter::visit(MemberAccess &memacc)
467 {
468         r_flattened_interface = false;
469         visit(memacc.left);
470         if(r_flattened_interface)
471         {
472                 VariableReference *var = new VariableReference;
473                 var->name = memacc.member;
474                 r_replaced_reference = var;
475         }
476 }
477
478 void StructuralFeatureConverter::visit(Assignment &assign)
479 {
480         TraversingVisitor::visit(assign);
481         if(assign.target.declaration==frag_out && !supports_unified_interface_syntax())
482                 assign.target.declaration = 0;
483 }
484
485 bool StructuralFeatureConverter::supports_unified_sampling_functions() const
486 {
487         if(features.target_api==VULKAN)
488                 return true;
489         else if(features.target_api==OPENGL_ES)
490                 return check_version(Version(3, 0));
491         else
492                 return check_version(Version(1, 30));
493 }
494
495 void StructuralFeatureConverter::visit(FunctionCall &call)
496 {
497         if(call.declaration && call.declaration->source==BUILTIN_SOURCE)
498         {
499                 if(!call.name.compare(0, 7, "texture") && call.arguments.size()>=1)
500                 {
501                         const ImageTypeDeclaration *arg_image = dynamic_cast<const ImageTypeDeclaration *>(call.arguments.front()->type);
502                         if(arg_image && !supports_unified_sampling_functions())
503                         {
504                                 string suffix = call.name.substr(7);
505                                 call.name = (arg_image->shadow ? "shadow" : "texture");
506
507                                 switch(arg_image->dimensions)
508                                 {
509                                 case ImageTypeDeclaration::ONE: call.name += "1D"; break;
510                                 case ImageTypeDeclaration::TWO: call.name += "2D"; break;
511                                 case ImageTypeDeclaration::THREE: call.name += "3D"; break;
512                                 case ImageTypeDeclaration::CUBE: call.name += "Cube"; break;
513                                 }
514
515                                 if(arg_image->array)
516                                 {
517                                         /* Array textures and the unified sampling function name were
518                                         both introduced in GLSL 1.30. */
519                                         if(arg_image->dimensions==ImageTypeDeclaration::ONE || arg_image->dimensions==ImageTypeDeclaration::TWO)
520                                                 check_extension(&Features::ext_texture_array);
521                                         call.name += "Array";
522                                 }
523
524                                 call.name += suffix;
525                         }
526                 }
527         }
528
529         TraversingVisitor::visit(call);
530 }
531
532 bool StructuralFeatureConverter::supports_interface_blocks(const string &iface) const
533 {
534         if(features.target_api==VULKAN)
535                 return true;
536         else if(features.target_api==OPENGL_ES)
537         {
538                 if(iface=="uniform")
539                         return check_version(Version(3, 0));
540                 else
541                         return check_version(Version(3, 20));
542         }
543         else if(check_version(Version(1, 50)))
544                 return true;
545         else if(iface=="uniform")
546                 return check_extension(&Features::arb_uniform_buffer_object);
547         else
548                 return false;
549 }
550
551 void StructuralFeatureConverter::visit(VariableDeclaration &var)
552 {
553         if(var.block_declaration)
554         {
555                 bool push_constant = has_layout_qualifier(var.layout.get(), "push_constant");
556                 if(!supports_interface_blocks(var.interface) || (push_constant && features.target_api!=VULKAN))
557                 {
558                         if(var.name.find(' ')==string::npos)
559                                 unsupported("ARB_uniform_buffer_object required for interface block instances");
560                         else
561                         {
562                                 for(const RefPtr<Statement> &s: var.block_declaration->members.body)
563                                         if(VariableDeclaration *mem = dynamic_cast<VariableDeclaration *>(s.get()))
564                                                 mem->interface = var.interface;
565                                 stage->content.body.splice(uniform_insert_point, var.block_declaration->members.body);
566                                 nodes_to_remove.insert(&var);
567                                 nodes_to_remove.insert(var.block_declaration);
568                         }
569                 }
570         }
571
572         if((var.interface=="in" || var.interface=="out") && !supports_unified_interface_syntax())
573                 if(stage->type==Stage::FRAGMENT && var.interface=="out")
574                 {
575                         frag_out = &var;
576                         nodes_to_remove.insert(&var);
577                 }
578
579         TraversingVisitor::visit(var);
580 }
581
582
583 void QualifierConverter::apply()
584 {
585         stage->content.visit(*this);
586 }
587
588 bool QualifierConverter::supports_interface_layouts() const
589 {
590         if(features.target_api==VULKAN)
591                 return true;
592         else if(features.target_api==OPENGL_ES)
593                 return check_version(Version(3, 0));
594         else if(check_version(Version(3, 30)))
595                 return true;
596         else if(check_version(Version(1, 30)))
597                 return check_extension(&Features::arb_explicit_attrib_location);
598         else
599                 return false;
600 }
601
602 bool QualifierConverter::supports_stage_interface_layouts() const
603 {
604         if(features.target_api==VULKAN)
605                 return true;
606         else if(features.target_api==OPENGL_ES)
607                 return check_version(Version(3, 10));
608         else if(check_version(Version(4, 10)))
609                 return true;
610         else
611                 return check_extension(&Features::arb_separate_shader_objects);
612 }
613
614 bool QualifierConverter::supports_centroid_sampling() const
615 {
616         if(features.target_api==VULKAN)
617                 return true;
618         else if(features.target_api==OPENGL_ES)
619                 return check_version(Version(3, 0));
620         else if(check_version(Version(1, 20)))
621                 return true;
622         else
623                 return check_extension(&Features::ext_gpu_shader4);
624 }
625
626 bool QualifierConverter::supports_sample_sampling() const
627 {
628         if(features.target_api==VULKAN)
629                 return true;
630         else if(features.target_api==OPENGL_ES)
631                 return check_version(Version(3, 20));
632         else if(check_version(Version(4, 0)))
633                 return true;
634         else
635                 return check_extension(&Features::arb_gpu_shader5);
636 }
637
638 bool QualifierConverter::supports_uniform_location() const
639 {
640         if(features.target_api==VULKAN)
641                 return false;
642         else if(features.target_api==OPENGL_ES)
643                 return check_version(Version(3, 10));
644         else if(check_version(Version(4, 30)))
645                 return true;
646         else
647                 return check_extension(&Features::arb_explicit_uniform_location);
648 }
649
650 bool QualifierConverter::supports_binding() const
651 {
652         if(features.target_api==VULKAN)
653                 return true;
654         else if(features.target_api==OPENGL_ES)
655                 return check_version(Version(3, 10));
656         else
657                 return check_version(Version(4, 20));
658 }
659
660 bool QualifierConverter::supports_interface_block_location() const
661 {
662         if(features.target_api==VULKAN)
663                 return true;
664         else if(features.target_api==OPENGL_ES)
665                 return check_version(Version(3, 20));
666         else if(check_version(Version(4, 40)))
667                 return true;
668         else
669                 return check_extension(&Features::arb_enhanced_layouts);
670 }
671
672 void QualifierConverter::visit(VariableDeclaration &var)
673 {
674         if(var.layout)
675         {
676                 for(auto i=var.layout->qualifiers.begin(); i!=var.layout->qualifiers.end(); )
677                 {
678                         if(i->name=="location")
679                         {
680                                 bool supported = true;
681                                 bool external = false;
682                                 if(var.block_declaration)
683                                         supported = supports_interface_block_location();
684                                 else if(var.interface=="in")
685                                 {
686                                         external = (stage->type==Stage::VERTEX);
687                                         supported = (external ? supports_interface_layouts() : supports_stage_interface_layouts());
688                                 }
689                                 else if(var.interface=="out")
690                                 {
691                                         external = (stage->type==Stage::FRAGMENT);
692                                         supported = (external ? supports_interface_layouts() : supports_stage_interface_layouts());
693                                         if(external && !supported && !check_extension(&Features::ext_gpu_shader4))
694                                         {
695                                                 external = false;
696                                                 if(i->value!=0)
697                                                         unsupported("EXT_gpu_shader4 required for multiple fragment shader outputs");
698                                         }
699                                 }
700                                 else if(var.interface=="uniform")
701                                         supported = supports_uniform_location();
702
703                                 if(!supported)
704                                 {
705                                         if(external)
706                                                 stage->locations[var.name] = i->value;
707                                         i = var.layout->qualifiers.erase(i);
708                                 }
709                                 else
710                                         ++i;
711                         }
712                         else if(i->name=="binding" && !supports_binding())
713                         {
714                                 if(var.block_declaration)
715                                         stage->uniform_block_bindings[var.block_declaration->block_name] = i->value;
716                                 else if(dynamic_cast<const ImageTypeDeclaration *>(get_ultimate_base_type(var.type_declaration)))
717                                         stage->texture_bindings[var.name] = i->value;
718
719                                 i = var.layout->qualifiers.erase(i);
720                         }
721                         else
722                                 ++i;
723                 }
724
725                 if(var.layout->qualifiers.empty())
726                         var.layout = 0;
727         }
728
729         if(var.sampling=="centroid")
730         {
731                 if(!supports_centroid_sampling())
732                         var.sampling = string();
733         }
734         else if(var.sampling=="sample")
735         {
736                 if(!supports_sample_sampling())
737                         var.sampling = string();
738         }
739
740         if(var.name=="gl_ClipDistance")
741                 if(const Literal *literal_size = dynamic_cast<const Literal *>(var.array_size.get()))
742                         stage->n_clip_distances = literal_size->value.value<int>();
743
744         TraversingVisitor::visit(var);
745 }
746
747 } // namespace SL
748 } // namespace GL
749 } // namespace Msp