1 #include <msp/core/algorithm.h>
2 #include <msp/strings/format.h>
3 #include <msp/strings/utils.h>
10 #include "glsl_error.h"
11 #include "modulecache.h"
26 Compiler::Compiler(const Features &f):
35 void Compiler::clear()
38 module = new Module();
39 imported_names.clear();
40 module->source_map.set_name(0, "<generated>");
43 void Compiler::set_source(const string &source, const string &src_name)
46 imported_names.push_back(src_name);
47 ModuleCache mod_cache(0);
48 append_module(mod_cache.add_module(source, src_name), mod_cache);
51 void Compiler::load_source(IO::Base &io, DataFile::Collection *res, const string &src_name)
54 imported_names.push_back(src_name);
55 ModuleCache mod_cache(res);
56 append_module(mod_cache.add_module(io, src_name), mod_cache);
59 void Compiler::load_source(IO::Base &io, const string &src_name)
61 load_source(io, 0, src_name);
64 void Compiler::specialize(const map<string, int> &sv)
70 void Compiler::compile(Mode mode)
72 if(specialized && mode!=PROGRAM)
73 throw invalid_operation("Compiler::compile");
75 for(Stage &s: module->stages)
77 ConstantIdAssigner().apply(*module, features);
78 LocationAllocator().apply(*module, features, false);
80 for(Stage &s: module->stages)
82 GlobalInterfaceValidator().apply(*module);
85 for(Stage &s: module->stages)
89 throw invalid_shader_source(get_diagnostics());
93 for(Stage &s: module->stages)
94 ConstantSpecializer().apply(s, spec_values);
98 for(Stage &s: module->stages)
99 DepthRangeConverter().apply(s, features);
101 for(auto i=module->stages.begin(); i!=module->stages.end(); )
103 OptimizeResult result = optimize(*i);
104 if(result==REDO_PREVIOUS)
105 i = module->stages.begin();
106 else if(result!=REDO_STAGE)
110 Stage *prev_stage = 0;
111 for(auto i=module->stages.begin(); i!=module->stages.end(); )
113 if(i->functions.empty())
114 i = module->stages.erase(i);
117 i->previous = prev_stage;
123 for(Stage &s: module->stages)
125 StructuralFeatureConverter().apply(s, features);
126 resolve(s, RESOLVE_VARIABLES|RESOLVE_FUNCTIONS);
128 LocationAllocator().apply(*module, features);
129 for(Stage &s: module->stages)
135 string Compiler::get_combined_glsl() const
138 throw invalid_operation("Compiler::get_combined_glsl");
142 unsigned source_count = module->source_map.get_count();
143 for(unsigned i=1; i<source_count; ++i)
144 glsl += format("#pragma MSP source(%d, \"%s\")\n", i, module->source_map.get_name(i));
145 for(Stage &s: module->stages)
147 glsl += format("#pragma MSP stage(%s)\n", Stage::get_stage_name(s.type));
148 glsl += Formatter().apply(s);
155 vector<Stage::Type> Compiler::get_stages() const
157 vector<Stage::Type> stage_types;
158 stage_types.reserve(module->stages.size());
159 for(const Stage &s: module->stages)
160 stage_types.push_back(s.type);
164 string Compiler::get_stage_glsl(Stage::Type stage_type) const
167 throw invalid_operation("Compiler::get_stage_glsl");
168 auto i = find_member(module->stages, stage_type, &Stage::type);
169 if(i!=module->stages.end())
170 return Formatter().apply(*i);
171 throw key_error(Stage::get_stage_name(stage_type));
174 vector<uint32_t> Compiler::get_combined_spirv() const
177 throw invalid_operation("Compiler::get_combined_spirv");
179 gen.apply(*module, features);
180 return gen.get_code();
183 const map<string, unsigned> &Compiler::get_vertex_attributes() const
186 throw invalid_operation("Compiler::get_vertex_attributes");
187 auto i = find_member(module->stages, Stage::VERTEX, &Stage::type);
188 if(i!=module->stages.end())
190 throw invalid_operation("Compiler::get_vertex_attributes");
193 const map<string, unsigned> &Compiler::get_fragment_outputs() const
196 throw invalid_operation("Compiler::get_fragment_outputs");
197 auto i = find_member(module->stages, Stage::FRAGMENT, &Stage::type);
198 if(i!=module->stages.end())
200 throw invalid_operation("Compiler::get_fragment_outputs");
203 const map<string, unsigned> &Compiler::get_texture_bindings() const
206 throw invalid_operation("Compiler::get_texture_bindings");
207 return module->shared.texture_bindings;
210 const map<string, unsigned> &Compiler::get_uniform_block_bindings() const
213 throw invalid_operation("Compiler::get_uniform_block_bindings");
214 return module->shared.uniform_block_bindings;
217 unsigned Compiler::get_n_clip_distances() const
220 throw invalid_operation("Compiler::get_n_clip_distances");
221 auto i = find_member(module->stages, Stage::VERTEX, &Stage::type);
222 return (i!=module->stages.end() ? i->n_clip_distances : 0);
225 const SourceMap &Compiler::get_source_map() const
227 return module->source_map;
230 string Compiler::get_stage_debug(Stage::Type stage_type, bool use_colors) const
232 auto i = find_member(module->stages, stage_type, &Stage::type);
233 if(i!=module->stages.end())
234 return DumpTree(use_colors).apply(*i);
235 throw key_error(Stage::get_stage_name(stage_type));
238 string Compiler::get_diagnostics() const
241 for(const Stage &s: module->stages)
242 for(const Diagnostic &d: s.diagnostics)
243 if(d.source!=INTERNAL_SOURCE)
244 append(combined, "\n", format("%s:%d: %s", module->source_map.get_name(d.source), d.line, d.message));
248 void Compiler::append_module(const Module &mod, ModuleCache &mod_cache)
250 module->source_map.merge_from(mod.source_map);
252 vector<Import *> imports;
253 for(const RefPtr<Statement> &s: mod.shared.content.body)
254 if(Import *imp = dynamic_cast<Import *>(s.get()))
255 imports.push_back(imp);
256 for(Import *i: imports)
257 import(mod_cache, i->module);
259 append_stage(mod.shared);
260 for(const Stage &s: mod.stages)
264 void Compiler::append_stage(const Stage &stage)
267 if(stage.type==Stage::SHARED)
268 target = &module->shared;
271 auto i = find_if(module->stages, [&stage](const Stage &s){ return s.type>=stage.type; });
272 if(i==module->stages.end() || i->type>stage.type)
274 auto j = module->stages.insert(i, stage.type);
275 if(i!=module->stages.end())
278 if(i!=module->stages.begin())
285 if(stage.required_features.glsl_version>target->required_features.glsl_version)
286 target->required_features.glsl_version = stage.required_features.glsl_version;
287 for(const RefPtr<Statement> &s: stage.content.body)
288 if(!dynamic_cast<Import *>(s.get()))
289 target->content.body.push_back(s);
292 void Compiler::import(ModuleCache &mod_cache, const string &name)
294 if(find(imported_names, name)!=imported_names.end())
296 imported_names.push_back(name);
298 append_module(mod_cache.get_module(name), mod_cache);
301 void Compiler::generate(Stage &stage)
303 stage.required_features.target_api = features.target_api;
304 if(module->shared.required_features.glsl_version>stage.required_features.glsl_version)
305 stage.required_features.glsl_version = module->shared.required_features.glsl_version;
307 inject_block(stage.content, module->shared.content);
308 if(const Stage *builtins = get_builtins(stage.type))
309 inject_block(stage.content, builtins->content);
310 if(const Stage *builtins = get_builtins(Stage::SHARED))
311 inject_block(stage.content, builtins->content);
313 // Initial resolving pass
316 /* All variables local to a stage have been resolved. Resolve non-local
317 variables through interfaces. */
318 InterfaceGenerator().apply(stage);
319 resolve(stage, RESOLVE_BLOCKS|RESOLVE_TYPES|RESOLVE_VARIABLES);
321 LayoutDefaulter().apply(stage);
322 ArraySizer().apply(stage);
323 resolve(stage, RESOLVE_EXPRESSIONS);
327 bool Compiler::resolve(Stage &stage, unsigned &flags, unsigned bit)
333 return T().apply(stage);
336 void Compiler::resolve(Stage &stage, unsigned flags)
340 if(resolve<BlockHierarchyResolver>(stage, flags, RESOLVE_BLOCKS))
342 else if(resolve<TypeResolver>(stage, flags, RESOLVE_TYPES))
343 flags |= RESOLVE_BLOCKS|RESOLVE_VARIABLES|RESOLVE_EXPRESSIONS;
344 else if(resolve<VariableResolver>(stage, flags, RESOLVE_VARIABLES))
345 flags |= RESOLVE_EXPRESSIONS;
346 else if(resolve<FunctionResolver>(stage, flags, RESOLVE_FUNCTIONS))
347 flags |= RESOLVE_EXPRESSIONS;
348 else if(resolve<ExpressionResolver>(stage, flags, RESOLVE_EXPRESSIONS))
349 flags |= RESOLVE_VARIABLES|RESOLVE_FUNCTIONS;
353 void Compiler::validate(Stage &stage)
355 DeclarationValidator().apply(stage, features);
356 IdentifierValidator().apply(stage);
357 ReferenceValidator().apply(stage);
358 ExpressionValidator().apply(stage);
359 FlowControlValidator().apply(stage);
360 StageInterfaceValidator().apply(stage);
363 bool Compiler::check_errors(Stage &stage)
365 stable_sort(stage.diagnostics, &diagnostic_line_order);
366 return !any_of(stage.diagnostics.begin(), stage.diagnostics.end(),
367 [](const Diagnostic &d){ return d.severity==Diagnostic::ERR; });
370 bool Compiler::diagnostic_line_order(const Diagnostic &diag1, const Diagnostic &diag2)
372 if(diag1.provoking_source!=diag2.provoking_source)
374 // Sort builtins first and imported modules according to import order.
375 if(diag1.provoking_source<=BUILTIN_SOURCE)
376 return diag1.provoking_source<diag2.provoking_source;
377 else if(diag2.provoking_source<=BUILTIN_SOURCE)
380 return diag1.provoking_source>diag2.provoking_source;
382 return diag1.provoking_line<diag2.provoking_line;
385 Compiler::OptimizeResult Compiler::optimize(Stage &stage)
387 if(ConstantFolder().apply(stage))
388 resolve(stage, RESOLVE_EXPRESSIONS);
389 if(ConstantConditionEliminator().apply(stage))
390 resolve(stage, RESOLVE_VARIABLES);
392 bool any_inlined = false;
393 if(FunctionInliner().apply(stage))
395 resolve(stage, RESOLVE_TYPES|RESOLVE_VARIABLES|RESOLVE_FUNCTIONS|RESOLVE_EXPRESSIONS);
398 if(AggregateDismantler().apply(stage))
400 resolve(stage, RESOLVE_TYPES|RESOLVE_VARIABLES|RESOLVE_FUNCTIONS|RESOLVE_EXPRESSIONS);
403 if(ExpressionInliner().apply(stage))
405 resolve(stage, RESOLVE_VARIABLES|RESOLVE_FUNCTIONS|RESOLVE_EXPRESSIONS);
409 /* Removing variables or functions may cause things from the previous stage
411 bool any_removed = UnreachableCodeRemover().apply(stage);
412 any_removed |= UnusedVariableRemover().apply(stage);
413 any_removed |= UnusedFunctionRemover().apply(stage);
414 any_removed |= UnusedTypeRemover().apply(stage);
416 return any_removed ? REDO_PREVIOUS : any_inlined ? REDO_STAGE : NEXT_STAGE;
419 void Compiler::finalize(Stage &stage, Mode mode)
421 QualifierConverter().apply(stage, features);
422 PrecisionConverter().apply(stage);
424 StructOrganizer().apply(stage);
426 // Collect bindings from all stages into the shared stage's maps
427 module->shared.texture_bindings.insert(stage.texture_bindings.begin(), stage.texture_bindings.end());
428 module->shared.uniform_block_bindings.insert(stage.uniform_block_bindings.begin(), stage.uniform_block_bindings.end());
431 void Compiler::inject_block(Block &target, const Block &source)
433 auto insert_point = target.body.begin();
434 for(const RefPtr<Statement> &s: source.body)
435 target.body.insert(insert_point, s->clone());