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