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