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