SkSLIRGenerator.cpp 113 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564
  1. /*
  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. #include "src/sksl/SkSLIRGenerator.h"
  8. #include "limits.h"
  9. #include <unordered_set>
  10. #include "src/sksl/SkSLCompiler.h"
  11. #include "src/sksl/SkSLParser.h"
  12. #include "src/sksl/ir/SkSLAppendStage.h"
  13. #include "src/sksl/ir/SkSLBinaryExpression.h"
  14. #include "src/sksl/ir/SkSLBoolLiteral.h"
  15. #include "src/sksl/ir/SkSLBreakStatement.h"
  16. #include "src/sksl/ir/SkSLConstructor.h"
  17. #include "src/sksl/ir/SkSLContinueStatement.h"
  18. #include "src/sksl/ir/SkSLDiscardStatement.h"
  19. #include "src/sksl/ir/SkSLDoStatement.h"
  20. #include "src/sksl/ir/SkSLEnum.h"
  21. #include "src/sksl/ir/SkSLExpressionStatement.h"
  22. #include "src/sksl/ir/SkSLExternalFunctionCall.h"
  23. #include "src/sksl/ir/SkSLExternalValueReference.h"
  24. #include "src/sksl/ir/SkSLField.h"
  25. #include "src/sksl/ir/SkSLFieldAccess.h"
  26. #include "src/sksl/ir/SkSLFloatLiteral.h"
  27. #include "src/sksl/ir/SkSLForStatement.h"
  28. #include "src/sksl/ir/SkSLFunctionCall.h"
  29. #include "src/sksl/ir/SkSLFunctionDeclaration.h"
  30. #include "src/sksl/ir/SkSLFunctionDefinition.h"
  31. #include "src/sksl/ir/SkSLFunctionReference.h"
  32. #include "src/sksl/ir/SkSLIfStatement.h"
  33. #include "src/sksl/ir/SkSLIndexExpression.h"
  34. #include "src/sksl/ir/SkSLIntLiteral.h"
  35. #include "src/sksl/ir/SkSLInterfaceBlock.h"
  36. #include "src/sksl/ir/SkSLLayout.h"
  37. #include "src/sksl/ir/SkSLNullLiteral.h"
  38. #include "src/sksl/ir/SkSLPostfixExpression.h"
  39. #include "src/sksl/ir/SkSLPrefixExpression.h"
  40. #include "src/sksl/ir/SkSLReturnStatement.h"
  41. #include "src/sksl/ir/SkSLSetting.h"
  42. #include "src/sksl/ir/SkSLSwitchCase.h"
  43. #include "src/sksl/ir/SkSLSwitchStatement.h"
  44. #include "src/sksl/ir/SkSLSwizzle.h"
  45. #include "src/sksl/ir/SkSLTernaryExpression.h"
  46. #include "src/sksl/ir/SkSLUnresolvedFunction.h"
  47. #include "src/sksl/ir/SkSLVarDeclarations.h"
  48. #include "src/sksl/ir/SkSLVarDeclarationsStatement.h"
  49. #include "src/sksl/ir/SkSLVariable.h"
  50. #include "src/sksl/ir/SkSLVariableReference.h"
  51. #include "src/sksl/ir/SkSLWhileStatement.h"
  52. namespace SkSL {
  53. class AutoSymbolTable {
  54. public:
  55. AutoSymbolTable(IRGenerator* ir)
  56. : fIR(ir)
  57. , fPrevious(fIR->fSymbolTable) {
  58. fIR->pushSymbolTable();
  59. }
  60. ~AutoSymbolTable() {
  61. fIR->popSymbolTable();
  62. SkASSERT(fPrevious == fIR->fSymbolTable);
  63. }
  64. IRGenerator* fIR;
  65. std::shared_ptr<SymbolTable> fPrevious;
  66. };
  67. class AutoLoopLevel {
  68. public:
  69. AutoLoopLevel(IRGenerator* ir)
  70. : fIR(ir) {
  71. fIR->fLoopLevel++;
  72. }
  73. ~AutoLoopLevel() {
  74. fIR->fLoopLevel--;
  75. }
  76. IRGenerator* fIR;
  77. };
  78. class AutoSwitchLevel {
  79. public:
  80. AutoSwitchLevel(IRGenerator* ir)
  81. : fIR(ir) {
  82. fIR->fSwitchLevel++;
  83. }
  84. ~AutoSwitchLevel() {
  85. fIR->fSwitchLevel--;
  86. }
  87. IRGenerator* fIR;
  88. };
  89. IRGenerator::IRGenerator(const Context* context, std::shared_ptr<SymbolTable> symbolTable,
  90. ErrorReporter& errorReporter)
  91. : fContext(*context)
  92. , fCurrentFunction(nullptr)
  93. , fRootSymbolTable(symbolTable)
  94. , fSymbolTable(symbolTable)
  95. , fLoopLevel(0)
  96. , fSwitchLevel(0)
  97. , fTmpCount(0)
  98. , fErrors(errorReporter) {}
  99. void IRGenerator::pushSymbolTable() {
  100. fSymbolTable.reset(new SymbolTable(std::move(fSymbolTable), &fErrors));
  101. }
  102. void IRGenerator::popSymbolTable() {
  103. fSymbolTable = fSymbolTable->fParent;
  104. }
  105. static void fill_caps(const SKSL_CAPS_CLASS& caps,
  106. std::unordered_map<String, Program::Settings::Value>* capsMap) {
  107. #define CAP(name) \
  108. capsMap->insert(std::make_pair(String(#name), Program::Settings::Value(caps.name())))
  109. CAP(fbFetchSupport);
  110. CAP(fbFetchNeedsCustomOutput);
  111. CAP(flatInterpolationSupport);
  112. CAP(noperspectiveInterpolationSupport);
  113. CAP(sampleVariablesSupport);
  114. CAP(externalTextureSupport);
  115. CAP(mustEnableAdvBlendEqs);
  116. CAP(mustEnableSpecificAdvBlendEqs);
  117. CAP(mustDeclareFragmentShaderOutput);
  118. CAP(mustDoOpBetweenFloorAndAbs);
  119. CAP(atan2ImplementedAsAtanYOverX);
  120. CAP(canUseAnyFunctionInShader);
  121. CAP(floatIs32Bits);
  122. CAP(integerSupport);
  123. #undef CAP
  124. }
  125. void IRGenerator::start(const Program::Settings* settings,
  126. std::vector<std::unique_ptr<ProgramElement>>* inherited) {
  127. if (fStarted) {
  128. this->popSymbolTable();
  129. }
  130. fSettings = settings;
  131. fCapsMap.clear();
  132. if (settings->fCaps) {
  133. fill_caps(*settings->fCaps, &fCapsMap);
  134. } else {
  135. fCapsMap.insert(std::make_pair(String("integerSupport"),
  136. Program::Settings::Value(true)));
  137. }
  138. this->pushSymbolTable();
  139. fInvocations = -1;
  140. fInputs.reset();
  141. fSkPerVertex = nullptr;
  142. fRTAdjust = nullptr;
  143. fRTAdjustInterfaceBlock = nullptr;
  144. if (inherited) {
  145. for (const auto& e : *inherited) {
  146. if (e->fKind == ProgramElement::kInterfaceBlock_Kind) {
  147. InterfaceBlock& intf = (InterfaceBlock&) *e;
  148. if (intf.fVariable.fName == Compiler::PERVERTEX_NAME) {
  149. SkASSERT(!fSkPerVertex);
  150. fSkPerVertex = &intf.fVariable;
  151. }
  152. }
  153. }
  154. }
  155. }
  156. std::unique_ptr<Extension> IRGenerator::convertExtension(int offset, StringFragment name) {
  157. return std::unique_ptr<Extension>(new Extension(offset, name));
  158. }
  159. void IRGenerator::finish() {
  160. this->popSymbolTable();
  161. fSettings = nullptr;
  162. }
  163. std::unique_ptr<Statement> IRGenerator::convertStatement(const ASTNode& statement) {
  164. switch (statement.fKind) {
  165. case ASTNode::Kind::kBlock:
  166. return this->convertBlock(statement);
  167. case ASTNode::Kind::kVarDeclarations:
  168. return this->convertVarDeclarationStatement(statement);
  169. case ASTNode::Kind::kIf:
  170. return this->convertIf(statement);
  171. case ASTNode::Kind::kFor:
  172. return this->convertFor(statement);
  173. case ASTNode::Kind::kWhile:
  174. return this->convertWhile(statement);
  175. case ASTNode::Kind::kDo:
  176. return this->convertDo(statement);
  177. case ASTNode::Kind::kSwitch:
  178. return this->convertSwitch(statement);
  179. case ASTNode::Kind::kReturn:
  180. return this->convertReturn(statement);
  181. case ASTNode::Kind::kBreak:
  182. return this->convertBreak(statement);
  183. case ASTNode::Kind::kContinue:
  184. return this->convertContinue(statement);
  185. case ASTNode::Kind::kDiscard:
  186. return this->convertDiscard(statement);
  187. default:
  188. // it's an expression
  189. std::unique_ptr<Statement> result = this->convertExpressionStatement(statement);
  190. if (fRTAdjust && Program::kGeometry_Kind == fKind) {
  191. SkASSERT(result->fKind == Statement::kExpression_Kind);
  192. Expression& expr = *((ExpressionStatement&) *result).fExpression;
  193. if (expr.fKind == Expression::kFunctionCall_Kind) {
  194. FunctionCall& fc = (FunctionCall&) expr;
  195. if (fc.fFunction.fBuiltin && fc.fFunction.fName == "EmitVertex") {
  196. std::vector<std::unique_ptr<Statement>> statements;
  197. statements.push_back(getNormalizeSkPositionCode());
  198. statements.push_back(std::move(result));
  199. return std::unique_ptr<Block>(new Block(statement.fOffset,
  200. std::move(statements),
  201. fSymbolTable));
  202. }
  203. }
  204. }
  205. return result;
  206. }
  207. }
  208. std::unique_ptr<Block> IRGenerator::convertBlock(const ASTNode& block) {
  209. SkASSERT(block.fKind == ASTNode::Kind::kBlock);
  210. AutoSymbolTable table(this);
  211. std::vector<std::unique_ptr<Statement>> statements;
  212. for (const auto& child : block) {
  213. std::unique_ptr<Statement> statement = this->convertStatement(child);
  214. if (!statement) {
  215. return nullptr;
  216. }
  217. statements.push_back(std::move(statement));
  218. }
  219. return std::unique_ptr<Block>(new Block(block.fOffset, std::move(statements), fSymbolTable));
  220. }
  221. std::unique_ptr<Statement> IRGenerator::convertVarDeclarationStatement(const ASTNode& s) {
  222. SkASSERT(s.fKind == ASTNode::Kind::kVarDeclarations);
  223. auto decl = this->convertVarDeclarations(s, Variable::kLocal_Storage);
  224. if (!decl) {
  225. return nullptr;
  226. }
  227. return std::unique_ptr<Statement>(new VarDeclarationsStatement(std::move(decl)));
  228. }
  229. std::unique_ptr<VarDeclarations> IRGenerator::convertVarDeclarations(const ASTNode& decls,
  230. Variable::Storage storage) {
  231. SkASSERT(decls.fKind == ASTNode::Kind::kVarDeclarations);
  232. auto iter = decls.begin();
  233. const Modifiers& modifiers = iter++->getModifiers();
  234. const ASTNode& rawType = *(iter++);
  235. std::vector<std::unique_ptr<VarDeclaration>> variables;
  236. const Type* baseType = this->convertType(rawType);
  237. if (!baseType) {
  238. return nullptr;
  239. }
  240. if (fKind != Program::kFragmentProcessor_Kind &&
  241. (modifiers.fFlags & Modifiers::kIn_Flag) &&
  242. baseType->kind() == Type::Kind::kMatrix_Kind) {
  243. fErrors.error(decls.fOffset, "'in' variables may not have matrix type");
  244. }
  245. if (modifiers.fLayout.fWhen.fLength && fKind != Program::kFragmentProcessor_Kind &&
  246. fKind != Program::kPipelineStage_Kind) {
  247. fErrors.error(decls.fOffset, "'when' is only permitted within fragment processors");
  248. }
  249. if (modifiers.fLayout.fKey) {
  250. if (fKind != Program::kFragmentProcessor_Kind && fKind != Program::kPipelineStage_Kind) {
  251. fErrors.error(decls.fOffset, "'key' is only permitted within fragment processors");
  252. }
  253. if ((modifiers.fFlags & Modifiers::kUniform_Flag) != 0) {
  254. fErrors.error(decls.fOffset, "'key' is not permitted on 'uniform' variables");
  255. }
  256. }
  257. for (; iter != decls.end(); ++iter) {
  258. const ASTNode& varDecl = *iter;
  259. if (modifiers.fLayout.fLocation == 0 && modifiers.fLayout.fIndex == 0 &&
  260. (modifiers.fFlags & Modifiers::kOut_Flag) && fKind == Program::kFragment_Kind &&
  261. varDecl.getVarData().fName != "sk_FragColor") {
  262. fErrors.error(varDecl.fOffset,
  263. "out location=0, index=0 is reserved for sk_FragColor");
  264. }
  265. const ASTNode::VarData& varData = varDecl.getVarData();
  266. const Type* type = baseType;
  267. std::vector<std::unique_ptr<Expression>> sizes;
  268. auto iter = varDecl.begin();
  269. for (size_t i = 0; i < varData.fSizeCount; ++i, ++iter) {
  270. const ASTNode& rawSize = *iter;
  271. if (rawSize) {
  272. auto size = this->coerce(this->convertExpression(rawSize), *fContext.fInt_Type);
  273. if (!size) {
  274. return nullptr;
  275. }
  276. String name(type->fName);
  277. int64_t count;
  278. if (size->fKind == Expression::kIntLiteral_Kind) {
  279. count = ((IntLiteral&) *size).fValue;
  280. if (count <= 0) {
  281. fErrors.error(size->fOffset, "array size must be positive");
  282. }
  283. name += "[" + to_string(count) + "]";
  284. } else {
  285. count = -1;
  286. name += "[]";
  287. }
  288. type = (Type*) fSymbolTable->takeOwnership(
  289. std::unique_ptr<Symbol>(new Type(name,
  290. Type::kArray_Kind,
  291. *type,
  292. (int) count)));
  293. sizes.push_back(std::move(size));
  294. } else {
  295. type = (Type*) fSymbolTable->takeOwnership(
  296. std::unique_ptr<Symbol>(new Type(type->name() + "[]",
  297. Type::kArray_Kind,
  298. *type,
  299. -1)));
  300. sizes.push_back(nullptr);
  301. }
  302. }
  303. auto var = std::unique_ptr<Variable>(new Variable(varDecl.fOffset, modifiers,
  304. varData.fName, *type, storage));
  305. if (var->fName == Compiler::RTADJUST_NAME) {
  306. SkASSERT(!fRTAdjust);
  307. SkASSERT(var->fType == *fContext.fFloat4_Type);
  308. fRTAdjust = var.get();
  309. }
  310. std::unique_ptr<Expression> value;
  311. if (iter != varDecl.end()) {
  312. value = this->convertExpression(*iter);
  313. if (!value) {
  314. return nullptr;
  315. }
  316. value = this->coerce(std::move(value), *type);
  317. if (!value) {
  318. return nullptr;
  319. }
  320. var->fWriteCount = 1;
  321. var->fInitialValue = value.get();
  322. }
  323. if (storage == Variable::kGlobal_Storage && var->fName == "sk_FragColor" &&
  324. (*fSymbolTable)[var->fName]) {
  325. // already defined, ignore
  326. } else if (storage == Variable::kGlobal_Storage && (*fSymbolTable)[var->fName] &&
  327. (*fSymbolTable)[var->fName]->fKind == Symbol::kVariable_Kind &&
  328. ((Variable*) (*fSymbolTable)[var->fName])->fModifiers.fLayout.fBuiltin >= 0) {
  329. // already defined, just update the modifiers
  330. Variable* old = (Variable*) (*fSymbolTable)[var->fName];
  331. old->fModifiers = var->fModifiers;
  332. } else {
  333. variables.emplace_back(new VarDeclaration(var.get(), std::move(sizes),
  334. std::move(value)));
  335. StringFragment name = var->fName;
  336. fSymbolTable->add(name, std::move(var));
  337. }
  338. }
  339. return std::unique_ptr<VarDeclarations>(new VarDeclarations(decls.fOffset,
  340. baseType,
  341. std::move(variables)));
  342. }
  343. std::unique_ptr<ModifiersDeclaration> IRGenerator::convertModifiersDeclaration(const ASTNode& m) {
  344. SkASSERT(m.fKind == ASTNode::Kind::kModifiers);
  345. Modifiers modifiers = m.getModifiers();
  346. if (modifiers.fLayout.fInvocations != -1) {
  347. if (fKind != Program::kGeometry_Kind) {
  348. fErrors.error(m.fOffset, "'invocations' is only legal in geometry shaders");
  349. return nullptr;
  350. }
  351. fInvocations = modifiers.fLayout.fInvocations;
  352. if (fSettings->fCaps && !fSettings->fCaps->gsInvocationsSupport()) {
  353. modifiers.fLayout.fInvocations = -1;
  354. Variable* invocationId = (Variable*) (*fSymbolTable)["sk_InvocationID"];
  355. SkASSERT(invocationId);
  356. invocationId->fModifiers.fFlags = 0;
  357. invocationId->fModifiers.fLayout.fBuiltin = -1;
  358. if (modifiers.fLayout.description() == "") {
  359. return nullptr;
  360. }
  361. }
  362. }
  363. if (modifiers.fLayout.fMaxVertices != -1 && fInvocations > 0 && fSettings->fCaps &&
  364. !fSettings->fCaps->gsInvocationsSupport()) {
  365. modifiers.fLayout.fMaxVertices *= fInvocations;
  366. }
  367. return std::unique_ptr<ModifiersDeclaration>(new ModifiersDeclaration(modifiers));
  368. }
  369. std::unique_ptr<Statement> IRGenerator::convertIf(const ASTNode& n) {
  370. SkASSERT(n.fKind == ASTNode::Kind::kIf);
  371. auto iter = n.begin();
  372. std::unique_ptr<Expression> test = this->coerce(this->convertExpression(*(iter++)),
  373. *fContext.fBool_Type);
  374. if (!test) {
  375. return nullptr;
  376. }
  377. std::unique_ptr<Statement> ifTrue = this->convertStatement(*(iter++));
  378. if (!ifTrue) {
  379. return nullptr;
  380. }
  381. std::unique_ptr<Statement> ifFalse;
  382. if (iter != n.end()) {
  383. ifFalse = this->convertStatement(*(iter++));
  384. if (!ifFalse) {
  385. return nullptr;
  386. }
  387. }
  388. if (test->fKind == Expression::kBoolLiteral_Kind) {
  389. // static boolean value, fold down to a single branch
  390. if (((BoolLiteral&) *test).fValue) {
  391. return ifTrue;
  392. } else if (ifFalse) {
  393. return ifFalse;
  394. } else {
  395. // False & no else clause. Not an error, so don't return null!
  396. std::vector<std::unique_ptr<Statement>> empty;
  397. return std::unique_ptr<Statement>(new Block(n.fOffset, std::move(empty),
  398. fSymbolTable));
  399. }
  400. }
  401. return std::unique_ptr<Statement>(new IfStatement(n.fOffset, n.getBool(), std::move(test),
  402. std::move(ifTrue), std::move(ifFalse)));
  403. }
  404. std::unique_ptr<Statement> IRGenerator::convertFor(const ASTNode& f) {
  405. SkASSERT(f.fKind == ASTNode::Kind::kFor);
  406. AutoLoopLevel level(this);
  407. AutoSymbolTable table(this);
  408. std::unique_ptr<Statement> initializer;
  409. auto iter = f.begin();
  410. if (*iter) {
  411. initializer = this->convertStatement(*iter);
  412. if (!initializer) {
  413. return nullptr;
  414. }
  415. }
  416. ++iter;
  417. std::unique_ptr<Expression> test;
  418. if (*iter) {
  419. test = this->coerce(this->convertExpression(*iter), *fContext.fBool_Type);
  420. if (!test) {
  421. return nullptr;
  422. }
  423. }
  424. ++iter;
  425. std::unique_ptr<Expression> next;
  426. if (*iter) {
  427. next = this->convertExpression(*iter);
  428. if (!next) {
  429. return nullptr;
  430. }
  431. this->checkValid(*next);
  432. }
  433. ++iter;
  434. std::unique_ptr<Statement> statement = this->convertStatement(*iter);
  435. if (!statement) {
  436. return nullptr;
  437. }
  438. return std::unique_ptr<Statement>(new ForStatement(f.fOffset, std::move(initializer),
  439. std::move(test), std::move(next),
  440. std::move(statement), fSymbolTable));
  441. }
  442. std::unique_ptr<Statement> IRGenerator::convertWhile(const ASTNode& w) {
  443. SkASSERT(w.fKind == ASTNode::Kind::kWhile);
  444. AutoLoopLevel level(this);
  445. auto iter = w.begin();
  446. std::unique_ptr<Expression> test = this->coerce(this->convertExpression(*(iter++)),
  447. *fContext.fBool_Type);
  448. if (!test) {
  449. return nullptr;
  450. }
  451. std::unique_ptr<Statement> statement = this->convertStatement(*(iter++));
  452. if (!statement) {
  453. return nullptr;
  454. }
  455. return std::unique_ptr<Statement>(new WhileStatement(w.fOffset, std::move(test),
  456. std::move(statement)));
  457. }
  458. std::unique_ptr<Statement> IRGenerator::convertDo(const ASTNode& d) {
  459. SkASSERT(d.fKind == ASTNode::Kind::kDo);
  460. AutoLoopLevel level(this);
  461. auto iter = d.begin();
  462. std::unique_ptr<Statement> statement = this->convertStatement(*(iter++));
  463. if (!statement) {
  464. return nullptr;
  465. }
  466. std::unique_ptr<Expression> test = this->coerce(this->convertExpression(*(iter++)),
  467. *fContext.fBool_Type);
  468. if (!test) {
  469. return nullptr;
  470. }
  471. return std::unique_ptr<Statement>(new DoStatement(d.fOffset, std::move(statement),
  472. std::move(test)));
  473. }
  474. std::unique_ptr<Statement> IRGenerator::convertSwitch(const ASTNode& s) {
  475. SkASSERT(s.fKind == ASTNode::Kind::kSwitch);
  476. AutoSwitchLevel level(this);
  477. auto iter = s.begin();
  478. std::unique_ptr<Expression> value = this->convertExpression(*(iter++));
  479. if (!value) {
  480. return nullptr;
  481. }
  482. if (value->fType != *fContext.fUInt_Type && value->fType.kind() != Type::kEnum_Kind) {
  483. value = this->coerce(std::move(value), *fContext.fInt_Type);
  484. if (!value) {
  485. return nullptr;
  486. }
  487. }
  488. AutoSymbolTable table(this);
  489. std::unordered_set<int> caseValues;
  490. std::vector<std::unique_ptr<SwitchCase>> cases;
  491. for (; iter != s.end(); ++iter) {
  492. const ASTNode& c = *iter;
  493. SkASSERT(c.fKind == ASTNode::Kind::kSwitchCase);
  494. std::unique_ptr<Expression> caseValue;
  495. auto childIter = c.begin();
  496. if (*childIter) {
  497. caseValue = this->convertExpression(*childIter);
  498. if (!caseValue) {
  499. return nullptr;
  500. }
  501. caseValue = this->coerce(std::move(caseValue), value->fType);
  502. if (!caseValue) {
  503. return nullptr;
  504. }
  505. if (!caseValue->isConstant()) {
  506. fErrors.error(caseValue->fOffset, "case value must be a constant");
  507. return nullptr;
  508. }
  509. int64_t v;
  510. this->getConstantInt(*caseValue, &v);
  511. if (caseValues.find(v) != caseValues.end()) {
  512. fErrors.error(caseValue->fOffset, "duplicate case value");
  513. }
  514. caseValues.insert(v);
  515. }
  516. ++childIter;
  517. std::vector<std::unique_ptr<Statement>> statements;
  518. for (; childIter != c.end(); ++childIter) {
  519. std::unique_ptr<Statement> converted = this->convertStatement(*childIter);
  520. if (!converted) {
  521. return nullptr;
  522. }
  523. statements.push_back(std::move(converted));
  524. }
  525. cases.emplace_back(new SwitchCase(c.fOffset, std::move(caseValue),
  526. std::move(statements)));
  527. }
  528. return std::unique_ptr<Statement>(new SwitchStatement(s.fOffset, s.getBool(),
  529. std::move(value), std::move(cases),
  530. fSymbolTable));
  531. }
  532. std::unique_ptr<Statement> IRGenerator::convertExpressionStatement(const ASTNode& s) {
  533. std::unique_ptr<Expression> e = this->convertExpression(s);
  534. if (!e) {
  535. return nullptr;
  536. }
  537. this->checkValid(*e);
  538. return std::unique_ptr<Statement>(new ExpressionStatement(std::move(e)));
  539. }
  540. std::unique_ptr<Statement> IRGenerator::convertReturn(const ASTNode& r) {
  541. SkASSERT(r.fKind == ASTNode::Kind::kReturn);
  542. SkASSERT(fCurrentFunction);
  543. // early returns from a vertex main function will bypass the sk_Position normalization, so
  544. // SkASSERT that we aren't doing that. It is of course possible to fix this by adding a
  545. // normalization before each return, but it will probably never actually be necessary.
  546. SkASSERT(Program::kVertex_Kind != fKind || !fRTAdjust || "main" != fCurrentFunction->fName);
  547. if (r.begin() != r.end()) {
  548. std::unique_ptr<Expression> result = this->convertExpression(*r.begin());
  549. if (!result) {
  550. return nullptr;
  551. }
  552. if (fCurrentFunction->fReturnType == *fContext.fVoid_Type) {
  553. fErrors.error(result->fOffset, "may not return a value from a void function");
  554. } else {
  555. result = this->coerce(std::move(result), fCurrentFunction->fReturnType);
  556. if (!result) {
  557. return nullptr;
  558. }
  559. }
  560. return std::unique_ptr<Statement>(new ReturnStatement(std::move(result)));
  561. } else {
  562. if (fCurrentFunction->fReturnType != *fContext.fVoid_Type) {
  563. fErrors.error(r.fOffset, "expected function to return '" +
  564. fCurrentFunction->fReturnType.description() + "'");
  565. }
  566. return std::unique_ptr<Statement>(new ReturnStatement(r.fOffset));
  567. }
  568. }
  569. std::unique_ptr<Statement> IRGenerator::convertBreak(const ASTNode& b) {
  570. SkASSERT(b.fKind == ASTNode::Kind::kBreak);
  571. if (fLoopLevel > 0 || fSwitchLevel > 0) {
  572. return std::unique_ptr<Statement>(new BreakStatement(b.fOffset));
  573. } else {
  574. fErrors.error(b.fOffset, "break statement must be inside a loop or switch");
  575. return nullptr;
  576. }
  577. }
  578. std::unique_ptr<Statement> IRGenerator::convertContinue(const ASTNode& c) {
  579. SkASSERT(c.fKind == ASTNode::Kind::kContinue);
  580. if (fLoopLevel > 0) {
  581. return std::unique_ptr<Statement>(new ContinueStatement(c.fOffset));
  582. } else {
  583. fErrors.error(c.fOffset, "continue statement must be inside a loop");
  584. return nullptr;
  585. }
  586. }
  587. std::unique_ptr<Statement> IRGenerator::convertDiscard(const ASTNode& d) {
  588. SkASSERT(d.fKind == ASTNode::Kind::kDiscard);
  589. return std::unique_ptr<Statement>(new DiscardStatement(d.fOffset));
  590. }
  591. std::unique_ptr<Block> IRGenerator::applyInvocationIDWorkaround(std::unique_ptr<Block> main) {
  592. Layout invokeLayout;
  593. Modifiers invokeModifiers(invokeLayout, Modifiers::kHasSideEffects_Flag);
  594. FunctionDeclaration* invokeDecl = new FunctionDeclaration(-1,
  595. invokeModifiers,
  596. "_invoke",
  597. std::vector<const Variable*>(),
  598. *fContext.fVoid_Type);
  599. fProgramElements->push_back(std::unique_ptr<ProgramElement>(
  600. new FunctionDefinition(-1, *invokeDecl, std::move(main))));
  601. fSymbolTable->add(invokeDecl->fName, std::unique_ptr<FunctionDeclaration>(invokeDecl));
  602. std::vector<std::unique_ptr<VarDeclaration>> variables;
  603. Variable* loopIdx = (Variable*) (*fSymbolTable)["sk_InvocationID"];
  604. SkASSERT(loopIdx);
  605. std::unique_ptr<Expression> test(new BinaryExpression(-1,
  606. std::unique_ptr<Expression>(new VariableReference(-1, *loopIdx)),
  607. Token::LT,
  608. std::unique_ptr<IntLiteral>(new IntLiteral(fContext, -1, fInvocations)),
  609. *fContext.fBool_Type));
  610. std::unique_ptr<Expression> next(new PostfixExpression(
  611. std::unique_ptr<Expression>(
  612. new VariableReference(-1,
  613. *loopIdx,
  614. VariableReference::kReadWrite_RefKind)),
  615. Token::PLUSPLUS));
  616. ASTNode endPrimitiveID(&fFile->fNodes, -1, ASTNode::Kind::kIdentifier, "EndPrimitive");
  617. std::unique_ptr<Expression> endPrimitive = this->convertExpression(endPrimitiveID);
  618. SkASSERT(endPrimitive);
  619. std::vector<std::unique_ptr<Statement>> loopBody;
  620. std::vector<std::unique_ptr<Expression>> invokeArgs;
  621. loopBody.push_back(std::unique_ptr<Statement>(new ExpressionStatement(
  622. this->call(-1,
  623. *invokeDecl,
  624. std::vector<std::unique_ptr<Expression>>()))));
  625. loopBody.push_back(std::unique_ptr<Statement>(new ExpressionStatement(
  626. this->call(-1,
  627. std::move(endPrimitive),
  628. std::vector<std::unique_ptr<Expression>>()))));
  629. std::unique_ptr<Expression> assignment(new BinaryExpression(-1,
  630. std::unique_ptr<Expression>(new VariableReference(-1, *loopIdx)),
  631. Token::EQ,
  632. std::unique_ptr<IntLiteral>(new IntLiteral(fContext, -1, 0)),
  633. *fContext.fInt_Type));
  634. std::unique_ptr<Statement> initializer(new ExpressionStatement(std::move(assignment)));
  635. std::unique_ptr<Statement> loop = std::unique_ptr<Statement>(
  636. new ForStatement(-1,
  637. std::move(initializer),
  638. std::move(test),
  639. std::move(next),
  640. std::unique_ptr<Block>(new Block(-1, std::move(loopBody))),
  641. fSymbolTable));
  642. std::vector<std::unique_ptr<Statement>> children;
  643. children.push_back(std::move(loop));
  644. return std::unique_ptr<Block>(new Block(-1, std::move(children)));
  645. }
  646. std::unique_ptr<Statement> IRGenerator::getNormalizeSkPositionCode() {
  647. // sk_Position = float4(sk_Position.xy * rtAdjust.xz + sk_Position.ww * rtAdjust.yw,
  648. // 0,
  649. // sk_Position.w);
  650. SkASSERT(fSkPerVertex && fRTAdjust);
  651. #define REF(var) std::unique_ptr<Expression>(\
  652. new VariableReference(-1, *var, VariableReference::kRead_RefKind))
  653. #define FIELD(var, idx) std::unique_ptr<Expression>(\
  654. new FieldAccess(REF(var), idx, FieldAccess::kAnonymousInterfaceBlock_OwnerKind))
  655. #define POS std::unique_ptr<Expression>(new FieldAccess(REF(fSkPerVertex), 0, \
  656. FieldAccess::kAnonymousInterfaceBlock_OwnerKind))
  657. #define ADJUST (fRTAdjustInterfaceBlock ? \
  658. FIELD(fRTAdjustInterfaceBlock, fRTAdjustFieldIndex) : \
  659. REF(fRTAdjust))
  660. #define SWIZZLE(expr, ...) std::unique_ptr<Expression>(new Swizzle(fContext, expr, \
  661. { __VA_ARGS__ }))
  662. #define OP(left, op, right) std::unique_ptr<Expression>( \
  663. new BinaryExpression(-1, left, op, right, \
  664. *fContext.fFloat2_Type))
  665. std::vector<std::unique_ptr<Expression>> children;
  666. children.push_back(OP(OP(SWIZZLE(POS, 0, 1), Token::STAR, SWIZZLE(ADJUST, 0, 2)),
  667. Token::PLUS,
  668. OP(SWIZZLE(POS, 3, 3), Token::STAR, SWIZZLE(ADJUST, 1, 3))));
  669. children.push_back(std::unique_ptr<Expression>(new FloatLiteral(fContext, -1, 0.0)));
  670. children.push_back(SWIZZLE(POS, 3));
  671. std::unique_ptr<Expression> result = OP(POS, Token::EQ,
  672. std::unique_ptr<Expression>(new Constructor(-1,
  673. *fContext.fFloat4_Type,
  674. std::move(children))));
  675. return std::unique_ptr<Statement>(new ExpressionStatement(std::move(result)));
  676. }
  677. void IRGenerator::convertFunction(const ASTNode& f) {
  678. auto iter = f.begin();
  679. const Type* returnType = this->convertType(*(iter++));
  680. if (!returnType) {
  681. return;
  682. }
  683. const ASTNode::FunctionData& fd = f.getFunctionData();
  684. std::vector<const Variable*> parameters;
  685. for (size_t i = 0; i < fd.fParameterCount; ++i) {
  686. const ASTNode& param = *(iter++);
  687. SkASSERT(param.fKind == ASTNode::Kind::kParameter);
  688. ASTNode::ParameterData pd = param.getParameterData();
  689. auto paramIter = param.begin();
  690. const Type* type = this->convertType(*(paramIter++));
  691. if (!type) {
  692. return;
  693. }
  694. for (int j = (int) pd.fSizeCount; j >= 1; j--) {
  695. int size = (param.begin() + j)->getInt();
  696. String name = type->name() + "[" + to_string(size) + "]";
  697. type = (Type*) fSymbolTable->takeOwnership(
  698. std::unique_ptr<Symbol>(new Type(std::move(name),
  699. Type::kArray_Kind,
  700. *type,
  701. size)));
  702. }
  703. StringFragment name = pd.fName;
  704. Variable* var = (Variable*) fSymbolTable->takeOwnership(
  705. std::unique_ptr<Symbol>(new Variable(param.fOffset,
  706. pd.fModifiers,
  707. name,
  708. *type,
  709. Variable::kParameter_Storage)));
  710. parameters.push_back(var);
  711. }
  712. if (fd.fName == "main") {
  713. switch (fKind) {
  714. case Program::kPipelineStage_Kind: {
  715. bool valid;
  716. switch (parameters.size()) {
  717. case 3:
  718. valid = parameters[0]->fType == *fContext.fFloat_Type &&
  719. parameters[0]->fModifiers.fFlags == 0 &&
  720. parameters[1]->fType == *fContext.fFloat_Type &&
  721. parameters[1]->fModifiers.fFlags == 0 &&
  722. parameters[2]->fType == *fContext.fHalf4_Type &&
  723. parameters[2]->fModifiers.fFlags == (Modifiers::kIn_Flag |
  724. Modifiers::kOut_Flag);
  725. break;
  726. case 1:
  727. valid = parameters[0]->fType == *fContext.fHalf4_Type &&
  728. parameters[0]->fModifiers.fFlags == (Modifiers::kIn_Flag |
  729. Modifiers::kOut_Flag);
  730. break;
  731. default:
  732. valid = false;
  733. }
  734. if (!valid) {
  735. fErrors.error(f.fOffset, "pipeline stage 'main' must be declared main(float, "
  736. "float, inout half4) or main(inout half4)");
  737. return;
  738. }
  739. break;
  740. }
  741. case Program::kGeneric_Kind:
  742. break;
  743. default:
  744. if (parameters.size()) {
  745. fErrors.error(f.fOffset, "shader 'main' must have zero parameters");
  746. }
  747. }
  748. }
  749. // find existing declaration
  750. const FunctionDeclaration* decl = nullptr;
  751. auto entry = (*fSymbolTable)[fd.fName];
  752. if (entry) {
  753. std::vector<const FunctionDeclaration*> functions;
  754. switch (entry->fKind) {
  755. case Symbol::kUnresolvedFunction_Kind:
  756. functions = ((UnresolvedFunction*) entry)->fFunctions;
  757. break;
  758. case Symbol::kFunctionDeclaration_Kind:
  759. functions.push_back((FunctionDeclaration*) entry);
  760. break;
  761. default:
  762. fErrors.error(f.fOffset, "symbol '" + fd.fName + "' was already defined");
  763. return;
  764. }
  765. for (const auto& other : functions) {
  766. SkASSERT(other->fName == fd.fName);
  767. if (parameters.size() == other->fParameters.size()) {
  768. bool match = true;
  769. for (size_t i = 0; i < parameters.size(); i++) {
  770. if (parameters[i]->fType != other->fParameters[i]->fType) {
  771. match = false;
  772. break;
  773. }
  774. }
  775. if (match) {
  776. if (*returnType != other->fReturnType) {
  777. FunctionDeclaration newDecl(f.fOffset, fd.fModifiers, fd.fName, parameters,
  778. *returnType);
  779. fErrors.error(f.fOffset, "functions '" + newDecl.description() +
  780. "' and '" + other->description() +
  781. "' differ only in return type");
  782. return;
  783. }
  784. decl = other;
  785. for (size_t i = 0; i < parameters.size(); i++) {
  786. if (parameters[i]->fModifiers != other->fParameters[i]->fModifiers) {
  787. fErrors.error(f.fOffset, "modifiers on parameter " +
  788. to_string((uint64_t) i + 1) +
  789. " differ between declaration and "
  790. "definition");
  791. return;
  792. }
  793. }
  794. if (other->fDefined) {
  795. fErrors.error(f.fOffset, "duplicate definition of " +
  796. other->description());
  797. }
  798. break;
  799. }
  800. }
  801. }
  802. }
  803. if (!decl) {
  804. // couldn't find an existing declaration
  805. auto newDecl = std::unique_ptr<FunctionDeclaration>(new FunctionDeclaration(f.fOffset,
  806. fd.fModifiers,
  807. fd.fName,
  808. parameters,
  809. *returnType));
  810. decl = newDecl.get();
  811. fSymbolTable->add(decl->fName, std::move(newDecl));
  812. }
  813. if (iter != f.end()) {
  814. // compile body
  815. SkASSERT(!fCurrentFunction);
  816. fCurrentFunction = decl;
  817. decl->fDefined = true;
  818. std::shared_ptr<SymbolTable> old = fSymbolTable;
  819. AutoSymbolTable table(this);
  820. if (fd.fName == "main" && fKind == Program::kPipelineStage_Kind) {
  821. if (parameters.size() == 3) {
  822. parameters[0]->fModifiers.fLayout.fBuiltin = SK_MAIN_X_BUILTIN;
  823. parameters[1]->fModifiers.fLayout.fBuiltin = SK_MAIN_Y_BUILTIN;
  824. parameters[2]->fModifiers.fLayout.fBuiltin = SK_OUTCOLOR_BUILTIN;
  825. } else {
  826. SkASSERT(parameters.size() == 1);
  827. parameters[0]->fModifiers.fLayout.fBuiltin = SK_OUTCOLOR_BUILTIN;
  828. }
  829. }
  830. for (size_t i = 0; i < parameters.size(); i++) {
  831. fSymbolTable->addWithoutOwnership(parameters[i]->fName, decl->fParameters[i]);
  832. }
  833. bool needInvocationIDWorkaround = fInvocations != -1 && fd.fName == "main" &&
  834. fSettings->fCaps &&
  835. !fSettings->fCaps->gsInvocationsSupport();
  836. SkASSERT(!fExtraVars.size());
  837. std::unique_ptr<Block> body = this->convertBlock(*iter);
  838. for (auto& v : fExtraVars) {
  839. body->fStatements.insert(body->fStatements.begin(), std::move(v));
  840. }
  841. fExtraVars.clear();
  842. fCurrentFunction = nullptr;
  843. if (!body) {
  844. return;
  845. }
  846. if (needInvocationIDWorkaround) {
  847. body = this->applyInvocationIDWorkaround(std::move(body));
  848. }
  849. // conservatively assume all user-defined functions have side effects
  850. ((Modifiers&) decl->fModifiers).fFlags |= Modifiers::kHasSideEffects_Flag;
  851. if (Program::kVertex_Kind == fKind && fd.fName == "main" && fRTAdjust) {
  852. body->fStatements.insert(body->fStatements.end(), this->getNormalizeSkPositionCode());
  853. }
  854. fProgramElements->push_back(std::unique_ptr<FunctionDefinition>(
  855. new FunctionDefinition(f.fOffset, *decl, std::move(body))));
  856. }
  857. }
  858. std::unique_ptr<InterfaceBlock> IRGenerator::convertInterfaceBlock(const ASTNode& intf) {
  859. SkASSERT(intf.fKind == ASTNode::Kind::kInterfaceBlock);
  860. ASTNode::InterfaceBlockData id = intf.getInterfaceBlockData();
  861. std::shared_ptr<SymbolTable> old = fSymbolTable;
  862. this->pushSymbolTable();
  863. std::shared_ptr<SymbolTable> symbols = fSymbolTable;
  864. std::vector<Type::Field> fields;
  865. bool haveRuntimeArray = false;
  866. bool foundRTAdjust = false;
  867. auto iter = intf.begin();
  868. for (size_t i = 0; i < id.fDeclarationCount; ++i) {
  869. std::unique_ptr<VarDeclarations> decl = this->convertVarDeclarations(
  870. *(iter++),
  871. Variable::kInterfaceBlock_Storage);
  872. if (!decl) {
  873. return nullptr;
  874. }
  875. for (const auto& stmt : decl->fVars) {
  876. VarDeclaration& vd = (VarDeclaration&) *stmt;
  877. if (haveRuntimeArray) {
  878. fErrors.error(decl->fOffset,
  879. "only the last entry in an interface block may be a runtime-sized "
  880. "array");
  881. }
  882. if (vd.fVar == fRTAdjust) {
  883. foundRTAdjust = true;
  884. SkASSERT(vd.fVar->fType == *fContext.fFloat4_Type);
  885. fRTAdjustFieldIndex = fields.size();
  886. }
  887. fields.push_back(Type::Field(vd.fVar->fModifiers, vd.fVar->fName,
  888. &vd.fVar->fType));
  889. if (vd.fValue) {
  890. fErrors.error(decl->fOffset,
  891. "initializers are not permitted on interface block fields");
  892. }
  893. if (vd.fVar->fModifiers.fFlags & (Modifiers::kIn_Flag |
  894. Modifiers::kOut_Flag |
  895. Modifiers::kUniform_Flag |
  896. Modifiers::kBuffer_Flag |
  897. Modifiers::kConst_Flag)) {
  898. fErrors.error(decl->fOffset,
  899. "interface block fields may not have storage qualifiers");
  900. }
  901. if (vd.fVar->fType.kind() == Type::kArray_Kind &&
  902. vd.fVar->fType.columns() == -1) {
  903. haveRuntimeArray = true;
  904. }
  905. }
  906. }
  907. this->popSymbolTable();
  908. Type* type = (Type*) old->takeOwnership(std::unique_ptr<Symbol>(new Type(intf.fOffset,
  909. id.fTypeName,
  910. fields)));
  911. std::vector<std::unique_ptr<Expression>> sizes;
  912. for (size_t i = 0; i < id.fSizeCount; ++i) {
  913. const ASTNode& size = *(iter++);
  914. if (size) {
  915. std::unique_ptr<Expression> converted = this->convertExpression(size);
  916. if (!converted) {
  917. return nullptr;
  918. }
  919. String name = type->fName;
  920. int64_t count;
  921. if (converted->fKind == Expression::kIntLiteral_Kind) {
  922. count = ((IntLiteral&) *converted).fValue;
  923. if (count <= 0) {
  924. fErrors.error(converted->fOffset, "array size must be positive");
  925. }
  926. name += "[" + to_string(count) + "]";
  927. } else {
  928. count = -1;
  929. name += "[]";
  930. }
  931. type = (Type*) symbols->takeOwnership(std::unique_ptr<Symbol>(
  932. new Type(name,
  933. Type::kArray_Kind,
  934. *type,
  935. (int) count)));
  936. sizes.push_back(std::move(converted));
  937. } else {
  938. type = (Type*) symbols->takeOwnership(std::unique_ptr<Symbol>(
  939. new Type(type->name() + "[]",
  940. Type::kArray_Kind,
  941. *type,
  942. -1)));
  943. sizes.push_back(nullptr);
  944. }
  945. }
  946. Variable* var = (Variable*) old->takeOwnership(std::unique_ptr<Symbol>(
  947. new Variable(intf.fOffset,
  948. id.fModifiers,
  949. id.fInstanceName.fLength ? id.fInstanceName : id.fTypeName,
  950. *type,
  951. Variable::kGlobal_Storage)));
  952. if (foundRTAdjust) {
  953. fRTAdjustInterfaceBlock = var;
  954. }
  955. if (id.fInstanceName.fLength) {
  956. old->addWithoutOwnership(id.fInstanceName, var);
  957. } else {
  958. for (size_t i = 0; i < fields.size(); i++) {
  959. old->add(fields[i].fName, std::unique_ptr<Field>(new Field(intf.fOffset, *var,
  960. (int) i)));
  961. }
  962. }
  963. return std::unique_ptr<InterfaceBlock>(new InterfaceBlock(intf.fOffset,
  964. var,
  965. id.fTypeName,
  966. id.fInstanceName,
  967. std::move(sizes),
  968. symbols));
  969. }
  970. void IRGenerator::getConstantInt(const Expression& value, int64_t* out) {
  971. switch (value.fKind) {
  972. case Expression::kIntLiteral_Kind:
  973. *out = ((const IntLiteral&) value).fValue;
  974. break;
  975. case Expression::kVariableReference_Kind: {
  976. const Variable& var = ((VariableReference&) value).fVariable;
  977. if ((var.fModifiers.fFlags & Modifiers::kConst_Flag) &&
  978. var.fInitialValue) {
  979. this->getConstantInt(*var.fInitialValue, out);
  980. }
  981. break;
  982. }
  983. default:
  984. fErrors.error(value.fOffset, "expected a constant int");
  985. }
  986. }
  987. void IRGenerator::convertEnum(const ASTNode& e) {
  988. SkASSERT(e.fKind == ASTNode::Kind::kEnum);
  989. std::vector<Variable*> variables;
  990. int64_t currentValue = 0;
  991. Layout layout;
  992. ASTNode enumType(e.fNodes, e.fOffset, ASTNode::Kind::kType,
  993. ASTNode::TypeData(e.getString(), false, false));
  994. const Type* type = this->convertType(enumType);
  995. Modifiers modifiers(layout, Modifiers::kConst_Flag);
  996. std::shared_ptr<SymbolTable> symbols(new SymbolTable(fSymbolTable, &fErrors));
  997. fSymbolTable = symbols;
  998. for (auto iter = e.begin(); iter != e.end(); ++iter) {
  999. const ASTNode& child = *iter;
  1000. SkASSERT(child.fKind == ASTNode::Kind::kEnumCase);
  1001. std::unique_ptr<Expression> value;
  1002. if (child.begin() != child.end()) {
  1003. value = this->convertExpression(*child.begin());
  1004. if (!value) {
  1005. fSymbolTable = symbols->fParent;
  1006. return;
  1007. }
  1008. this->getConstantInt(*value, &currentValue);
  1009. }
  1010. value = std::unique_ptr<Expression>(new IntLiteral(fContext, e.fOffset, currentValue));
  1011. ++currentValue;
  1012. auto var = std::unique_ptr<Variable>(new Variable(e.fOffset, modifiers, child.getString(),
  1013. *type, Variable::kGlobal_Storage,
  1014. value.get()));
  1015. variables.push_back(var.get());
  1016. symbols->add(child.getString(), std::move(var));
  1017. symbols->takeOwnership(std::move(value));
  1018. }
  1019. fProgramElements->push_back(std::unique_ptr<ProgramElement>(new Enum(e.fOffset, e.getString(),
  1020. symbols)));
  1021. fSymbolTable = symbols->fParent;
  1022. }
  1023. const Type* IRGenerator::convertType(const ASTNode& type) {
  1024. ASTNode::TypeData td = type.getTypeData();
  1025. const Symbol* result = (*fSymbolTable)[td.fName];
  1026. if (result && result->fKind == Symbol::kType_Kind) {
  1027. if (td.fIsNullable) {
  1028. if (((Type&) *result) == *fContext.fFragmentProcessor_Type) {
  1029. if (type.begin() != type.end()) {
  1030. fErrors.error(type.fOffset, "type '" + td.fName + "' may not be used in "
  1031. "an array");
  1032. }
  1033. result = fSymbolTable->takeOwnership(std::unique_ptr<Symbol>(
  1034. new Type(String(result->fName) + "?",
  1035. Type::kNullable_Kind,
  1036. (const Type&) *result)));
  1037. } else {
  1038. fErrors.error(type.fOffset, "type '" + td.fName + "' may not be nullable");
  1039. }
  1040. }
  1041. for (const auto& size : type) {
  1042. String name(result->fName);
  1043. name += "[";
  1044. if (size) {
  1045. name += to_string(size.getInt());
  1046. }
  1047. name += "]";
  1048. result = (Type*) fSymbolTable->takeOwnership(std::unique_ptr<Symbol>(
  1049. new Type(name,
  1050. Type::kArray_Kind,
  1051. (const Type&) *result,
  1052. size ? size.getInt()
  1053. : 0)));
  1054. }
  1055. return (const Type*) result;
  1056. }
  1057. fErrors.error(type.fOffset, "unknown type '" + td.fName + "'");
  1058. return nullptr;
  1059. }
  1060. std::unique_ptr<Expression> IRGenerator::convertExpression(const ASTNode& expr) {
  1061. switch (expr.fKind) {
  1062. case ASTNode::Kind::kBinary:
  1063. return this->convertBinaryExpression(expr);
  1064. case ASTNode::Kind::kBool:
  1065. return std::unique_ptr<Expression>(new BoolLiteral(fContext, expr.fOffset,
  1066. expr.getBool()));
  1067. case ASTNode::Kind::kCall:
  1068. return this->convertCallExpression(expr);
  1069. case ASTNode::Kind::kField:
  1070. return this->convertFieldExpression(expr);
  1071. case ASTNode::Kind::kFloat:
  1072. return std::unique_ptr<Expression>(new FloatLiteral(fContext, expr.fOffset,
  1073. expr.getFloat()));
  1074. case ASTNode::Kind::kIdentifier:
  1075. return this->convertIdentifier(expr);
  1076. case ASTNode::Kind::kIndex:
  1077. return this->convertIndexExpression(expr);
  1078. case ASTNode::Kind::kInt:
  1079. return std::unique_ptr<Expression>(new IntLiteral(fContext, expr.fOffset,
  1080. expr.getInt()));
  1081. case ASTNode::Kind::kNull:
  1082. return std::unique_ptr<Expression>(new NullLiteral(fContext, expr.fOffset));
  1083. case ASTNode::Kind::kPostfix:
  1084. return this->convertPostfixExpression(expr);
  1085. case ASTNode::Kind::kPrefix:
  1086. return this->convertPrefixExpression(expr);
  1087. case ASTNode::Kind::kTernary:
  1088. return this->convertTernaryExpression(expr);
  1089. default:
  1090. ABORT("unsupported expression: %s\n", expr.description().c_str());
  1091. }
  1092. }
  1093. std::unique_ptr<Expression> IRGenerator::convertIdentifier(const ASTNode& identifier) {
  1094. SkASSERT(identifier.fKind == ASTNode::Kind::kIdentifier);
  1095. const Symbol* result = (*fSymbolTable)[identifier.getString()];
  1096. if (!result) {
  1097. fErrors.error(identifier.fOffset, "unknown identifier '" + identifier.getString() + "'");
  1098. return nullptr;
  1099. }
  1100. switch (result->fKind) {
  1101. case Symbol::kFunctionDeclaration_Kind: {
  1102. std::vector<const FunctionDeclaration*> f = {
  1103. (const FunctionDeclaration*) result
  1104. };
  1105. return std::unique_ptr<FunctionReference>(new FunctionReference(fContext,
  1106. identifier.fOffset,
  1107. f));
  1108. }
  1109. case Symbol::kUnresolvedFunction_Kind: {
  1110. const UnresolvedFunction* f = (const UnresolvedFunction*) result;
  1111. return std::unique_ptr<FunctionReference>(new FunctionReference(fContext,
  1112. identifier.fOffset,
  1113. f->fFunctions));
  1114. }
  1115. case Symbol::kVariable_Kind: {
  1116. const Variable* var = (const Variable*) result;
  1117. switch (var->fModifiers.fLayout.fBuiltin) {
  1118. case SK_WIDTH_BUILTIN:
  1119. fInputs.fRTWidth = true;
  1120. break;
  1121. case SK_HEIGHT_BUILTIN:
  1122. fInputs.fRTHeight = true;
  1123. break;
  1124. #ifndef SKSL_STANDALONE
  1125. case SK_FRAGCOORD_BUILTIN:
  1126. if (var->fModifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
  1127. fInputs.fFlipY = true;
  1128. if (fSettings->fFlipY &&
  1129. (!fSettings->fCaps ||
  1130. !fSettings->fCaps->fragCoordConventionsExtensionString())) {
  1131. fInputs.fRTHeight = true;
  1132. }
  1133. }
  1134. #endif
  1135. }
  1136. // default to kRead_RefKind; this will be corrected later if the variable is written to
  1137. return std::unique_ptr<VariableReference>(new VariableReference(
  1138. identifier.fOffset,
  1139. *var,
  1140. VariableReference::kRead_RefKind));
  1141. }
  1142. case Symbol::kField_Kind: {
  1143. const Field* field = (const Field*) result;
  1144. VariableReference* base = new VariableReference(identifier.fOffset, field->fOwner,
  1145. VariableReference::kRead_RefKind);
  1146. return std::unique_ptr<Expression>(new FieldAccess(
  1147. std::unique_ptr<Expression>(base),
  1148. field->fFieldIndex,
  1149. FieldAccess::kAnonymousInterfaceBlock_OwnerKind));
  1150. }
  1151. case Symbol::kType_Kind: {
  1152. const Type* t = (const Type*) result;
  1153. return std::unique_ptr<TypeReference>(new TypeReference(fContext, identifier.fOffset,
  1154. *t));
  1155. }
  1156. case Symbol::kExternal_Kind: {
  1157. ExternalValue* r = (ExternalValue*) result;
  1158. return std::unique_ptr<ExternalValueReference>(
  1159. new ExternalValueReference(identifier.fOffset, r));
  1160. }
  1161. default:
  1162. ABORT("unsupported symbol type %d\n", result->fKind);
  1163. }
  1164. }
  1165. std::unique_ptr<Section> IRGenerator::convertSection(const ASTNode& s) {
  1166. ASTNode::SectionData section = s.getSectionData();
  1167. return std::unique_ptr<Section>(new Section(s.fOffset, section.fName, section.fArgument,
  1168. section.fText));
  1169. }
  1170. std::unique_ptr<Expression> IRGenerator::coerce(std::unique_ptr<Expression> expr,
  1171. const Type& type) {
  1172. if (!expr) {
  1173. return nullptr;
  1174. }
  1175. if (expr->fType == type) {
  1176. return expr;
  1177. }
  1178. this->checkValid(*expr);
  1179. if (expr->fType == *fContext.fInvalid_Type) {
  1180. return nullptr;
  1181. }
  1182. if (expr->coercionCost(type) == INT_MAX) {
  1183. fErrors.error(expr->fOffset, "expected '" + type.description() + "', but found '" +
  1184. expr->fType.description() + "'");
  1185. return nullptr;
  1186. }
  1187. if (type.kind() == Type::kScalar_Kind) {
  1188. std::vector<std::unique_ptr<Expression>> args;
  1189. args.push_back(std::move(expr));
  1190. std::unique_ptr<Expression> ctor;
  1191. if (type == *fContext.fFloatLiteral_Type) {
  1192. ctor = this->convertIdentifier(ASTNode(&fFile->fNodes, -1, ASTNode::Kind::kIdentifier,
  1193. "float"));
  1194. } else if (type == *fContext.fIntLiteral_Type) {
  1195. ctor = this->convertIdentifier(ASTNode(&fFile->fNodes, -1, ASTNode::Kind::kIdentifier,
  1196. "int"));
  1197. } else {
  1198. ctor = this->convertIdentifier(ASTNode(&fFile->fNodes, -1, ASTNode::Kind::kIdentifier,
  1199. type.fName));
  1200. }
  1201. if (!ctor) {
  1202. printf("error, null identifier: %s\n", String(type.fName).c_str());
  1203. }
  1204. SkASSERT(ctor);
  1205. return this->call(-1, std::move(ctor), std::move(args));
  1206. }
  1207. if (expr->fKind == Expression::kNullLiteral_Kind) {
  1208. SkASSERT(type.kind() == Type::kNullable_Kind);
  1209. return std::unique_ptr<Expression>(new NullLiteral(expr->fOffset, type));
  1210. }
  1211. std::vector<std::unique_ptr<Expression>> args;
  1212. args.push_back(std::move(expr));
  1213. return std::unique_ptr<Expression>(new Constructor(-1, type, std::move(args)));
  1214. }
  1215. static bool is_matrix_multiply(const Type& left, const Type& right) {
  1216. if (left.kind() == Type::kMatrix_Kind) {
  1217. return right.kind() == Type::kMatrix_Kind || right.kind() == Type::kVector_Kind;
  1218. }
  1219. return left.kind() == Type::kVector_Kind && right.kind() == Type::kMatrix_Kind;
  1220. }
  1221. /**
  1222. * Determines the operand and result types of a binary expression. Returns true if the expression is
  1223. * legal, false otherwise. If false, the values of the out parameters are undefined.
  1224. */
  1225. static bool determine_binary_type(const Context& context,
  1226. Token::Kind op,
  1227. const Type& left,
  1228. const Type& right,
  1229. const Type** outLeftType,
  1230. const Type** outRightType,
  1231. const Type** outResultType,
  1232. bool tryFlipped) {
  1233. bool isLogical;
  1234. bool validMatrixOrVectorOp;
  1235. switch (op) {
  1236. case Token::EQ:
  1237. *outLeftType = &left;
  1238. *outRightType = &left;
  1239. *outResultType = &left;
  1240. return right.canCoerceTo(left);
  1241. case Token::EQEQ: // fall through
  1242. case Token::NEQ:
  1243. if (right.canCoerceTo(left)) {
  1244. *outLeftType = &left;
  1245. *outRightType = &left;
  1246. *outResultType = context.fBool_Type.get();
  1247. return true;
  1248. } if (left.canCoerceTo(right)) {
  1249. *outLeftType = &right;
  1250. *outRightType = &right;
  1251. *outResultType = context.fBool_Type.get();
  1252. return true;
  1253. }
  1254. return false;
  1255. case Token::LT: // fall through
  1256. case Token::GT: // fall through
  1257. case Token::LTEQ: // fall through
  1258. case Token::GTEQ:
  1259. isLogical = true;
  1260. validMatrixOrVectorOp = false;
  1261. break;
  1262. case Token::LOGICALOR: // fall through
  1263. case Token::LOGICALAND: // fall through
  1264. case Token::LOGICALXOR: // fall through
  1265. case Token::LOGICALOREQ: // fall through
  1266. case Token::LOGICALANDEQ: // fall through
  1267. case Token::LOGICALXOREQ:
  1268. *outLeftType = context.fBool_Type.get();
  1269. *outRightType = context.fBool_Type.get();
  1270. *outResultType = context.fBool_Type.get();
  1271. return left.canCoerceTo(*context.fBool_Type) &&
  1272. right.canCoerceTo(*context.fBool_Type);
  1273. case Token::STAREQ:
  1274. if (left.kind() == Type::kScalar_Kind) {
  1275. *outLeftType = &left;
  1276. *outRightType = &left;
  1277. *outResultType = &left;
  1278. return right.canCoerceTo(left);
  1279. }
  1280. // fall through
  1281. case Token::STAR:
  1282. if (is_matrix_multiply(left, right)) {
  1283. // determine final component type
  1284. if (determine_binary_type(context, Token::STAR, left.componentType(),
  1285. right.componentType(), outLeftType, outRightType,
  1286. outResultType, false)) {
  1287. *outLeftType = &(*outResultType)->toCompound(context, left.columns(),
  1288. left.rows());
  1289. *outRightType = &(*outResultType)->toCompound(context, right.columns(),
  1290. right.rows());
  1291. int leftColumns = left.columns();
  1292. int leftRows = left.rows();
  1293. int rightColumns;
  1294. int rightRows;
  1295. if (right.kind() == Type::kVector_Kind) {
  1296. // matrix * vector treats the vector as a column vector, so we need to
  1297. // transpose it
  1298. rightColumns = right.rows();
  1299. rightRows = right.columns();
  1300. SkASSERT(rightColumns == 1);
  1301. } else {
  1302. rightColumns = right.columns();
  1303. rightRows = right.rows();
  1304. }
  1305. if (rightColumns > 1) {
  1306. *outResultType = &(*outResultType)->toCompound(context, rightColumns,
  1307. leftRows);
  1308. } else {
  1309. // result was a column vector, transpose it back to a row
  1310. *outResultType = &(*outResultType)->toCompound(context, leftRows,
  1311. rightColumns);
  1312. }
  1313. return leftColumns == rightRows;
  1314. } else {
  1315. return false;
  1316. }
  1317. }
  1318. isLogical = false;
  1319. validMatrixOrVectorOp = true;
  1320. break;
  1321. case Token::PLUSEQ:
  1322. case Token::MINUSEQ:
  1323. case Token::SLASHEQ:
  1324. case Token::PERCENTEQ:
  1325. case Token::SHLEQ:
  1326. case Token::SHREQ:
  1327. if (left.kind() == Type::kScalar_Kind) {
  1328. *outLeftType = &left;
  1329. *outRightType = &left;
  1330. *outResultType = &left;
  1331. return right.canCoerceTo(left);
  1332. }
  1333. // fall through
  1334. case Token::PLUS: // fall through
  1335. case Token::MINUS: // fall through
  1336. case Token::SLASH: // fall through
  1337. isLogical = false;
  1338. validMatrixOrVectorOp = true;
  1339. break;
  1340. case Token::COMMA:
  1341. *outLeftType = &left;
  1342. *outRightType = &right;
  1343. *outResultType = &right;
  1344. return true;
  1345. default:
  1346. isLogical = false;
  1347. validMatrixOrVectorOp = false;
  1348. }
  1349. bool isVectorOrMatrix = left.kind() == Type::kVector_Kind || left.kind() == Type::kMatrix_Kind;
  1350. if (left.kind() == Type::kScalar_Kind && right.kind() == Type::kScalar_Kind &&
  1351. right.canCoerceTo(left)) {
  1352. if (left.priority() > right.priority()) {
  1353. *outLeftType = &left;
  1354. *outRightType = &left;
  1355. } else {
  1356. *outLeftType = &right;
  1357. *outRightType = &right;
  1358. }
  1359. if (isLogical) {
  1360. *outResultType = context.fBool_Type.get();
  1361. } else {
  1362. *outResultType = &left;
  1363. }
  1364. return true;
  1365. }
  1366. if (right.canCoerceTo(left) && isVectorOrMatrix && validMatrixOrVectorOp) {
  1367. *outLeftType = &left;
  1368. *outRightType = &left;
  1369. if (isLogical) {
  1370. *outResultType = context.fBool_Type.get();
  1371. } else {
  1372. *outResultType = &left;
  1373. }
  1374. return true;
  1375. }
  1376. if ((left.kind() == Type::kVector_Kind || left.kind() == Type::kMatrix_Kind) &&
  1377. (right.kind() == Type::kScalar_Kind)) {
  1378. if (determine_binary_type(context, op, left.componentType(), right, outLeftType,
  1379. outRightType, outResultType, false)) {
  1380. *outLeftType = &(*outLeftType)->toCompound(context, left.columns(), left.rows());
  1381. if (!isLogical) {
  1382. *outResultType = &(*outResultType)->toCompound(context, left.columns(),
  1383. left.rows());
  1384. }
  1385. return true;
  1386. }
  1387. return false;
  1388. }
  1389. if (tryFlipped) {
  1390. return determine_binary_type(context, op, right, left, outRightType, outLeftType,
  1391. outResultType, false);
  1392. }
  1393. return false;
  1394. }
  1395. static std::unique_ptr<Expression> short_circuit_boolean(const Context& context,
  1396. const Expression& left,
  1397. Token::Kind op,
  1398. const Expression& right) {
  1399. SkASSERT(left.fKind == Expression::kBoolLiteral_Kind);
  1400. bool leftVal = ((BoolLiteral&) left).fValue;
  1401. if (op == Token::LOGICALAND) {
  1402. // (true && expr) -> (expr) and (false && expr) -> (false)
  1403. return leftVal ? right.clone()
  1404. : std::unique_ptr<Expression>(new BoolLiteral(context, left.fOffset, false));
  1405. } else if (op == Token::LOGICALOR) {
  1406. // (true || expr) -> (true) and (false || expr) -> (expr)
  1407. return leftVal ? std::unique_ptr<Expression>(new BoolLiteral(context, left.fOffset, true))
  1408. : right.clone();
  1409. } else {
  1410. // Can't short circuit XOR
  1411. return nullptr;
  1412. }
  1413. }
  1414. std::unique_ptr<Expression> IRGenerator::constantFold(const Expression& left,
  1415. Token::Kind op,
  1416. const Expression& right) const {
  1417. // If the left side is a constant boolean literal, the right side does not need to be constant
  1418. // for short circuit optimizations to allow the constant to be folded.
  1419. if (left.fKind == Expression::kBoolLiteral_Kind && !right.isConstant()) {
  1420. return short_circuit_boolean(fContext, left, op, right);
  1421. } else if (right.fKind == Expression::kBoolLiteral_Kind && !left.isConstant()) {
  1422. // There aren't side effects in SKSL within expressions, so (left OP right) is equivalent to
  1423. // (right OP left) for short-circuit optimizations
  1424. return short_circuit_boolean(fContext, right, op, left);
  1425. }
  1426. // Other than the short-circuit cases above, constant folding requires both sides to be constant
  1427. if (!left.isConstant() || !right.isConstant()) {
  1428. return nullptr;
  1429. }
  1430. // Note that we expressly do not worry about precision and overflow here -- we use the maximum
  1431. // precision to calculate the results and hope the result makes sense. The plan is to move the
  1432. // Skia caps into SkSL, so we have access to all of them including the precisions of the various
  1433. // types, which will let us be more intelligent about this.
  1434. if (left.fKind == Expression::kBoolLiteral_Kind &&
  1435. right.fKind == Expression::kBoolLiteral_Kind) {
  1436. bool leftVal = ((BoolLiteral&) left).fValue;
  1437. bool rightVal = ((BoolLiteral&) right).fValue;
  1438. bool result;
  1439. switch (op) {
  1440. case Token::LOGICALAND: result = leftVal && rightVal; break;
  1441. case Token::LOGICALOR: result = leftVal || rightVal; break;
  1442. case Token::LOGICALXOR: result = leftVal ^ rightVal; break;
  1443. default: return nullptr;
  1444. }
  1445. return std::unique_ptr<Expression>(new BoolLiteral(fContext, left.fOffset, result));
  1446. }
  1447. #define RESULT(t, op) std::unique_ptr<Expression>(new t ## Literal(fContext, left.fOffset, \
  1448. leftVal op rightVal))
  1449. if (left.fKind == Expression::kIntLiteral_Kind && right.fKind == Expression::kIntLiteral_Kind) {
  1450. int64_t leftVal = ((IntLiteral&) left).fValue;
  1451. int64_t rightVal = ((IntLiteral&) right).fValue;
  1452. switch (op) {
  1453. case Token::PLUS: return RESULT(Int, +);
  1454. case Token::MINUS: return RESULT(Int, -);
  1455. case Token::STAR: return RESULT(Int, *);
  1456. case Token::SLASH:
  1457. if (rightVal) {
  1458. return RESULT(Int, /);
  1459. }
  1460. fErrors.error(right.fOffset, "division by zero");
  1461. return nullptr;
  1462. case Token::PERCENT:
  1463. if (rightVal) {
  1464. return RESULT(Int, %);
  1465. }
  1466. fErrors.error(right.fOffset, "division by zero");
  1467. return nullptr;
  1468. case Token::BITWISEAND: return RESULT(Int, &);
  1469. case Token::BITWISEOR: return RESULT(Int, |);
  1470. case Token::BITWISEXOR: return RESULT(Int, ^);
  1471. case Token::EQEQ: return RESULT(Bool, ==);
  1472. case Token::NEQ: return RESULT(Bool, !=);
  1473. case Token::GT: return RESULT(Bool, >);
  1474. case Token::GTEQ: return RESULT(Bool, >=);
  1475. case Token::LT: return RESULT(Bool, <);
  1476. case Token::LTEQ: return RESULT(Bool, <=);
  1477. case Token::SHL:
  1478. if (rightVal >= 0 && rightVal <= 31) {
  1479. return RESULT(Int, <<);
  1480. }
  1481. fErrors.error(right.fOffset, "shift value out of range");
  1482. return nullptr;
  1483. case Token::SHR:
  1484. if (rightVal >= 0 && rightVal <= 31) {
  1485. return RESULT(Int, >>);
  1486. }
  1487. fErrors.error(right.fOffset, "shift value out of range");
  1488. return nullptr;
  1489. default:
  1490. return nullptr;
  1491. }
  1492. }
  1493. if (left.fKind == Expression::kFloatLiteral_Kind &&
  1494. right.fKind == Expression::kFloatLiteral_Kind) {
  1495. double leftVal = ((FloatLiteral&) left).fValue;
  1496. double rightVal = ((FloatLiteral&) right).fValue;
  1497. switch (op) {
  1498. case Token::PLUS: return RESULT(Float, +);
  1499. case Token::MINUS: return RESULT(Float, -);
  1500. case Token::STAR: return RESULT(Float, *);
  1501. case Token::SLASH:
  1502. if (rightVal) {
  1503. return RESULT(Float, /);
  1504. }
  1505. fErrors.error(right.fOffset, "division by zero");
  1506. return nullptr;
  1507. case Token::EQEQ: return RESULT(Bool, ==);
  1508. case Token::NEQ: return RESULT(Bool, !=);
  1509. case Token::GT: return RESULT(Bool, >);
  1510. case Token::GTEQ: return RESULT(Bool, >=);
  1511. case Token::LT: return RESULT(Bool, <);
  1512. case Token::LTEQ: return RESULT(Bool, <=);
  1513. default: return nullptr;
  1514. }
  1515. }
  1516. if (left.fType.kind() == Type::kVector_Kind && left.fType.componentType().isFloat() &&
  1517. left.fType == right.fType) {
  1518. std::vector<std::unique_ptr<Expression>> args;
  1519. #define RETURN_VEC_COMPONENTWISE_RESULT(op) \
  1520. for (int i = 0; i < left.fType.columns(); i++) { \
  1521. float value = left.getFVecComponent(i) op \
  1522. right.getFVecComponent(i); \
  1523. args.emplace_back(new FloatLiteral(fContext, -1, value)); \
  1524. } \
  1525. return std::unique_ptr<Expression>(new Constructor(-1, left.fType, \
  1526. std::move(args)))
  1527. switch (op) {
  1528. case Token::EQEQ:
  1529. return std::unique_ptr<Expression>(new BoolLiteral(fContext, -1,
  1530. left.compareConstant(fContext, right)));
  1531. case Token::NEQ:
  1532. return std::unique_ptr<Expression>(new BoolLiteral(fContext, -1,
  1533. !left.compareConstant(fContext, right)));
  1534. case Token::PLUS: RETURN_VEC_COMPONENTWISE_RESULT(+);
  1535. case Token::MINUS: RETURN_VEC_COMPONENTWISE_RESULT(-);
  1536. case Token::STAR: RETURN_VEC_COMPONENTWISE_RESULT(*);
  1537. case Token::SLASH:
  1538. for (int i = 0; i < left.fType.columns(); i++) {
  1539. SKSL_FLOAT rvalue = right.getFVecComponent(i);
  1540. if (rvalue == 0.0) {
  1541. fErrors.error(right.fOffset, "division by zero");
  1542. return nullptr;
  1543. }
  1544. float value = left.getFVecComponent(i) / rvalue;
  1545. args.emplace_back(new FloatLiteral(fContext, -1, value));
  1546. }
  1547. return std::unique_ptr<Expression>(new Constructor(-1, left.fType,
  1548. std::move(args)));
  1549. default: return nullptr;
  1550. }
  1551. }
  1552. if (left.fType.kind() == Type::kMatrix_Kind &&
  1553. right.fType.kind() == Type::kMatrix_Kind &&
  1554. left.fKind == right.fKind) {
  1555. switch (op) {
  1556. case Token::EQEQ:
  1557. return std::unique_ptr<Expression>(new BoolLiteral(fContext, -1,
  1558. left.compareConstant(fContext, right)));
  1559. case Token::NEQ:
  1560. return std::unique_ptr<Expression>(new BoolLiteral(fContext, -1,
  1561. !left.compareConstant(fContext, right)));
  1562. default:
  1563. return nullptr;
  1564. }
  1565. }
  1566. #undef RESULT
  1567. return nullptr;
  1568. }
  1569. std::unique_ptr<Expression> IRGenerator::convertBinaryExpression(const ASTNode& expression) {
  1570. SkASSERT(expression.fKind == ASTNode::Kind::kBinary);
  1571. auto iter = expression.begin();
  1572. std::unique_ptr<Expression> left = this->convertExpression(*(iter++));
  1573. if (!left) {
  1574. return nullptr;
  1575. }
  1576. std::unique_ptr<Expression> right = this->convertExpression(*(iter++));
  1577. if (!right) {
  1578. return nullptr;
  1579. }
  1580. const Type* leftType;
  1581. const Type* rightType;
  1582. const Type* resultType;
  1583. const Type* rawLeftType;
  1584. if (left->fKind == Expression::kIntLiteral_Kind && right->fType.isInteger()) {
  1585. rawLeftType = &right->fType;
  1586. } else {
  1587. rawLeftType = &left->fType;
  1588. }
  1589. const Type* rawRightType;
  1590. if (right->fKind == Expression::kIntLiteral_Kind && left->fType.isInteger()) {
  1591. rawRightType = &left->fType;
  1592. } else {
  1593. rawRightType = &right->fType;
  1594. }
  1595. Token::Kind op = expression.getToken().fKind;
  1596. if (!determine_binary_type(fContext, op, *rawLeftType, *rawRightType, &leftType, &rightType,
  1597. &resultType, !Compiler::IsAssignment(op))) {
  1598. fErrors.error(expression.fOffset, String("type mismatch: '") +
  1599. Compiler::OperatorName(expression.getToken().fKind) +
  1600. "' cannot operate on '" + left->fType.description() +
  1601. "', '" + right->fType.description() + "'");
  1602. return nullptr;
  1603. }
  1604. if (Compiler::IsAssignment(op)) {
  1605. this->setRefKind(*left, op != Token::EQ ? VariableReference::kReadWrite_RefKind :
  1606. VariableReference::kWrite_RefKind);
  1607. }
  1608. left = this->coerce(std::move(left), *leftType);
  1609. right = this->coerce(std::move(right), *rightType);
  1610. if (!left || !right) {
  1611. return nullptr;
  1612. }
  1613. std::unique_ptr<Expression> result = this->constantFold(*left.get(), op, *right.get());
  1614. if (!result) {
  1615. result = std::unique_ptr<Expression>(new BinaryExpression(expression.fOffset,
  1616. std::move(left),
  1617. op,
  1618. std::move(right),
  1619. *resultType));
  1620. }
  1621. return result;
  1622. }
  1623. std::unique_ptr<Expression> IRGenerator::convertTernaryExpression(const ASTNode& node) {
  1624. SkASSERT(node.fKind == ASTNode::Kind::kTernary);
  1625. auto iter = node.begin();
  1626. std::unique_ptr<Expression> test = this->coerce(this->convertExpression(*(iter++)),
  1627. *fContext.fBool_Type);
  1628. if (!test) {
  1629. return nullptr;
  1630. }
  1631. std::unique_ptr<Expression> ifTrue = this->convertExpression(*(iter++));
  1632. if (!ifTrue) {
  1633. return nullptr;
  1634. }
  1635. std::unique_ptr<Expression> ifFalse = this->convertExpression(*(iter++));
  1636. if (!ifFalse) {
  1637. return nullptr;
  1638. }
  1639. const Type* trueType;
  1640. const Type* falseType;
  1641. const Type* resultType;
  1642. if (!determine_binary_type(fContext, Token::EQEQ, ifTrue->fType, ifFalse->fType, &trueType,
  1643. &falseType, &resultType, true) || trueType != falseType) {
  1644. fErrors.error(node.fOffset, "ternary operator result mismatch: '" +
  1645. ifTrue->fType.description() + "', '" +
  1646. ifFalse->fType.description() + "'");
  1647. return nullptr;
  1648. }
  1649. ifTrue = this->coerce(std::move(ifTrue), *trueType);
  1650. if (!ifTrue) {
  1651. return nullptr;
  1652. }
  1653. ifFalse = this->coerce(std::move(ifFalse), *falseType);
  1654. if (!ifFalse) {
  1655. return nullptr;
  1656. }
  1657. if (test->fKind == Expression::kBoolLiteral_Kind) {
  1658. // static boolean test, just return one of the branches
  1659. if (((BoolLiteral&) *test).fValue) {
  1660. return ifTrue;
  1661. } else {
  1662. return ifFalse;
  1663. }
  1664. }
  1665. return std::unique_ptr<Expression>(new TernaryExpression(node.fOffset,
  1666. std::move(test),
  1667. std::move(ifTrue),
  1668. std::move(ifFalse)));
  1669. }
  1670. std::unique_ptr<Expression> IRGenerator::call(int offset,
  1671. const FunctionDeclaration& function,
  1672. std::vector<std::unique_ptr<Expression>> arguments) {
  1673. if (function.fParameters.size() != arguments.size()) {
  1674. String msg = "call to '" + function.fName + "' expected " +
  1675. to_string((uint64_t) function.fParameters.size()) +
  1676. " argument";
  1677. if (function.fParameters.size() != 1) {
  1678. msg += "s";
  1679. }
  1680. msg += ", but found " + to_string((uint64_t) arguments.size());
  1681. fErrors.error(offset, msg);
  1682. return nullptr;
  1683. }
  1684. std::vector<const Type*> types;
  1685. const Type* returnType;
  1686. if (!function.determineFinalTypes(arguments, &types, &returnType)) {
  1687. String msg = "no match for " + function.fName + "(";
  1688. String separator;
  1689. for (size_t i = 0; i < arguments.size(); i++) {
  1690. msg += separator;
  1691. separator = ", ";
  1692. msg += arguments[i]->fType.description();
  1693. }
  1694. msg += ")";
  1695. fErrors.error(offset, msg);
  1696. return nullptr;
  1697. }
  1698. for (size_t i = 0; i < arguments.size(); i++) {
  1699. arguments[i] = this->coerce(std::move(arguments[i]), *types[i]);
  1700. if (!arguments[i]) {
  1701. return nullptr;
  1702. }
  1703. if (arguments[i] && (function.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag)) {
  1704. this->setRefKind(*arguments[i],
  1705. function.fParameters[i]->fModifiers.fFlags & Modifiers::kIn_Flag ?
  1706. VariableReference::kReadWrite_RefKind :
  1707. VariableReference::kPointer_RefKind);
  1708. }
  1709. }
  1710. return std::unique_ptr<FunctionCall>(new FunctionCall(offset, *returnType, function,
  1711. std::move(arguments)));
  1712. }
  1713. /**
  1714. * Determines the cost of coercing the arguments of a function to the required types. Cost has no
  1715. * particular meaning other than "lower costs are preferred". Returns INT_MAX if the call is not
  1716. * valid.
  1717. */
  1718. int IRGenerator::callCost(const FunctionDeclaration& function,
  1719. const std::vector<std::unique_ptr<Expression>>& arguments) {
  1720. if (function.fParameters.size() != arguments.size()) {
  1721. return INT_MAX;
  1722. }
  1723. int total = 0;
  1724. std::vector<const Type*> types;
  1725. const Type* ignored;
  1726. if (!function.determineFinalTypes(arguments, &types, &ignored)) {
  1727. return INT_MAX;
  1728. }
  1729. for (size_t i = 0; i < arguments.size(); i++) {
  1730. int cost = arguments[i]->coercionCost(*types[i]);
  1731. if (cost != INT_MAX) {
  1732. total += cost;
  1733. } else {
  1734. return INT_MAX;
  1735. }
  1736. }
  1737. return total;
  1738. }
  1739. std::unique_ptr<Expression> IRGenerator::call(int offset,
  1740. std::unique_ptr<Expression> functionValue,
  1741. std::vector<std::unique_ptr<Expression>> arguments) {
  1742. switch (functionValue->fKind) {
  1743. case Expression::kTypeReference_Kind:
  1744. return this->convertConstructor(offset,
  1745. ((TypeReference&) *functionValue).fValue,
  1746. std::move(arguments));
  1747. case Expression::kExternalValue_Kind: {
  1748. ExternalValue* v = ((ExternalValueReference&) *functionValue).fValue;
  1749. if (!v->canCall()) {
  1750. fErrors.error(offset, "this external value is not a function");
  1751. return nullptr;
  1752. }
  1753. int count = v->callParameterCount();
  1754. if (count != (int) arguments.size()) {
  1755. fErrors.error(offset, "external function expected " + to_string(count) +
  1756. " arguments, but found " + to_string((int) arguments.size()));
  1757. return nullptr;
  1758. }
  1759. static constexpr int PARAMETER_MAX = 16;
  1760. SkASSERT(count < PARAMETER_MAX);
  1761. const Type* types[PARAMETER_MAX];
  1762. v->getCallParameterTypes(types);
  1763. for (int i = 0; i < count; ++i) {
  1764. arguments[i] = this->coerce(std::move(arguments[i]), *types[i]);
  1765. if (!arguments[i]) {
  1766. return nullptr;
  1767. }
  1768. }
  1769. return std::unique_ptr<Expression>(new ExternalFunctionCall(offset, v->callReturnType(),
  1770. v, std::move(arguments)));
  1771. }
  1772. case Expression::kFunctionReference_Kind: {
  1773. FunctionReference* ref = (FunctionReference*) functionValue.get();
  1774. int bestCost = INT_MAX;
  1775. const FunctionDeclaration* best = nullptr;
  1776. if (ref->fFunctions.size() > 1) {
  1777. for (const auto& f : ref->fFunctions) {
  1778. int cost = this->callCost(*f, arguments);
  1779. if (cost < bestCost) {
  1780. bestCost = cost;
  1781. best = f;
  1782. }
  1783. }
  1784. if (best) {
  1785. return this->call(offset, *best, std::move(arguments));
  1786. }
  1787. String msg = "no match for " + ref->fFunctions[0]->fName + "(";
  1788. String separator;
  1789. for (size_t i = 0; i < arguments.size(); i++) {
  1790. msg += separator;
  1791. separator = ", ";
  1792. msg += arguments[i]->fType.description();
  1793. }
  1794. msg += ")";
  1795. fErrors.error(offset, msg);
  1796. return nullptr;
  1797. }
  1798. return this->call(offset, *ref->fFunctions[0], std::move(arguments));
  1799. }
  1800. default:
  1801. fErrors.error(offset, "'" + functionValue->description() + "' is not a function");
  1802. return nullptr;
  1803. }
  1804. }
  1805. std::unique_ptr<Expression> IRGenerator::convertNumberConstructor(
  1806. int offset,
  1807. const Type& type,
  1808. std::vector<std::unique_ptr<Expression>> args) {
  1809. SkASSERT(type.isNumber());
  1810. if (args.size() != 1) {
  1811. fErrors.error(offset, "invalid arguments to '" + type.description() +
  1812. "' constructor, (expected exactly 1 argument, but found " +
  1813. to_string((uint64_t) args.size()) + ")");
  1814. return nullptr;
  1815. }
  1816. if (type == args[0]->fType) {
  1817. return std::move(args[0]);
  1818. }
  1819. if (type.isFloat() && args.size() == 1 && args[0]->fKind == Expression::kFloatLiteral_Kind) {
  1820. double value = ((FloatLiteral&) *args[0]).fValue;
  1821. return std::unique_ptr<Expression>(new FloatLiteral(offset, value, &type));
  1822. }
  1823. if (type.isFloat() && args.size() == 1 && args[0]->fKind == Expression::kIntLiteral_Kind) {
  1824. int64_t value = ((IntLiteral&) *args[0]).fValue;
  1825. return std::unique_ptr<Expression>(new FloatLiteral(offset, (double) value, &type));
  1826. }
  1827. if (args[0]->fKind == Expression::kIntLiteral_Kind && (type == *fContext.fInt_Type ||
  1828. type == *fContext.fUInt_Type)) {
  1829. return std::unique_ptr<Expression>(new IntLiteral(offset,
  1830. ((IntLiteral&) *args[0]).fValue,
  1831. &type));
  1832. }
  1833. if (args[0]->fType == *fContext.fBool_Type) {
  1834. std::unique_ptr<IntLiteral> zero(new IntLiteral(fContext, offset, 0));
  1835. std::unique_ptr<IntLiteral> one(new IntLiteral(fContext, offset, 1));
  1836. return std::unique_ptr<Expression>(
  1837. new TernaryExpression(offset, std::move(args[0]),
  1838. this->coerce(std::move(one), type),
  1839. this->coerce(std::move(zero),
  1840. type)));
  1841. }
  1842. if (!args[0]->fType.isNumber()) {
  1843. fErrors.error(offset, "invalid argument to '" + type.description() +
  1844. "' constructor (expected a number or bool, but found '" +
  1845. args[0]->fType.description() + "')");
  1846. return nullptr;
  1847. }
  1848. return std::unique_ptr<Expression>(new Constructor(offset, type, std::move(args)));
  1849. }
  1850. int component_count(const Type& type) {
  1851. switch (type.kind()) {
  1852. case Type::kVector_Kind:
  1853. return type.columns();
  1854. case Type::kMatrix_Kind:
  1855. return type.columns() * type.rows();
  1856. default:
  1857. return 1;
  1858. }
  1859. }
  1860. std::unique_ptr<Expression> IRGenerator::convertCompoundConstructor(
  1861. int offset,
  1862. const Type& type,
  1863. std::vector<std::unique_ptr<Expression>> args) {
  1864. SkASSERT(type.kind() == Type::kVector_Kind || type.kind() == Type::kMatrix_Kind);
  1865. if (type.kind() == Type::kMatrix_Kind && args.size() == 1 &&
  1866. args[0]->fType.kind() == Type::kMatrix_Kind) {
  1867. // matrix from matrix is always legal
  1868. return std::unique_ptr<Expression>(new Constructor(offset, type, std::move(args)));
  1869. }
  1870. int actual = 0;
  1871. int expected = type.rows() * type.columns();
  1872. if (args.size() != 1 || expected != component_count(args[0]->fType) ||
  1873. type.componentType().isNumber() != args[0]->fType.componentType().isNumber()) {
  1874. for (size_t i = 0; i < args.size(); i++) {
  1875. if (args[i]->fType.kind() == Type::kVector_Kind) {
  1876. if (type.componentType().isNumber() !=
  1877. args[i]->fType.componentType().isNumber()) {
  1878. fErrors.error(offset, "'" + args[i]->fType.description() + "' is not a valid "
  1879. "parameter to '" + type.description() +
  1880. "' constructor");
  1881. return nullptr;
  1882. }
  1883. actual += args[i]->fType.columns();
  1884. } else if (args[i]->fType.kind() == Type::kScalar_Kind) {
  1885. actual += 1;
  1886. if (type.kind() != Type::kScalar_Kind) {
  1887. args[i] = this->coerce(std::move(args[i]), type.componentType());
  1888. if (!args[i]) {
  1889. return nullptr;
  1890. }
  1891. }
  1892. } else {
  1893. fErrors.error(offset, "'" + args[i]->fType.description() + "' is not a valid "
  1894. "parameter to '" + type.description() + "' constructor");
  1895. return nullptr;
  1896. }
  1897. }
  1898. if (actual != 1 && actual != expected) {
  1899. fErrors.error(offset, "invalid arguments to '" + type.description() +
  1900. "' constructor (expected " + to_string(expected) +
  1901. " scalars, but found " + to_string(actual) + ")");
  1902. return nullptr;
  1903. }
  1904. }
  1905. return std::unique_ptr<Expression>(new Constructor(offset, type, std::move(args)));
  1906. }
  1907. std::unique_ptr<Expression> IRGenerator::convertConstructor(
  1908. int offset,
  1909. const Type& type,
  1910. std::vector<std::unique_ptr<Expression>> args) {
  1911. // FIXME: add support for structs
  1912. Type::Kind kind = type.kind();
  1913. if (args.size() == 1 && args[0]->fType == type) {
  1914. // argument is already the right type, just return it
  1915. return std::move(args[0]);
  1916. }
  1917. if (type.isNumber()) {
  1918. return this->convertNumberConstructor(offset, type, std::move(args));
  1919. } else if (kind == Type::kArray_Kind) {
  1920. const Type& base = type.componentType();
  1921. for (size_t i = 0; i < args.size(); i++) {
  1922. args[i] = this->coerce(std::move(args[i]), base);
  1923. if (!args[i]) {
  1924. return nullptr;
  1925. }
  1926. }
  1927. return std::unique_ptr<Expression>(new Constructor(offset, type, std::move(args)));
  1928. } else if (kind == Type::kVector_Kind || kind == Type::kMatrix_Kind) {
  1929. return this->convertCompoundConstructor(offset, type, std::move(args));
  1930. } else {
  1931. fErrors.error(offset, "cannot construct '" + type.description() + "'");
  1932. return nullptr;
  1933. }
  1934. }
  1935. std::unique_ptr<Expression> IRGenerator::convertPrefixExpression(const ASTNode& expression) {
  1936. SkASSERT(expression.fKind == ASTNode::Kind::kPrefix);
  1937. std::unique_ptr<Expression> base = this->convertExpression(*expression.begin());
  1938. if (!base) {
  1939. return nullptr;
  1940. }
  1941. switch (expression.getToken().fKind) {
  1942. case Token::PLUS:
  1943. if (!base->fType.isNumber() && base->fType.kind() != Type::kVector_Kind &&
  1944. base->fType != *fContext.fFloatLiteral_Type) {
  1945. fErrors.error(expression.fOffset,
  1946. "'+' cannot operate on '" + base->fType.description() + "'");
  1947. return nullptr;
  1948. }
  1949. return base;
  1950. case Token::MINUS:
  1951. if (base->fKind == Expression::kIntLiteral_Kind) {
  1952. return std::unique_ptr<Expression>(new IntLiteral(fContext, base->fOffset,
  1953. -((IntLiteral&) *base).fValue));
  1954. }
  1955. if (base->fKind == Expression::kFloatLiteral_Kind) {
  1956. double value = -((FloatLiteral&) *base).fValue;
  1957. return std::unique_ptr<Expression>(new FloatLiteral(fContext, base->fOffset,
  1958. value));
  1959. }
  1960. if (!base->fType.isNumber() && base->fType.kind() != Type::kVector_Kind) {
  1961. fErrors.error(expression.fOffset,
  1962. "'-' cannot operate on '" + base->fType.description() + "'");
  1963. return nullptr;
  1964. }
  1965. return std::unique_ptr<Expression>(new PrefixExpression(Token::MINUS, std::move(base)));
  1966. case Token::PLUSPLUS:
  1967. if (!base->fType.isNumber()) {
  1968. fErrors.error(expression.fOffset,
  1969. String("'") + Compiler::OperatorName(expression.getToken().fKind) +
  1970. "' cannot operate on '" + base->fType.description() + "'");
  1971. return nullptr;
  1972. }
  1973. this->setRefKind(*base, VariableReference::kReadWrite_RefKind);
  1974. break;
  1975. case Token::MINUSMINUS:
  1976. if (!base->fType.isNumber()) {
  1977. fErrors.error(expression.fOffset,
  1978. String("'") + Compiler::OperatorName(expression.getToken().fKind) +
  1979. "' cannot operate on '" + base->fType.description() + "'");
  1980. return nullptr;
  1981. }
  1982. this->setRefKind(*base, VariableReference::kReadWrite_RefKind);
  1983. break;
  1984. case Token::LOGICALNOT:
  1985. if (base->fType != *fContext.fBool_Type) {
  1986. fErrors.error(expression.fOffset,
  1987. String("'") + Compiler::OperatorName(expression.getToken().fKind) +
  1988. "' cannot operate on '" + base->fType.description() + "'");
  1989. return nullptr;
  1990. }
  1991. if (base->fKind == Expression::kBoolLiteral_Kind) {
  1992. return std::unique_ptr<Expression>(new BoolLiteral(fContext, base->fOffset,
  1993. !((BoolLiteral&) *base).fValue));
  1994. }
  1995. break;
  1996. case Token::BITWISENOT:
  1997. if (base->fType != *fContext.fInt_Type) {
  1998. fErrors.error(expression.fOffset,
  1999. String("'") + Compiler::OperatorName(expression.getToken().fKind) +
  2000. "' cannot operate on '" + base->fType.description() + "'");
  2001. return nullptr;
  2002. }
  2003. break;
  2004. default:
  2005. ABORT("unsupported prefix operator\n");
  2006. }
  2007. return std::unique_ptr<Expression>(new PrefixExpression(expression.getToken().fKind,
  2008. std::move(base)));
  2009. }
  2010. std::unique_ptr<Expression> IRGenerator::convertIndex(std::unique_ptr<Expression> base,
  2011. const ASTNode& index) {
  2012. if (base->fKind == Expression::kTypeReference_Kind) {
  2013. if (index.fKind == ASTNode::Kind::kInt) {
  2014. const Type& oldType = ((TypeReference&) *base).fValue;
  2015. SKSL_INT size = index.getInt();
  2016. Type* newType = (Type*) fSymbolTable->takeOwnership(std::unique_ptr<Symbol>(
  2017. new Type(oldType.name() + "[" + to_string(size) + "]",
  2018. Type::kArray_Kind, oldType, size)));
  2019. return std::unique_ptr<Expression>(new TypeReference(fContext, base->fOffset,
  2020. *newType));
  2021. } else {
  2022. fErrors.error(base->fOffset, "array size must be a constant");
  2023. return nullptr;
  2024. }
  2025. }
  2026. if (base->fType.kind() != Type::kArray_Kind && base->fType.kind() != Type::kMatrix_Kind &&
  2027. base->fType.kind() != Type::kVector_Kind) {
  2028. fErrors.error(base->fOffset, "expected array, but found '" + base->fType.description() +
  2029. "'");
  2030. return nullptr;
  2031. }
  2032. std::unique_ptr<Expression> converted = this->convertExpression(index);
  2033. if (!converted) {
  2034. return nullptr;
  2035. }
  2036. if (converted->fType != *fContext.fUInt_Type) {
  2037. converted = this->coerce(std::move(converted), *fContext.fInt_Type);
  2038. if (!converted) {
  2039. return nullptr;
  2040. }
  2041. }
  2042. return std::unique_ptr<Expression>(new IndexExpression(fContext, std::move(base),
  2043. std::move(converted)));
  2044. }
  2045. std::unique_ptr<Expression> IRGenerator::convertField(std::unique_ptr<Expression> base,
  2046. StringFragment field) {
  2047. if (base->fKind == Expression::kExternalValue_Kind) {
  2048. ExternalValue& ev = *((ExternalValueReference&) *base).fValue;
  2049. ExternalValue* result = ev.getChild(String(field).c_str());
  2050. if (!result) {
  2051. fErrors.error(base->fOffset, "external value does not have a child named '" + field +
  2052. "'");
  2053. return nullptr;
  2054. }
  2055. return std::unique_ptr<Expression>(new ExternalValueReference(base->fOffset, result));
  2056. }
  2057. auto fields = base->fType.fields();
  2058. for (size_t i = 0; i < fields.size(); i++) {
  2059. if (fields[i].fName == field) {
  2060. return std::unique_ptr<Expression>(new FieldAccess(std::move(base), (int) i));
  2061. }
  2062. }
  2063. fErrors.error(base->fOffset, "type '" + base->fType.description() + "' does not have a "
  2064. "field named '" + field + "");
  2065. return nullptr;
  2066. }
  2067. std::unique_ptr<Expression> IRGenerator::convertSwizzle(std::unique_ptr<Expression> base,
  2068. StringFragment fields) {
  2069. if (base->fType.kind() != Type::kVector_Kind) {
  2070. fErrors.error(base->fOffset, "cannot swizzle type '" + base->fType.description() + "'");
  2071. return nullptr;
  2072. }
  2073. std::vector<int> swizzleComponents;
  2074. for (size_t i = 0; i < fields.fLength; i++) {
  2075. switch (fields[i]) {
  2076. case '0':
  2077. if (i != fields.fLength - 1) {
  2078. fErrors.error(base->fOffset,
  2079. "only the last swizzle component can be a constant");
  2080. }
  2081. swizzleComponents.push_back(SKSL_SWIZZLE_0);
  2082. break;
  2083. case '1':
  2084. if (i != fields.fLength - 1) {
  2085. fErrors.error(base->fOffset,
  2086. "only the last swizzle component can be a constant");
  2087. }
  2088. swizzleComponents.push_back(SKSL_SWIZZLE_1);
  2089. break;
  2090. case 'x': // fall through
  2091. case 'r': // fall through
  2092. case 's':
  2093. swizzleComponents.push_back(0);
  2094. break;
  2095. case 'y': // fall through
  2096. case 'g': // fall through
  2097. case 't':
  2098. if (base->fType.columns() >= 2) {
  2099. swizzleComponents.push_back(1);
  2100. break;
  2101. }
  2102. // fall through
  2103. case 'z': // fall through
  2104. case 'b': // fall through
  2105. case 'p':
  2106. if (base->fType.columns() >= 3) {
  2107. swizzleComponents.push_back(2);
  2108. break;
  2109. }
  2110. // fall through
  2111. case 'w': // fall through
  2112. case 'a': // fall through
  2113. case 'q':
  2114. if (base->fType.columns() >= 4) {
  2115. swizzleComponents.push_back(3);
  2116. break;
  2117. }
  2118. // fall through
  2119. default:
  2120. fErrors.error(base->fOffset, String::printf("invalid swizzle component '%c'",
  2121. fields[i]));
  2122. return nullptr;
  2123. }
  2124. }
  2125. SkASSERT(swizzleComponents.size() > 0);
  2126. if (swizzleComponents.size() > 4) {
  2127. fErrors.error(base->fOffset, "too many components in swizzle mask '" + fields + "'");
  2128. return nullptr;
  2129. }
  2130. return std::unique_ptr<Expression>(new Swizzle(fContext, std::move(base), swizzleComponents));
  2131. }
  2132. std::unique_ptr<Expression> IRGenerator::getCap(int offset, String name) {
  2133. auto found = fCapsMap.find(name);
  2134. if (found == fCapsMap.end()) {
  2135. fErrors.error(offset, "unknown capability flag '" + name + "'");
  2136. return nullptr;
  2137. }
  2138. String fullName = "sk_Caps." + name;
  2139. return std::unique_ptr<Expression>(new Setting(offset, fullName,
  2140. found->second.literal(fContext, offset)));
  2141. }
  2142. std::unique_ptr<Expression> IRGenerator::getArg(int offset, String name) const {
  2143. auto found = fSettings->fArgs.find(name);
  2144. if (found == fSettings->fArgs.end()) {
  2145. return nullptr;
  2146. }
  2147. String fullName = "sk_Args." + name;
  2148. return std::unique_ptr<Expression>(new Setting(offset,
  2149. fullName,
  2150. found->second.literal(fContext, offset)));
  2151. }
  2152. std::unique_ptr<Expression> IRGenerator::convertTypeField(int offset, const Type& type,
  2153. StringFragment field) {
  2154. std::unique_ptr<Expression> result;
  2155. for (const auto& e : *fProgramElements) {
  2156. if (e->fKind == ProgramElement::kEnum_Kind && type.name() == ((Enum&) *e).fTypeName) {
  2157. std::shared_ptr<SymbolTable> old = fSymbolTable;
  2158. fSymbolTable = ((Enum&) *e).fSymbols;
  2159. result = convertIdentifier(ASTNode(&fFile->fNodes, offset, ASTNode::Kind::kIdentifier,
  2160. field));
  2161. fSymbolTable = old;
  2162. }
  2163. }
  2164. if (!result) {
  2165. fErrors.error(offset, "type '" + type.fName + "' does not have a field named '" + field +
  2166. "'");
  2167. }
  2168. return result;
  2169. }
  2170. std::unique_ptr<Expression> IRGenerator::convertAppend(int offset,
  2171. const std::vector<ASTNode>& args) {
  2172. #ifndef SKSL_STANDALONE
  2173. if (args.size() < 2) {
  2174. fErrors.error(offset, "'append' requires at least two arguments");
  2175. return nullptr;
  2176. }
  2177. std::unique_ptr<Expression> pipeline = this->convertExpression(args[0]);
  2178. if (!pipeline) {
  2179. return nullptr;
  2180. }
  2181. if (pipeline->fType != *fContext.fSkRasterPipeline_Type) {
  2182. fErrors.error(offset, "first argument of 'append' must have type 'SkRasterPipeline'");
  2183. return nullptr;
  2184. }
  2185. if (ASTNode::Kind::kIdentifier != args[1].fKind) {
  2186. fErrors.error(offset, "'" + args[1].description() + "' is not a valid stage");
  2187. return nullptr;
  2188. }
  2189. StringFragment name = args[1].getString();
  2190. SkRasterPipeline::StockStage stage = SkRasterPipeline::premul;
  2191. std::vector<std::unique_ptr<Expression>> stageArgs;
  2192. stageArgs.push_back(std::move(pipeline));
  2193. for (size_t i = 2; i < args.size(); ++i) {
  2194. std::unique_ptr<Expression> arg = this->convertExpression(args[i]);
  2195. if (!arg) {
  2196. return nullptr;
  2197. }
  2198. stageArgs.push_back(std::move(arg));
  2199. }
  2200. size_t expectedArgs = 0;
  2201. // FIXME use a map
  2202. if ("premul" == name) {
  2203. stage = SkRasterPipeline::premul;
  2204. }
  2205. else if ("unpremul" == name) {
  2206. stage = SkRasterPipeline::unpremul;
  2207. }
  2208. else if ("clamp_0" == name) {
  2209. stage = SkRasterPipeline::clamp_0;
  2210. }
  2211. else if ("clamp_1" == name) {
  2212. stage = SkRasterPipeline::clamp_1;
  2213. }
  2214. else if ("matrix_4x5" == name) {
  2215. expectedArgs = 1;
  2216. stage = SkRasterPipeline::matrix_4x5;
  2217. if (1 == stageArgs.size() && stageArgs[0]->fType.fName != "float[20]") {
  2218. fErrors.error(offset, "pipeline stage '" + name + "' expected a float[20] argument");
  2219. return nullptr;
  2220. }
  2221. }
  2222. else {
  2223. bool found = false;
  2224. for (const auto& e : *fProgramElements) {
  2225. if (ProgramElement::kFunction_Kind == e->fKind) {
  2226. const FunctionDefinition& f = (const FunctionDefinition&) *e;
  2227. if (f.fDeclaration.fName == name) {
  2228. stage = SkRasterPipeline::callback;
  2229. std::vector<const FunctionDeclaration*> functions = { &f.fDeclaration };
  2230. stageArgs.emplace_back(new FunctionReference(fContext, offset, functions));
  2231. found = true;
  2232. break;
  2233. }
  2234. }
  2235. }
  2236. if (!found) {
  2237. fErrors.error(offset, "'" + name + "' is not a valid pipeline stage");
  2238. return nullptr;
  2239. }
  2240. }
  2241. if (args.size() != expectedArgs + 2) {
  2242. fErrors.error(offset, "pipeline stage '" + name + "' expected an additional argument " +
  2243. "count of " + to_string((int) expectedArgs) + ", but found " +
  2244. to_string((int) args.size() - 1));
  2245. return nullptr;
  2246. }
  2247. return std::unique_ptr<Expression>(new AppendStage(fContext, offset, stage,
  2248. std::move(stageArgs)));
  2249. #else
  2250. SkASSERT(false);
  2251. return nullptr;
  2252. #endif
  2253. }
  2254. std::unique_ptr<Expression> IRGenerator::convertIndexExpression(const ASTNode& index) {
  2255. SkASSERT(index.fKind == ASTNode::Kind::kIndex);
  2256. auto iter = index.begin();
  2257. std::unique_ptr<Expression> base = this->convertExpression(*(iter++));
  2258. if (!base) {
  2259. return nullptr;
  2260. }
  2261. if (iter != index.end()) {
  2262. return this->convertIndex(std::move(base), *(iter++));
  2263. } else if (base->fKind == Expression::kTypeReference_Kind) {
  2264. const Type& oldType = ((TypeReference&) *base).fValue;
  2265. Type* newType = (Type*) fSymbolTable->takeOwnership(std::unique_ptr<Symbol>(
  2266. new Type(oldType.name() + "[]",
  2267. Type::kArray_Kind,
  2268. oldType,
  2269. -1)));
  2270. return std::unique_ptr<Expression>(new TypeReference(fContext, base->fOffset,
  2271. *newType));
  2272. }
  2273. fErrors.error(index.fOffset, "'[]' must follow a type name");
  2274. return nullptr;
  2275. }
  2276. std::unique_ptr<Expression> IRGenerator::convertCallExpression(const ASTNode& callNode) {
  2277. SkASSERT(callNode.fKind == ASTNode::Kind::kCall);
  2278. auto iter = callNode.begin();
  2279. std::unique_ptr<Expression> base = this->convertExpression(*(iter++));
  2280. if (!base) {
  2281. return nullptr;
  2282. }
  2283. std::vector<std::unique_ptr<Expression>> arguments;
  2284. for (; iter != callNode.end(); ++iter) {
  2285. std::unique_ptr<Expression> converted = this->convertExpression(*iter);
  2286. if (!converted) {
  2287. return nullptr;
  2288. }
  2289. arguments.push_back(std::move(converted));
  2290. }
  2291. return this->call(callNode.fOffset, std::move(base), std::move(arguments));
  2292. }
  2293. std::unique_ptr<Expression> IRGenerator::convertFieldExpression(const ASTNode& fieldNode) {
  2294. std::unique_ptr<Expression> base = this->convertExpression(*fieldNode.begin());
  2295. if (!base) {
  2296. return nullptr;
  2297. }
  2298. StringFragment field = fieldNode.getString();
  2299. if (base->fType == *fContext.fSkCaps_Type) {
  2300. return this->getCap(fieldNode.fOffset, field);
  2301. }
  2302. if (base->fType == *fContext.fSkArgs_Type) {
  2303. return this->getArg(fieldNode.fOffset, field);
  2304. }
  2305. if (base->fKind == Expression::kTypeReference_Kind) {
  2306. return this->convertTypeField(base->fOffset, ((TypeReference&) *base).fValue,
  2307. field);
  2308. }
  2309. if (base->fKind == Expression::kExternalValue_Kind) {
  2310. return this->convertField(std::move(base), field);
  2311. }
  2312. switch (base->fType.kind()) {
  2313. case Type::kVector_Kind:
  2314. return this->convertSwizzle(std::move(base), field);
  2315. case Type::kOther_Kind:
  2316. case Type::kStruct_Kind:
  2317. return this->convertField(std::move(base), field);
  2318. default:
  2319. fErrors.error(base->fOffset, "cannot swizzle value of type '" +
  2320. base->fType.description() + "'");
  2321. return nullptr;
  2322. }
  2323. }
  2324. std::unique_ptr<Expression> IRGenerator::convertPostfixExpression(const ASTNode& expression) {
  2325. std::unique_ptr<Expression> base = this->convertExpression(*expression.begin());
  2326. if (!base) {
  2327. return nullptr;
  2328. }
  2329. if (!base->fType.isNumber()) {
  2330. fErrors.error(expression.fOffset,
  2331. "'" + String(Compiler::OperatorName(expression.getToken().fKind)) +
  2332. "' cannot operate on '" + base->fType.description() + "'");
  2333. return nullptr;
  2334. }
  2335. this->setRefKind(*base, VariableReference::kReadWrite_RefKind);
  2336. return std::unique_ptr<Expression>(new PostfixExpression(std::move(base),
  2337. expression.getToken().fKind));
  2338. }
  2339. void IRGenerator::checkValid(const Expression& expr) {
  2340. switch (expr.fKind) {
  2341. case Expression::kFunctionReference_Kind:
  2342. fErrors.error(expr.fOffset, "expected '(' to begin function call");
  2343. break;
  2344. case Expression::kTypeReference_Kind:
  2345. fErrors.error(expr.fOffset, "expected '(' to begin constructor invocation");
  2346. break;
  2347. default:
  2348. if (expr.fType == *fContext.fInvalid_Type) {
  2349. fErrors.error(expr.fOffset, "invalid expression");
  2350. }
  2351. }
  2352. }
  2353. bool IRGenerator::checkSwizzleWrite(const Swizzle& swizzle) {
  2354. int bits = 0;
  2355. for (int idx : swizzle.fComponents) {
  2356. if (idx < 0) {
  2357. fErrors.error(swizzle.fOffset, "cannot write to a swizzle mask containing a constant");
  2358. return false;
  2359. }
  2360. SkASSERT(idx <= 3);
  2361. int bit = 1 << idx;
  2362. if (bits & bit) {
  2363. fErrors.error(swizzle.fOffset,
  2364. "cannot write to the same swizzle field more than once");
  2365. return false;
  2366. }
  2367. bits |= bit;
  2368. }
  2369. return true;
  2370. }
  2371. void IRGenerator::setRefKind(const Expression& expr, VariableReference::RefKind kind) {
  2372. switch (expr.fKind) {
  2373. case Expression::kVariableReference_Kind: {
  2374. const Variable& var = ((VariableReference&) expr).fVariable;
  2375. if (var.fModifiers.fFlags & (Modifiers::kConst_Flag | Modifiers::kUniform_Flag)) {
  2376. fErrors.error(expr.fOffset,
  2377. "cannot modify immutable variable '" + var.fName + "'");
  2378. }
  2379. ((VariableReference&) expr).setRefKind(kind);
  2380. break;
  2381. }
  2382. case Expression::kFieldAccess_Kind:
  2383. this->setRefKind(*((FieldAccess&) expr).fBase, kind);
  2384. break;
  2385. case Expression::kSwizzle_Kind: {
  2386. const Swizzle& swizzle = (Swizzle&) expr;
  2387. this->checkSwizzleWrite(swizzle);
  2388. this->setRefKind(*swizzle.fBase, kind);
  2389. break;
  2390. }
  2391. case Expression::kIndex_Kind:
  2392. this->setRefKind(*((IndexExpression&) expr).fBase, kind);
  2393. break;
  2394. case Expression::kTernary_Kind: {
  2395. TernaryExpression& t = (TernaryExpression&) expr;
  2396. this->setRefKind(*t.fIfTrue, kind);
  2397. this->setRefKind(*t.fIfFalse, kind);
  2398. break;
  2399. }
  2400. case Expression::kExternalValue_Kind: {
  2401. const ExternalValue& v = *((ExternalValueReference&) expr).fValue;
  2402. if (!v.canWrite()) {
  2403. fErrors.error(expr.fOffset,
  2404. "cannot modify immutable external value '" + v.fName + "'");
  2405. }
  2406. break;
  2407. }
  2408. default:
  2409. fErrors.error(expr.fOffset, "cannot assign to '" + expr.description() + "'");
  2410. break;
  2411. }
  2412. }
  2413. void IRGenerator::convertProgram(Program::Kind kind,
  2414. const char* text,
  2415. size_t length,
  2416. SymbolTable& types,
  2417. std::vector<std::unique_ptr<ProgramElement>>* out) {
  2418. fKind = kind;
  2419. fProgramElements = out;
  2420. Parser parser(text, length, types, fErrors);
  2421. fFile = parser.file();
  2422. if (fErrors.errorCount()) {
  2423. return;
  2424. }
  2425. SkASSERT(fFile);
  2426. for (const auto& decl : fFile->root()) {
  2427. switch (decl.fKind) {
  2428. case ASTNode::Kind::kVarDeclarations: {
  2429. std::unique_ptr<VarDeclarations> s = this->convertVarDeclarations(
  2430. decl,
  2431. Variable::kGlobal_Storage);
  2432. if (s) {
  2433. fProgramElements->push_back(std::move(s));
  2434. }
  2435. break;
  2436. }
  2437. case ASTNode::Kind::kEnum: {
  2438. this->convertEnum(decl);
  2439. break;
  2440. }
  2441. case ASTNode::Kind::kFunction: {
  2442. this->convertFunction(decl);
  2443. break;
  2444. }
  2445. case ASTNode::Kind::kModifiers: {
  2446. std::unique_ptr<ModifiersDeclaration> f = this->convertModifiersDeclaration(decl);
  2447. if (f) {
  2448. fProgramElements->push_back(std::move(f));
  2449. }
  2450. break;
  2451. }
  2452. case ASTNode::Kind::kInterfaceBlock: {
  2453. std::unique_ptr<InterfaceBlock> i = this->convertInterfaceBlock(decl);
  2454. if (i) {
  2455. fProgramElements->push_back(std::move(i));
  2456. }
  2457. break;
  2458. }
  2459. case ASTNode::Kind::kExtension: {
  2460. std::unique_ptr<Extension> e = this->convertExtension(decl.fOffset,
  2461. decl.getString());
  2462. if (e) {
  2463. fProgramElements->push_back(std::move(e));
  2464. }
  2465. break;
  2466. }
  2467. case ASTNode::Kind::kSection: {
  2468. std::unique_ptr<Section> s = this->convertSection(decl);
  2469. if (s) {
  2470. fProgramElements->push_back(std::move(s));
  2471. }
  2472. break;
  2473. }
  2474. default:
  2475. ABORT("unsupported declaration: %s\n", decl.description().c_str());
  2476. }
  2477. }
  2478. }
  2479. }