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