blob: 5b502dce2fb2b5511527462cd478d662730d2a9a [file] [log] [blame]
ethannicholasb3058bd2016-07-01 08:22:01 -07001/*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "SkSLCompiler.h"
9
10#include <fstream>
11#include <streambuf>
12
ethannicholas5961bc92016-10-12 06:39:56 -070013#include "ast/SkSLASTPrecision.h"
ethannicholas22f939e2016-10-13 13:25:34 -070014#include "SkSLCFGGenerator.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070015#include "SkSLIRGenerator.h"
16#include "SkSLParser.h"
17#include "SkSLSPIRVCodeGenerator.h"
18#include "ir/SkSLExpression.h"
19#include "ir/SkSLIntLiteral.h"
ethannicholas5961bc92016-10-12 06:39:56 -070020#include "ir/SkSLModifiersDeclaration.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070021#include "ir/SkSLSymbolTable.h"
ethannicholasddb37d62016-10-20 09:54:00 -070022#include "ir/SkSLUnresolvedFunction.h"
ethannicholas22f939e2016-10-13 13:25:34 -070023#include "ir/SkSLVarDeclarations.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070024#include "SkMutex.h"
25
26#define STRINGIFY(x) #x
27
28// include the built-in shader symbols as static strings
29
ethannicholas5961bc92016-10-12 06:39:56 -070030static const char* SKSL_INCLUDE =
ethannicholasb3058bd2016-07-01 08:22:01 -070031#include "sksl.include"
32;
33
ethannicholas5961bc92016-10-12 06:39:56 -070034static const char* SKSL_VERT_INCLUDE =
ethannicholasb3058bd2016-07-01 08:22:01 -070035#include "sksl_vert.include"
36;
37
ethannicholas5961bc92016-10-12 06:39:56 -070038static const char* SKSL_FRAG_INCLUDE =
ethannicholasb3058bd2016-07-01 08:22:01 -070039#include "sksl_frag.include"
40;
41
42namespace SkSL {
43
44Compiler::Compiler()
45: fErrorCount(0) {
46 auto types = std::shared_ptr<SymbolTable>(new SymbolTable(*this));
47 auto symbols = std::shared_ptr<SymbolTable>(new SymbolTable(types, *this));
ethannicholasd598f792016-07-25 10:08:54 -070048 fIRGenerator = new IRGenerator(&fContext, symbols, *this);
ethannicholasb3058bd2016-07-01 08:22:01 -070049 fTypes = types;
ethannicholasd598f792016-07-25 10:08:54 -070050 #define ADD_TYPE(t) types->addWithoutOwnership(fContext.f ## t ## _Type->fName, \
51 fContext.f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -070052 ADD_TYPE(Void);
53 ADD_TYPE(Float);
54 ADD_TYPE(Vec2);
55 ADD_TYPE(Vec3);
56 ADD_TYPE(Vec4);
57 ADD_TYPE(Double);
58 ADD_TYPE(DVec2);
59 ADD_TYPE(DVec3);
60 ADD_TYPE(DVec4);
61 ADD_TYPE(Int);
62 ADD_TYPE(IVec2);
63 ADD_TYPE(IVec3);
64 ADD_TYPE(IVec4);
65 ADD_TYPE(UInt);
66 ADD_TYPE(UVec2);
67 ADD_TYPE(UVec3);
68 ADD_TYPE(UVec4);
69 ADD_TYPE(Bool);
70 ADD_TYPE(BVec2);
71 ADD_TYPE(BVec3);
72 ADD_TYPE(BVec4);
73 ADD_TYPE(Mat2x2);
ethannicholasf789b382016-08-03 12:43:36 -070074 types->addWithoutOwnership("mat2x2", fContext.fMat2x2_Type.get());
ethannicholasb3058bd2016-07-01 08:22:01 -070075 ADD_TYPE(Mat2x3);
76 ADD_TYPE(Mat2x4);
77 ADD_TYPE(Mat3x2);
78 ADD_TYPE(Mat3x3);
ethannicholasf789b382016-08-03 12:43:36 -070079 types->addWithoutOwnership("mat3x3", fContext.fMat3x3_Type.get());
ethannicholasb3058bd2016-07-01 08:22:01 -070080 ADD_TYPE(Mat3x4);
81 ADD_TYPE(Mat4x2);
82 ADD_TYPE(Mat4x3);
83 ADD_TYPE(Mat4x4);
ethannicholasf789b382016-08-03 12:43:36 -070084 types->addWithoutOwnership("mat4x4", fContext.fMat4x4_Type.get());
ethannicholasb3058bd2016-07-01 08:22:01 -070085 ADD_TYPE(GenType);
86 ADD_TYPE(GenDType);
87 ADD_TYPE(GenIType);
88 ADD_TYPE(GenUType);
89 ADD_TYPE(GenBType);
90 ADD_TYPE(Mat);
91 ADD_TYPE(Vec);
92 ADD_TYPE(GVec);
93 ADD_TYPE(GVec2);
94 ADD_TYPE(GVec3);
95 ADD_TYPE(GVec4);
96 ADD_TYPE(DVec);
97 ADD_TYPE(IVec);
98 ADD_TYPE(UVec);
99 ADD_TYPE(BVec);
100
101 ADD_TYPE(Sampler1D);
102 ADD_TYPE(Sampler2D);
103 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700104 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700105 ADD_TYPE(SamplerCube);
106 ADD_TYPE(Sampler2DRect);
107 ADD_TYPE(Sampler1DArray);
108 ADD_TYPE(Sampler2DArray);
109 ADD_TYPE(SamplerCubeArray);
110 ADD_TYPE(SamplerBuffer);
111 ADD_TYPE(Sampler2DMS);
112 ADD_TYPE(Sampler2DMSArray);
113
114 ADD_TYPE(GSampler1D);
115 ADD_TYPE(GSampler2D);
116 ADD_TYPE(GSampler3D);
117 ADD_TYPE(GSamplerCube);
118 ADD_TYPE(GSampler2DRect);
119 ADD_TYPE(GSampler1DArray);
120 ADD_TYPE(GSampler2DArray);
121 ADD_TYPE(GSamplerCubeArray);
122 ADD_TYPE(GSamplerBuffer);
123 ADD_TYPE(GSampler2DMS);
124 ADD_TYPE(GSampler2DMSArray);
125
126 ADD_TYPE(Sampler1DShadow);
127 ADD_TYPE(Sampler2DShadow);
128 ADD_TYPE(SamplerCubeShadow);
129 ADD_TYPE(Sampler2DRectShadow);
130 ADD_TYPE(Sampler1DArrayShadow);
131 ADD_TYPE(Sampler2DArrayShadow);
132 ADD_TYPE(SamplerCubeArrayShadow);
133 ADD_TYPE(GSampler2DArrayShadow);
134 ADD_TYPE(GSamplerCubeArrayShadow);
135
ethannicholas5961bc92016-10-12 06:39:56 -0700136 Modifiers::Flag ignored1;
137 std::vector<std::unique_ptr<ProgramElement>> ignored2;
138 this->internalConvertProgram(SKSL_INCLUDE, &ignored1, &ignored2);
ethannicholasddb37d62016-10-20 09:54:00 -0700139 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
ethannicholasb3058bd2016-07-01 08:22:01 -0700140 ASSERT(!fErrorCount);
141}
142
143Compiler::~Compiler() {
144 delete fIRGenerator;
145}
146
ethannicholas22f939e2016-10-13 13:25:34 -0700147// add the definition created by assigning to the lvalue to the definition set
148void Compiler::addDefinition(const Expression* lvalue, const Expression* expr,
149 std::unordered_map<const Variable*, const Expression*>* definitions) {
150 switch (lvalue->fKind) {
151 case Expression::kVariableReference_Kind: {
152 const Variable& var = ((VariableReference*) lvalue)->fVariable;
153 if (var.fStorage == Variable::kLocal_Storage) {
154 (*definitions)[&var] = expr;
155 }
156 break;
157 }
158 case Expression::kSwizzle_Kind:
159 // We consider the variable written to as long as at least some of its components have
160 // been written to. This will lead to some false negatives (we won't catch it if you
161 // write to foo.x and then read foo.y), but being stricter could lead to false positives
162 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
163 // but since we pass foo as a whole it is flagged as an error) unless we perform a much
164 // more complicated whole-program analysis. This is probably good enough.
165 this->addDefinition(((Swizzle*) lvalue)->fBase.get(),
166 fContext.fDefined_Expression.get(),
167 definitions);
168 break;
169 case Expression::kIndex_Kind:
170 // see comments in Swizzle
171 this->addDefinition(((IndexExpression*) lvalue)->fBase.get(),
172 fContext.fDefined_Expression.get(),
173 definitions);
174 break;
175 case Expression::kFieldAccess_Kind:
176 // see comments in Swizzle
177 this->addDefinition(((FieldAccess*) lvalue)->fBase.get(),
178 fContext.fDefined_Expression.get(),
179 definitions);
180 break;
181 default:
182 // not an lvalue, can't happen
183 ASSERT(false);
184 }
185}
186
187// add local variables defined by this node to the set
188void Compiler::addDefinitions(const BasicBlock::Node& node,
189 std::unordered_map<const Variable*, const Expression*>* definitions) {
190 switch (node.fKind) {
191 case BasicBlock::Node::kExpression_Kind: {
192 const Expression* expr = (Expression*) node.fNode;
193 if (expr->fKind == Expression::kBinary_Kind) {
194 const BinaryExpression* b = (BinaryExpression*) expr;
195 if (b->fOperator == Token::EQ) {
196 this->addDefinition(b->fLeft.get(), b->fRight.get(), definitions);
197 }
198 }
199 break;
200 }
201 case BasicBlock::Node::kStatement_Kind: {
202 const Statement* stmt = (Statement*) node.fNode;
203 if (stmt->fKind == Statement::kVarDeclarations_Kind) {
204 const VarDeclarationsStatement* vd = (VarDeclarationsStatement*) stmt;
205 for (const VarDeclaration& decl : vd->fDeclaration->fVars) {
206 if (decl.fValue) {
207 (*definitions)[decl.fVar] = decl.fValue.get();
208 }
209 }
210 }
211 break;
212 }
213 }
214}
215
216void Compiler::scanCFG(CFG* cfg, BlockId blockId, std::set<BlockId>* workList) {
217 BasicBlock& block = cfg->fBlocks[blockId];
218
219 // compute definitions after this block
220 std::unordered_map<const Variable*, const Expression*> after = block.fBefore;
221 for (const BasicBlock::Node& n : block.fNodes) {
222 this->addDefinitions(n, &after);
223 }
224
225 // propagate definitions to exits
226 for (BlockId exitId : block.fExits) {
227 BasicBlock& exit = cfg->fBlocks[exitId];
228 for (const auto& pair : after) {
229 const Expression* e1 = pair.second;
230 if (exit.fBefore.find(pair.first) == exit.fBefore.end()) {
231 exit.fBefore[pair.first] = e1;
232 } else {
233 const Expression* e2 = exit.fBefore[pair.first];
234 if (e1 != e2) {
235 // definition has changed, merge and add exit block to worklist
236 workList->insert(exitId);
237 if (!e1 || !e2) {
238 exit.fBefore[pair.first] = nullptr;
239 } else {
240 exit.fBefore[pair.first] = fContext.fDefined_Expression.get();
241 }
242 }
243 }
244 }
245 }
246}
247
248// returns a map which maps all local variables in the function to null, indicating that their value
249// is initially unknown
250static std::unordered_map<const Variable*, const Expression*> compute_start_state(const CFG& cfg) {
251 std::unordered_map<const Variable*, const Expression*> result;
252 for (const auto block : cfg.fBlocks) {
253 for (const auto node : block.fNodes) {
254 if (node.fKind == BasicBlock::Node::kStatement_Kind) {
255 const Statement* s = (Statement*) node.fNode;
256 if (s->fKind == Statement::kVarDeclarations_Kind) {
257 const VarDeclarationsStatement* vd = (const VarDeclarationsStatement*) s;
258 for (const VarDeclaration& decl : vd->fDeclaration->fVars) {
259 result[decl.fVar] = nullptr;
260 }
261 }
262 }
263 }
264 }
265 return result;
266}
267
268void Compiler::scanCFG(const FunctionDefinition& f) {
269 CFG cfg = CFGGenerator().getCFG(f);
270
271 // compute the data flow
272 cfg.fBlocks[cfg.fStart].fBefore = compute_start_state(cfg);
273 std::set<BlockId> workList;
274 for (BlockId i = 0; i < cfg.fBlocks.size(); i++) {
275 workList.insert(i);
276 }
277 while (workList.size()) {
278 BlockId next = *workList.begin();
279 workList.erase(workList.begin());
280 this->scanCFG(&cfg, next, &workList);
281 }
282
283 // check for unreachable code
284 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
285 if (i != cfg.fStart && !cfg.fBlocks[i].fEntrances.size() &&
286 cfg.fBlocks[i].fNodes.size()) {
287 this->error(cfg.fBlocks[i].fNodes[0].fNode->fPosition, "unreachable");
288 }
289 }
290 if (fErrorCount) {
291 return;
292 }
293
294 // check for undefined variables
295 for (const BasicBlock& b : cfg.fBlocks) {
296 std::unordered_map<const Variable*, const Expression*> definitions = b.fBefore;
297 for (const BasicBlock::Node& n : b.fNodes) {
298 if (n.fKind == BasicBlock::Node::kExpression_Kind) {
299 const Expression* expr = (const Expression*) n.fNode;
300 if (expr->fKind == Expression::kVariableReference_Kind) {
301 const Variable& var = ((VariableReference*) expr)->fVariable;
302 if (var.fStorage == Variable::kLocal_Storage &&
303 !definitions[&var]) {
304 this->error(expr->fPosition,
305 "'" + var.fName + "' has not been assigned");
306 }
307 }
308 }
309 this->addDefinitions(n, &definitions);
310 }
311 }
312
313 // check for missing return
314 if (f.fDeclaration.fReturnType != *fContext.fVoid_Type) {
315 if (cfg.fBlocks[cfg.fExit].fEntrances.size()) {
316 this->error(f.fPosition, "function can exit without returning a value");
317 }
318 }
319}
320
ethannicholasb3058bd2016-07-01 08:22:01 -0700321void Compiler::internalConvertProgram(std::string text,
ethannicholas5961bc92016-10-12 06:39:56 -0700322 Modifiers::Flag* defaultPrecision,
ethannicholasb3058bd2016-07-01 08:22:01 -0700323 std::vector<std::unique_ptr<ProgramElement>>* result) {
324 Parser parser(text, *fTypes, *this);
325 std::vector<std::unique_ptr<ASTDeclaration>> parsed = parser.file();
326 if (fErrorCount) {
327 return;
328 }
ethannicholas5961bc92016-10-12 06:39:56 -0700329 *defaultPrecision = Modifiers::kHighp_Flag;
ethannicholasb3058bd2016-07-01 08:22:01 -0700330 for (size_t i = 0; i < parsed.size(); i++) {
331 ASTDeclaration& decl = *parsed[i];
332 switch (decl.fKind) {
333 case ASTDeclaration::kVar_Kind: {
ethannicholas14fe8cc2016-09-07 13:37:16 -0700334 std::unique_ptr<VarDeclarations> s = fIRGenerator->convertVarDeclarations(
335 (ASTVarDeclarations&) decl,
ethannicholasb3058bd2016-07-01 08:22:01 -0700336 Variable::kGlobal_Storage);
337 if (s) {
338 result->push_back(std::move(s));
339 }
340 break;
341 }
342 case ASTDeclaration::kFunction_Kind: {
343 std::unique_ptr<FunctionDefinition> f = fIRGenerator->convertFunction(
344 (ASTFunction&) decl);
ethannicholas22f939e2016-10-13 13:25:34 -0700345 if (!fErrorCount && f) {
346 this->scanCFG(*f);
ethannicholasb3058bd2016-07-01 08:22:01 -0700347 result->push_back(std::move(f));
348 }
349 break;
350 }
ethannicholas5961bc92016-10-12 06:39:56 -0700351 case ASTDeclaration::kModifiers_Kind: {
352 std::unique_ptr<ModifiersDeclaration> f = fIRGenerator->convertModifiersDeclaration(
353 (ASTModifiersDeclaration&) decl);
354 if (f) {
355 result->push_back(std::move(f));
356 }
357 break;
358 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700359 case ASTDeclaration::kInterfaceBlock_Kind: {
360 std::unique_ptr<InterfaceBlock> i = fIRGenerator->convertInterfaceBlock(
361 (ASTInterfaceBlock&) decl);
362 if (i) {
363 result->push_back(std::move(i));
364 }
365 break;
366 }
367 case ASTDeclaration::kExtension_Kind: {
368 std::unique_ptr<Extension> e = fIRGenerator->convertExtension((ASTExtension&) decl);
369 if (e) {
370 result->push_back(std::move(e));
371 }
372 break;
373 }
ethannicholas5961bc92016-10-12 06:39:56 -0700374 case ASTDeclaration::kPrecision_Kind: {
375 *defaultPrecision = ((ASTPrecision&) decl).fPrecision;
376 break;
377 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700378 default:
379 ABORT("unsupported declaration: %s\n", decl.description().c_str());
380 }
381 }
382}
383
384std::unique_ptr<Program> Compiler::convertProgram(Program::Kind kind, std::string text) {
385 fErrorText = "";
386 fErrorCount = 0;
387 fIRGenerator->pushSymbolTable();
ethannicholasd598f792016-07-25 10:08:54 -0700388 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholas5961bc92016-10-12 06:39:56 -0700389 Modifiers::Flag ignored;
ethannicholasb3058bd2016-07-01 08:22:01 -0700390 switch (kind) {
391 case Program::kVertex_Kind:
ethannicholas5961bc92016-10-12 06:39:56 -0700392 this->internalConvertProgram(SKSL_VERT_INCLUDE, &ignored, &elements);
ethannicholasb3058bd2016-07-01 08:22:01 -0700393 break;
394 case Program::kFragment_Kind:
ethannicholas5961bc92016-10-12 06:39:56 -0700395 this->internalConvertProgram(SKSL_FRAG_INCLUDE, &ignored, &elements);
ethannicholasb3058bd2016-07-01 08:22:01 -0700396 break;
397 }
ethannicholasddb37d62016-10-20 09:54:00 -0700398 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
ethannicholas5961bc92016-10-12 06:39:56 -0700399 Modifiers::Flag defaultPrecision;
400 this->internalConvertProgram(text, &defaultPrecision, &elements);
401 auto result = std::unique_ptr<Program>(new Program(kind, defaultPrecision, std::move(elements),
ethannicholasddb37d62016-10-20 09:54:00 -0700402 fIRGenerator->fSymbolTable));
ethannicholasb3058bd2016-07-01 08:22:01 -0700403 fIRGenerator->popSymbolTable();
404 this->writeErrorCount();
ethannicholasd598f792016-07-25 10:08:54 -0700405 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -0700406}
407
408void Compiler::error(Position position, std::string msg) {
409 fErrorCount++;
410 fErrorText += "error: " + position.description() + ": " + msg.c_str() + "\n";
411}
412
413std::string Compiler::errorText() {
414 std::string result = fErrorText;
415 return result;
416}
417
418void Compiler::writeErrorCount() {
419 if (fErrorCount) {
420 fErrorText += to_string(fErrorCount) + " error";
421 if (fErrorCount > 1) {
422 fErrorText += "s";
423 }
424 fErrorText += "\n";
425 }
426}
427
ethannicholasf789b382016-08-03 12:43:36 -0700428bool Compiler::toSPIRV(Program::Kind kind, const std::string& text, std::ostream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700429 auto program = this->convertProgram(kind, text);
430 if (fErrorCount == 0) {
ethannicholasd598f792016-07-25 10:08:54 -0700431 SkSL::SPIRVCodeGenerator cg(&fContext);
ethannicholasb3058bd2016-07-01 08:22:01 -0700432 cg.generateCode(*program.get(), out);
433 ASSERT(!out.rdstate());
434 }
435 return fErrorCount == 0;
436}
437
ethannicholasf789b382016-08-03 12:43:36 -0700438bool Compiler::toSPIRV(Program::Kind kind, const std::string& text, std::string* out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700439 std::stringstream buffer;
440 bool result = this->toSPIRV(kind, text, buffer);
441 if (result) {
442 *out = buffer.str();
443 }
ethannicholasf789b382016-08-03 12:43:36 -0700444 return result;
445}
446
447bool Compiler::toGLSL(Program::Kind kind, const std::string& text, GLCaps caps,
448 std::ostream& out) {
449 auto program = this->convertProgram(kind, text);
450 if (fErrorCount == 0) {
451 SkSL::GLSLCodeGenerator cg(&fContext, caps);
452 cg.generateCode(*program.get(), out);
453 ASSERT(!out.rdstate());
454 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700455 return fErrorCount == 0;
456}
457
ethannicholasf789b382016-08-03 12:43:36 -0700458bool Compiler::toGLSL(Program::Kind kind, const std::string& text, GLCaps caps,
459 std::string* out) {
460 std::stringstream buffer;
461 bool result = this->toGLSL(kind, text, caps, buffer);
462 if (result) {
463 *out = buffer.str();
464 }
465 return result;
466}
467
ethannicholasb3058bd2016-07-01 08:22:01 -0700468} // namespace