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