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