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