]> git.tdb.fi Git - libs/gl.git/blob - source/glsl/compiler.cpp
Take care of SPIR-V load IDs in ternary expressions
[libs/gl.git] / source / glsl / compiler.cpp
1 #include <msp/core/algorithm.h>
2 #include <msp/strings/format.h>
3 #include <msp/strings/utils.h>
4 #include "builtin.h"
5 #include "compiler.h"
6 #include "debug.h"
7 #include "error.h"
8 #include "finalize.h"
9 #include "generate.h"
10 #include "glsl_error.h"
11 #include "modulecache.h"
12 #include "optimize.h"
13 #include "output.h"
14 #include "resolve.h"
15 #include "spirv.h"
16 #include "validate.h"
17
18 #undef interface
19
20 using namespace std;
21
22 namespace Msp {
23 namespace GL {
24 namespace SL {
25
26 Compiler::Compiler(const Features &f):
27         features(f)
28 { }
29
30 Compiler::~Compiler()
31 {
32         delete module;
33 }
34
35 void Compiler::clear()
36 {
37         delete module;
38         module = new Module();
39         imported_names.clear();
40         module->source_map.set_name(0, "<generated>");
41 }
42
43 void Compiler::set_source(const string &source, const string &src_name)
44 {
45         clear();
46         imported_names.push_back(src_name);
47         ModuleCache mod_cache(0);
48         append_module(mod_cache.add_module(source, src_name), mod_cache);
49 }
50
51 void Compiler::load_source(IO::Base &io, DataFile::Collection *res, const string &src_name)
52 {
53         clear();
54         imported_names.push_back(src_name);
55         ModuleCache mod_cache(res);
56         append_module(mod_cache.add_module(io, src_name), mod_cache);
57 }
58
59 void Compiler::load_source(IO::Base &io, const string &src_name)
60 {
61         load_source(io, 0, src_name);
62 }
63
64 void Compiler::specialize(const map<string, int> &sv)
65 {
66         specialized = true;
67         spec_values = sv;
68 }
69
70 void Compiler::compile(Mode mode)
71 {
72         if(specialized && mode!=PROGRAM)
73                 throw invalid_operation("Compiler::compile");
74
75         for(Stage &s: module->stages)
76                 generate(s);
77         ConstantIdAssigner().apply(*module, features);
78         LocationAllocator().apply(*module, features, false);
79
80         for(Stage &s: module->stages)
81                 validate(s);
82         GlobalInterfaceValidator().apply(*module);
83
84         bool valid = true;
85         for(Stage &s: module->stages)
86                 if(!check_errors(s))
87                         valid = false;
88         if(!valid)
89                 throw invalid_shader_source(get_diagnostics());
90
91         if(specialized)
92         {
93                 for(Stage &s: module->stages)
94                         ConstantSpecializer().apply(s, spec_values);
95         }
96         if(mode==PROGRAM)
97         {
98                 for(Stage &s: module->stages)
99                         DepthRangeConverter().apply(s, features);
100         }
101         for(auto i=module->stages.begin(); i!=module->stages.end(); )
102         {
103                 OptimizeResult result = optimize(*i);
104                 if(result==REDO_PREVIOUS)
105                         i = module->stages.begin();
106                 else if(result!=REDO_STAGE)
107                         ++i;
108         }
109
110         for(Stage &s: module->stages)
111         {
112                 StructuralFeatureConverter().apply(s, features);
113                 resolve(s, RESOLVE_VARIABLES|RESOLVE_FUNCTIONS);
114         }
115         LocationAllocator().apply(*module, features);
116         for(Stage &s: module->stages)
117                 finalize(s, mode);
118
119         compiled = true;
120 }
121
122 string Compiler::get_combined_glsl() const
123 {
124         if(!compiled)
125                 throw invalid_operation("Compiler::get_combined_glsl");
126
127         string glsl;
128
129         unsigned source_count = module->source_map.get_count();
130         for(unsigned i=1; i<source_count; ++i)
131                 glsl += format("#pragma MSP source(%d, \"%s\")\n", i, module->source_map.get_name(i));
132         for(Stage &s: module->stages)
133         {
134                 glsl += format("#pragma MSP stage(%s)\n", Stage::get_stage_name(s.type));
135                 glsl += Formatter().apply(s);
136                 glsl += '\n';
137         }
138
139         return glsl;
140 }
141
142 vector<Stage::Type> Compiler::get_stages() const
143 {
144         vector<Stage::Type> stage_types;
145         stage_types.reserve(module->stages.size());
146         for(const Stage &s: module->stages)
147                 stage_types.push_back(s.type);
148         return stage_types;
149 }
150
151 string Compiler::get_stage_glsl(Stage::Type stage_type) const
152 {
153         if(!compiled)
154                 throw invalid_operation("Compiler::get_stage_glsl");
155         auto i = find_member(module->stages, stage_type, &Stage::type);
156         if(i!=module->stages.end())
157                 return Formatter().apply(*i);
158         throw key_error(Stage::get_stage_name(stage_type));
159 }
160
161 vector<uint32_t> Compiler::get_combined_spirv() const
162 {
163         if(!compiled)
164                 throw invalid_operation("Compiler::get_combined_spirv");
165         SpirVGenerator gen;
166         gen.apply(*module, features);
167         return gen.get_code();
168 }
169
170 const map<string, unsigned> &Compiler::get_vertex_attributes() const
171 {
172         if(!compiled)
173                 throw invalid_operation("Compiler::get_vertex_attributes");
174         auto i = find_member(module->stages, Stage::VERTEX, &Stage::type);
175         if(i!=module->stages.end())
176                 return i->locations;
177         throw invalid_operation("Compiler::get_vertex_attributes");
178 }
179
180 const map<string, unsigned> &Compiler::get_fragment_outputs() const
181 {
182         if(!compiled)
183                 throw invalid_operation("Compiler::get_fragment_outputs");
184         auto i = find_member(module->stages, Stage::FRAGMENT, &Stage::type);
185         if(i!=module->stages.end())
186                 return i->locations;
187         throw invalid_operation("Compiler::get_fragment_outputs");
188 }
189
190 const map<string, unsigned> &Compiler::get_texture_bindings() const
191 {
192         if(!compiled)
193                 throw invalid_operation("Compiler::get_texture_bindings");
194         return module->shared.texture_bindings;
195 }
196
197 const map<string, unsigned> &Compiler::get_uniform_block_bindings() const
198 {
199         if(!compiled)
200                 throw invalid_operation("Compiler::get_uniform_block_bindings");
201         return module->shared.uniform_block_bindings;
202 }
203
204 unsigned Compiler::get_n_clip_distances() const
205 {
206         if(!compiled)
207                 throw invalid_operation("Compiler::get_n_clip_distances");
208         auto i = find_member(module->stages, Stage::VERTEX, &Stage::type);
209         return (i!=module->stages.end() ? i->n_clip_distances : 0);
210 }
211
212 const SourceMap &Compiler::get_source_map() const
213 {
214         return module->source_map;
215 }
216
217 string Compiler::get_stage_debug(Stage::Type stage_type, bool use_colors) const
218 {
219         auto i = find_member(module->stages, stage_type, &Stage::type);
220         if(i!=module->stages.end())
221                 return DumpTree(use_colors).apply(*i);
222         throw key_error(Stage::get_stage_name(stage_type));
223 }
224
225 string Compiler::get_diagnostics() const
226 {
227         string combined;
228         for(const Stage &s: module->stages)
229                 for(const Diagnostic &d: s.diagnostics)
230                         if(d.source!=INTERNAL_SOURCE)
231                                 append(combined, "\n", format("%s:%d: %s", module->source_map.get_name(d.source), d.line, d.message));
232         return combined;
233 }
234
235 void Compiler::append_module(const Module &mod, ModuleCache &mod_cache)
236 {
237         module->source_map.merge_from(mod.source_map);
238
239         vector<Import *> imports;
240         for(const RefPtr<Statement> &s: mod.shared.content.body)
241                 if(Import *imp = dynamic_cast<Import *>(s.get()))
242                         imports.push_back(imp);
243         for(Import *i: imports)
244                 import(mod_cache, i->module);
245
246         append_stage(mod.shared);
247         for(const Stage &s: mod.stages)
248                 append_stage(s);
249 }
250
251 void Compiler::append_stage(const Stage &stage)
252 {
253         Stage *target = 0;
254         if(stage.type==Stage::SHARED)
255                 target = &module->shared;
256         else
257         {
258                 auto i = find_if(module->stages, [&stage](const Stage &s){ return s.type>=stage.type; });
259                 if(i==module->stages.end() || i->type>stage.type)
260                 {
261                         auto j = module->stages.insert(i, stage.type);
262                         if(i!=module->stages.end())
263                                 i->previous = &*j;
264                         i = j;
265                         if(i!=module->stages.begin())
266                                 i->previous = &*--j;
267                 }
268
269                 target = &*i;
270         }
271
272         if(stage.required_features.glsl_version>target->required_features.glsl_version)
273                 target->required_features.glsl_version = stage.required_features.glsl_version;
274         for(const RefPtr<Statement> &s: stage.content.body)
275                 if(!dynamic_cast<Import *>(s.get()))
276                         target->content.body.push_back(s);
277 }
278
279 void Compiler::import(ModuleCache &mod_cache, const string &name)
280 {
281         if(find(imported_names, name)!=imported_names.end())
282                 return;
283         imported_names.push_back(name);
284
285         append_module(mod_cache.get_module(name), mod_cache);
286 }
287
288 void Compiler::generate(Stage &stage)
289 {
290         stage.required_features.target_api = features.target_api;
291         if(module->shared.required_features.glsl_version>stage.required_features.glsl_version)
292                 stage.required_features.glsl_version = module->shared.required_features.glsl_version;
293
294         inject_block(stage.content, module->shared.content);
295         if(const Stage *builtins = get_builtins(stage.type))
296                 inject_block(stage.content, builtins->content);
297         if(const Stage *builtins = get_builtins(Stage::SHARED))
298                 inject_block(stage.content, builtins->content);
299
300         // Initial resolving pass
301         resolve(stage);
302
303         /* All variables local to a stage have been resolved.  Resolve non-local
304         variables through interfaces. */
305         InterfaceGenerator().apply(stage);
306         resolve(stage, RESOLVE_BLOCKS|RESOLVE_TYPES|RESOLVE_VARIABLES);
307
308         ArraySizer().apply(stage);
309         resolve(stage, RESOLVE_EXPRESSIONS);
310 }
311
312 template<typename T>
313 bool Compiler::resolve(Stage &stage, unsigned &flags, unsigned bit)
314 {
315         if(!(flags&bit))
316                 return false;
317
318         flags &= ~bit;
319         return T().apply(stage);
320 }
321
322 void Compiler::resolve(Stage &stage, unsigned flags)
323 {
324         while(flags)
325         {
326                 if(resolve<BlockHierarchyResolver>(stage, flags, RESOLVE_BLOCKS))
327                         ;
328                 else if(resolve<TypeResolver>(stage, flags, RESOLVE_TYPES))
329                         flags |= RESOLVE_BLOCKS|RESOLVE_VARIABLES|RESOLVE_EXPRESSIONS;
330                 else if(resolve<VariableResolver>(stage, flags, RESOLVE_VARIABLES))
331                         flags |= RESOLVE_EXPRESSIONS;
332                 else if(resolve<FunctionResolver>(stage, flags, RESOLVE_FUNCTIONS))
333                         flags |= RESOLVE_EXPRESSIONS;
334                 else if(resolve<ExpressionResolver>(stage, flags, RESOLVE_EXPRESSIONS))
335                         flags |= RESOLVE_VARIABLES|RESOLVE_FUNCTIONS;
336         }
337 }
338
339 void Compiler::validate(Stage &stage)
340 {
341         DeclarationValidator().apply(stage, features);
342         IdentifierValidator().apply(stage);
343         ReferenceValidator().apply(stage);
344         ExpressionValidator().apply(stage);
345         FlowControlValidator().apply(stage);
346         StageInterfaceValidator().apply(stage);
347 }
348
349 bool Compiler::check_errors(Stage &stage)
350 {
351         stable_sort(stage.diagnostics, &diagnostic_line_order);
352         return !any_of(stage.diagnostics.begin(), stage.diagnostics.end(),
353                 [](const Diagnostic &d){ return d.severity==Diagnostic::ERR; });
354 }
355
356 bool Compiler::diagnostic_line_order(const Diagnostic &diag1, const Diagnostic &diag2)
357 {
358         if(diag1.provoking_source!=diag2.provoking_source)
359         {
360                 // Sort builtins first and imported modules according to import order.
361                 if(diag1.provoking_source<=BUILTIN_SOURCE)
362                         return diag1.provoking_source<diag2.provoking_source;
363                 else if(diag2.provoking_source<=BUILTIN_SOURCE)
364                         return false;
365                 else
366                         return diag1.provoking_source>diag2.provoking_source;
367         }
368         return diag1.provoking_line<diag2.provoking_line;
369 }
370
371 Compiler::OptimizeResult Compiler::optimize(Stage &stage)
372 {
373         if(ConstantFolder().apply(stage))
374                 resolve(stage, RESOLVE_EXPRESSIONS);
375         if(ConstantConditionEliminator().apply(stage))
376                 resolve(stage, RESOLVE_VARIABLES);
377
378         bool any_inlined = false;
379         if(FunctionInliner().apply(stage))
380         {
381                 resolve(stage, RESOLVE_TYPES|RESOLVE_VARIABLES|RESOLVE_FUNCTIONS|RESOLVE_EXPRESSIONS);
382                 any_inlined = true;
383         }
384         if(AggregateDismantler().apply(stage))
385         {
386                 resolve(stage, RESOLVE_TYPES|RESOLVE_VARIABLES|RESOLVE_FUNCTIONS|RESOLVE_EXPRESSIONS);
387                 any_inlined = true;
388         }
389         if(ExpressionInliner().apply(stage))
390         {
391                 resolve(stage, RESOLVE_VARIABLES|RESOLVE_FUNCTIONS|RESOLVE_EXPRESSIONS);
392                 any_inlined = true;
393         }
394
395         /* Removing variables or functions may cause things from the previous stage
396         to become unused. */
397         bool any_removed = UnreachableCodeRemover().apply(stage);
398         any_removed |= UnusedVariableRemover().apply(stage);
399         any_removed |= UnusedFunctionRemover().apply(stage);
400         any_removed |= UnusedTypeRemover().apply(stage);
401
402         return any_removed ? REDO_PREVIOUS : any_inlined ? REDO_STAGE : NEXT_STAGE;
403 }
404
405 void Compiler::finalize(Stage &stage, Mode mode)
406 {
407         QualifierConverter().apply(stage, features);
408         PrecisionConverter().apply(stage);
409         if(mode==SPIRV)
410                 StructOrganizer().apply(stage);
411
412         // Collect bindings from all stages into the shared stage's maps
413         module->shared.texture_bindings.insert(stage.texture_bindings.begin(), stage.texture_bindings.end());
414         module->shared.uniform_block_bindings.insert(stage.uniform_block_bindings.begin(), stage.uniform_block_bindings.end());
415 }
416
417 void Compiler::inject_block(Block &target, const Block &source)
418 {
419         auto insert_point = target.body.begin();
420         for(const RefPtr<Statement> &s: source.body)
421                 target.body.insert(insert_point, s->clone());
422 }
423
424 } // namespace SL
425 } // namespace GL
426 } // namespace Msp