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