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