SpvBuilder.h 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. //
  2. // Copyright (C) 2014-2015 LunarG, Inc.
  3. // Copyright (C) 2015-2020 Google, Inc.
  4. // Copyright (C) 2017 ARM Limited.
  5. // Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
  6. //
  7. // All rights reserved.
  8. //
  9. // Redistribution and use in source and binary forms, with or without
  10. // modification, are permitted provided that the following conditions
  11. // are met:
  12. //
  13. // Redistributions of source code must retain the above copyright
  14. // notice, this list of conditions and the following disclaimer.
  15. //
  16. // Redistributions in binary form must reproduce the above
  17. // copyright notice, this list of conditions and the following
  18. // disclaimer in the documentation and/or other materials provided
  19. // with the distribution.
  20. //
  21. // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
  22. // contributors may be used to endorse or promote products derived
  23. // from this software without specific prior written permission.
  24. //
  25. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  26. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  27. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  28. // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  29. // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  30. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  31. // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  32. // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  33. // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  34. // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  35. // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  36. // POSSIBILITY OF SUCH DAMAGE.
  37. //
  38. // "Builder" is an interface to fully build SPIR-V IR. Allocate one of
  39. // these to build (a thread safe) internal SPIR-V representation (IR),
  40. // and then dump it as a binary stream according to the SPIR-V specification.
  41. //
  42. // A Builder has a 1:1 relationship with a SPIR-V module.
  43. //
  44. #pragma once
  45. #ifndef SpvBuilder_H
  46. #define SpvBuilder_H
  47. #include "Logger.h"
  48. #include "spirv.hpp"
  49. #include "spvIR.h"
  50. #include <algorithm>
  51. #include <map>
  52. #include <memory>
  53. #include <set>
  54. #include <sstream>
  55. #include <stack>
  56. #include <unordered_map>
  57. #include <map>
  58. namespace spv {
  59. typedef enum {
  60. Spv_1_0 = (1 << 16),
  61. Spv_1_1 = (1 << 16) | (1 << 8),
  62. Spv_1_2 = (1 << 16) | (2 << 8),
  63. Spv_1_3 = (1 << 16) | (3 << 8),
  64. Spv_1_4 = (1 << 16) | (4 << 8),
  65. Spv_1_5 = (1 << 16) | (5 << 8),
  66. } SpvVersion;
  67. class Builder {
  68. public:
  69. Builder(unsigned int spvVersion, unsigned int userNumber, SpvBuildLogger* logger);
  70. virtual ~Builder();
  71. static const int maxMatrixSize = 4;
  72. unsigned int getSpvVersion() const { return spvVersion; }
  73. void setSource(spv::SourceLanguage lang, int version)
  74. {
  75. source = lang;
  76. sourceVersion = version;
  77. }
  78. spv::Id getStringId(const std::string& str)
  79. {
  80. auto sItr = stringIds.find(str);
  81. if (sItr != stringIds.end())
  82. return sItr->second;
  83. spv::Id strId = getUniqueId();
  84. Instruction* fileString = new Instruction(strId, NoType, OpString);
  85. const char* file_c_str = str.c_str();
  86. fileString->addStringOperand(file_c_str);
  87. strings.push_back(std::unique_ptr<Instruction>(fileString));
  88. module.mapInstruction(fileString);
  89. stringIds[file_c_str] = strId;
  90. return strId;
  91. }
  92. void setSourceFile(const std::string& file)
  93. {
  94. sourceFileStringId = getStringId(file);
  95. }
  96. void setSourceText(const std::string& text) { sourceText = text; }
  97. void addSourceExtension(const char* ext) { sourceExtensions.push_back(ext); }
  98. void addModuleProcessed(const std::string& p) { moduleProcesses.push_back(p.c_str()); }
  99. void setEmitOpLines() { emitOpLines = true; }
  100. void addExtension(const char* ext) { extensions.insert(ext); }
  101. void removeExtension(const char* ext)
  102. {
  103. extensions.erase(ext);
  104. }
  105. void addIncorporatedExtension(const char* ext, SpvVersion incorporatedVersion)
  106. {
  107. if (getSpvVersion() < static_cast<unsigned>(incorporatedVersion))
  108. addExtension(ext);
  109. }
  110. void promoteIncorporatedExtension(const char* baseExt, const char* promoExt, SpvVersion incorporatedVersion)
  111. {
  112. removeExtension(baseExt);
  113. addIncorporatedExtension(promoExt, incorporatedVersion);
  114. }
  115. void addInclude(const std::string& name, const std::string& text)
  116. {
  117. spv::Id incId = getStringId(name);
  118. includeFiles[incId] = &text;
  119. }
  120. Id import(const char*);
  121. void setMemoryModel(spv::AddressingModel addr, spv::MemoryModel mem)
  122. {
  123. addressModel = addr;
  124. memoryModel = mem;
  125. }
  126. void addCapability(spv::Capability cap) { capabilities.insert(cap); }
  127. // To get a new <id> for anything needing a new one.
  128. Id getUniqueId() { return ++uniqueId; }
  129. // To get a set of new <id>s, e.g., for a set of function parameters
  130. Id getUniqueIds(int numIds)
  131. {
  132. Id id = uniqueId + 1;
  133. uniqueId += numIds;
  134. return id;
  135. }
  136. // Generate OpLine for non-filename-based #line directives (ie no filename
  137. // seen yet): Log the current line, and if different than the last one,
  138. // issue a new OpLine using the new line and current source file name.
  139. void setLine(int line);
  140. // If filename null, generate OpLine for non-filename-based line directives,
  141. // else do filename-based: Log the current line and file, and if different
  142. // than the last one, issue a new OpLine using the new line and file
  143. // name.
  144. void setLine(int line, const char* filename);
  145. // Low-level OpLine. See setLine() for a layered helper.
  146. void addLine(Id fileName, int line, int column);
  147. // For creating new types (will return old type if the requested one was already made).
  148. Id makeVoidType();
  149. Id makeBoolType();
  150. Id makePointer(StorageClass, Id pointee);
  151. Id makeForwardPointer(StorageClass);
  152. Id makePointerFromForwardPointer(StorageClass, Id forwardPointerType, Id pointee);
  153. Id makeIntegerType(int width, bool hasSign); // generic
  154. Id makeIntType(int width) { return makeIntegerType(width, true); }
  155. Id makeUintType(int width) { return makeIntegerType(width, false); }
  156. Id makeFloatType(int width);
  157. Id makeStructType(const std::vector<Id>& members, const char*);
  158. Id makeStructResultType(Id type0, Id type1);
  159. Id makeVectorType(Id component, int size);
  160. Id makeMatrixType(Id component, int cols, int rows);
  161. Id makeArrayType(Id element, Id sizeId, int stride); // 0 stride means no stride decoration
  162. Id makeRuntimeArray(Id element);
  163. Id makeFunctionType(Id returnType, const std::vector<Id>& paramTypes);
  164. Id makeImageType(Id sampledType, Dim, bool depth, bool arrayed, bool ms, unsigned sampled, ImageFormat format);
  165. Id makeSamplerType();
  166. Id makeSampledImageType(Id imageType);
  167. Id makeCooperativeMatrixType(Id component, Id scope, Id rows, Id cols);
  168. // accelerationStructureNV type
  169. Id makeAccelerationStructureType();
  170. // rayQueryEXT type
  171. Id makeRayQueryType();
  172. // For querying about types.
  173. Id getTypeId(Id resultId) const { return module.getTypeId(resultId); }
  174. Id getDerefTypeId(Id resultId) const;
  175. Op getOpCode(Id id) const { return module.getInstruction(id)->getOpCode(); }
  176. Op getTypeClass(Id typeId) const { return getOpCode(typeId); }
  177. Op getMostBasicTypeClass(Id typeId) const;
  178. int getNumComponents(Id resultId) const { return getNumTypeComponents(getTypeId(resultId)); }
  179. int getNumTypeConstituents(Id typeId) const;
  180. int getNumTypeComponents(Id typeId) const { return getNumTypeConstituents(typeId); }
  181. Id getScalarTypeId(Id typeId) const;
  182. Id getContainedTypeId(Id typeId) const;
  183. Id getContainedTypeId(Id typeId, int) const;
  184. StorageClass getTypeStorageClass(Id typeId) const { return module.getStorageClass(typeId); }
  185. ImageFormat getImageTypeFormat(Id typeId) const
  186. { return (ImageFormat)module.getInstruction(typeId)->getImmediateOperand(6); }
  187. bool isPointer(Id resultId) const { return isPointerType(getTypeId(resultId)); }
  188. bool isScalar(Id resultId) const { return isScalarType(getTypeId(resultId)); }
  189. bool isVector(Id resultId) const { return isVectorType(getTypeId(resultId)); }
  190. bool isMatrix(Id resultId) const { return isMatrixType(getTypeId(resultId)); }
  191. bool isCooperativeMatrix(Id resultId)const { return isCooperativeMatrixType(getTypeId(resultId)); }
  192. bool isAggregate(Id resultId) const { return isAggregateType(getTypeId(resultId)); }
  193. bool isSampledImage(Id resultId) const { return isSampledImageType(getTypeId(resultId)); }
  194. bool isBoolType(Id typeId)
  195. { return groupedTypes[OpTypeBool].size() > 0 && typeId == groupedTypes[OpTypeBool].back()->getResultId(); }
  196. bool isIntType(Id typeId) const
  197. { return getTypeClass(typeId) == OpTypeInt && module.getInstruction(typeId)->getImmediateOperand(1) != 0; }
  198. bool isUintType(Id typeId) const
  199. { return getTypeClass(typeId) == OpTypeInt && module.getInstruction(typeId)->getImmediateOperand(1) == 0; }
  200. bool isFloatType(Id typeId) const { return getTypeClass(typeId) == OpTypeFloat; }
  201. bool isPointerType(Id typeId) const { return getTypeClass(typeId) == OpTypePointer; }
  202. bool isScalarType(Id typeId) const
  203. { return getTypeClass(typeId) == OpTypeFloat || getTypeClass(typeId) == OpTypeInt ||
  204. getTypeClass(typeId) == OpTypeBool; }
  205. bool isVectorType(Id typeId) const { return getTypeClass(typeId) == OpTypeVector; }
  206. bool isMatrixType(Id typeId) const { return getTypeClass(typeId) == OpTypeMatrix; }
  207. bool isStructType(Id typeId) const { return getTypeClass(typeId) == OpTypeStruct; }
  208. bool isArrayType(Id typeId) const { return getTypeClass(typeId) == OpTypeArray; }
  209. #ifdef GLSLANG_WEB
  210. bool isCooperativeMatrixType(Id typeId)const { return false; }
  211. #else
  212. bool isCooperativeMatrixType(Id typeId)const { return getTypeClass(typeId) == OpTypeCooperativeMatrixNV; }
  213. #endif
  214. bool isAggregateType(Id typeId) const
  215. { return isArrayType(typeId) || isStructType(typeId) || isCooperativeMatrixType(typeId); }
  216. bool isImageType(Id typeId) const { return getTypeClass(typeId) == OpTypeImage; }
  217. bool isSamplerType(Id typeId) const { return getTypeClass(typeId) == OpTypeSampler; }
  218. bool isSampledImageType(Id typeId) const { return getTypeClass(typeId) == OpTypeSampledImage; }
  219. bool containsType(Id typeId, Op typeOp, unsigned int width) const;
  220. bool containsPhysicalStorageBufferOrArray(Id typeId) const;
  221. bool isConstantOpCode(Op opcode) const;
  222. bool isSpecConstantOpCode(Op opcode) const;
  223. bool isConstant(Id resultId) const { return isConstantOpCode(getOpCode(resultId)); }
  224. bool isConstantScalar(Id resultId) const { return getOpCode(resultId) == OpConstant; }
  225. bool isSpecConstant(Id resultId) const { return isSpecConstantOpCode(getOpCode(resultId)); }
  226. unsigned int getConstantScalar(Id resultId) const
  227. { return module.getInstruction(resultId)->getImmediateOperand(0); }
  228. StorageClass getStorageClass(Id resultId) const { return getTypeStorageClass(getTypeId(resultId)); }
  229. bool isVariableOpCode(Op opcode) const { return opcode == OpVariable; }
  230. bool isVariable(Id resultId) const { return isVariableOpCode(getOpCode(resultId)); }
  231. bool isGlobalStorage(Id resultId) const { return getStorageClass(resultId) != StorageClassFunction; }
  232. bool isGlobalVariable(Id resultId) const { return isVariable(resultId) && isGlobalStorage(resultId); }
  233. // See if a resultId is valid for use as an initializer.
  234. bool isValidInitializer(Id resultId) const { return isConstant(resultId) || isGlobalVariable(resultId); }
  235. int getScalarTypeWidth(Id typeId) const
  236. {
  237. Id scalarTypeId = getScalarTypeId(typeId);
  238. assert(getTypeClass(scalarTypeId) == OpTypeInt || getTypeClass(scalarTypeId) == OpTypeFloat);
  239. return module.getInstruction(scalarTypeId)->getImmediateOperand(0);
  240. }
  241. int getTypeNumColumns(Id typeId) const
  242. {
  243. assert(isMatrixType(typeId));
  244. return getNumTypeConstituents(typeId);
  245. }
  246. int getNumColumns(Id resultId) const { return getTypeNumColumns(getTypeId(resultId)); }
  247. int getTypeNumRows(Id typeId) const
  248. {
  249. assert(isMatrixType(typeId));
  250. return getNumTypeComponents(getContainedTypeId(typeId));
  251. }
  252. int getNumRows(Id resultId) const { return getTypeNumRows(getTypeId(resultId)); }
  253. Dim getTypeDimensionality(Id typeId) const
  254. {
  255. assert(isImageType(typeId));
  256. return (Dim)module.getInstruction(typeId)->getImmediateOperand(1);
  257. }
  258. Id getImageType(Id resultId) const
  259. {
  260. Id typeId = getTypeId(resultId);
  261. assert(isImageType(typeId) || isSampledImageType(typeId));
  262. return isSampledImageType(typeId) ? module.getInstruction(typeId)->getIdOperand(0) : typeId;
  263. }
  264. bool isArrayedImageType(Id typeId) const
  265. {
  266. assert(isImageType(typeId));
  267. return module.getInstruction(typeId)->getImmediateOperand(3) != 0;
  268. }
  269. // For making new constants (will return old constant if the requested one was already made).
  270. Id makeBoolConstant(bool b, bool specConstant = false);
  271. Id makeInt8Constant(int i, bool specConstant = false)
  272. { return makeIntConstant(makeIntType(8), (unsigned)i, specConstant); }
  273. Id makeUint8Constant(unsigned u, bool specConstant = false)
  274. { return makeIntConstant(makeUintType(8), u, specConstant); }
  275. Id makeInt16Constant(int i, bool specConstant = false)
  276. { return makeIntConstant(makeIntType(16), (unsigned)i, specConstant); }
  277. Id makeUint16Constant(unsigned u, bool specConstant = false)
  278. { return makeIntConstant(makeUintType(16), u, specConstant); }
  279. Id makeIntConstant(int i, bool specConstant = false)
  280. { return makeIntConstant(makeIntType(32), (unsigned)i, specConstant); }
  281. Id makeUintConstant(unsigned u, bool specConstant = false)
  282. { return makeIntConstant(makeUintType(32), u, specConstant); }
  283. Id makeInt64Constant(long long i, bool specConstant = false)
  284. { return makeInt64Constant(makeIntType(64), (unsigned long long)i, specConstant); }
  285. Id makeUint64Constant(unsigned long long u, bool specConstant = false)
  286. { return makeInt64Constant(makeUintType(64), u, specConstant); }
  287. Id makeFloatConstant(float f, bool specConstant = false);
  288. Id makeDoubleConstant(double d, bool specConstant = false);
  289. Id makeFloat16Constant(float f16, bool specConstant = false);
  290. Id makeFpConstant(Id type, double d, bool specConstant = false);
  291. // Turn the array of constants into a proper spv constant of the requested type.
  292. Id makeCompositeConstant(Id type, const std::vector<Id>& comps, bool specConst = false);
  293. // Methods for adding information outside the CFG.
  294. Instruction* addEntryPoint(ExecutionModel, Function*, const char* name);
  295. void addExecutionMode(Function*, ExecutionMode mode, int value1 = -1, int value2 = -1, int value3 = -1);
  296. void addName(Id, const char* name);
  297. void addMemberName(Id, int member, const char* name);
  298. void addDecoration(Id, Decoration, int num = -1);
  299. void addDecoration(Id, Decoration, const char*);
  300. void addDecorationId(Id id, Decoration, Id idDecoration);
  301. void addMemberDecoration(Id, unsigned int member, Decoration, int num = -1);
  302. void addMemberDecoration(Id, unsigned int member, Decoration, const char*);
  303. // At the end of what block do the next create*() instructions go?
  304. void setBuildPoint(Block* bp) { buildPoint = bp; }
  305. Block* getBuildPoint() const { return buildPoint; }
  306. // Make the entry-point function. The returned pointer is only valid
  307. // for the lifetime of this builder.
  308. Function* makeEntryPoint(const char*);
  309. // Make a shader-style function, and create its entry block if entry is non-zero.
  310. // Return the function, pass back the entry.
  311. // The returned pointer is only valid for the lifetime of this builder.
  312. Function* makeFunctionEntry(Decoration precision, Id returnType, const char* name,
  313. const std::vector<Id>& paramTypes, const std::vector<std::vector<Decoration>>& precisions, Block **entry = 0);
  314. // Create a return. An 'implicit' return is one not appearing in the source
  315. // code. In the case of an implicit return, no post-return block is inserted.
  316. void makeReturn(bool implicit, Id retVal = 0);
  317. // Generate all the code needed to finish up a function.
  318. void leaveFunction();
  319. // Create a discard.
  320. void makeDiscard();
  321. // Create a global or function local or IO variable.
  322. Id createVariable(Decoration precision, StorageClass, Id type, const char* name = nullptr,
  323. Id initializer = NoResult);
  324. // Create an intermediate with an undefined value.
  325. Id createUndefined(Id type);
  326. // Store into an Id and return the l-value
  327. void createStore(Id rValue, Id lValue, spv::MemoryAccessMask memoryAccess = spv::MemoryAccessMaskNone,
  328. spv::Scope scope = spv::ScopeMax, unsigned int alignment = 0);
  329. // Load from an Id and return it
  330. Id createLoad(Id lValue, spv::Decoration precision,
  331. spv::MemoryAccessMask memoryAccess = spv::MemoryAccessMaskNone,
  332. spv::Scope scope = spv::ScopeMax, unsigned int alignment = 0);
  333. // Create an OpAccessChain instruction
  334. Id createAccessChain(StorageClass, Id base, const std::vector<Id>& offsets);
  335. // Create an OpArrayLength instruction
  336. Id createArrayLength(Id base, unsigned int member);
  337. // Create an OpCooperativeMatrixLengthNV instruction
  338. Id createCooperativeMatrixLength(Id type);
  339. // Create an OpCompositeExtract instruction
  340. Id createCompositeExtract(Id composite, Id typeId, unsigned index);
  341. Id createCompositeExtract(Id composite, Id typeId, const std::vector<unsigned>& indexes);
  342. Id createCompositeInsert(Id object, Id composite, Id typeId, unsigned index);
  343. Id createCompositeInsert(Id object, Id composite, Id typeId, const std::vector<unsigned>& indexes);
  344. Id createVectorExtractDynamic(Id vector, Id typeId, Id componentIndex);
  345. Id createVectorInsertDynamic(Id vector, Id typeId, Id component, Id componentIndex);
  346. void createNoResultOp(Op);
  347. void createNoResultOp(Op, Id operand);
  348. void createNoResultOp(Op, const std::vector<Id>& operands);
  349. void createNoResultOp(Op, const std::vector<IdImmediate>& operands);
  350. void createControlBarrier(Scope execution, Scope memory, MemorySemanticsMask);
  351. void createMemoryBarrier(unsigned executionScope, unsigned memorySemantics);
  352. Id createUnaryOp(Op, Id typeId, Id operand);
  353. Id createBinOp(Op, Id typeId, Id operand1, Id operand2);
  354. Id createTriOp(Op, Id typeId, Id operand1, Id operand2, Id operand3);
  355. Id createOp(Op, Id typeId, const std::vector<Id>& operands);
  356. Id createOp(Op, Id typeId, const std::vector<IdImmediate>& operands);
  357. Id createFunctionCall(spv::Function*, const std::vector<spv::Id>&);
  358. Id createSpecConstantOp(Op, Id typeId, const std::vector<spv::Id>& operands, const std::vector<unsigned>& literals);
  359. // Take an rvalue (source) and a set of channels to extract from it to
  360. // make a new rvalue, which is returned.
  361. Id createRvalueSwizzle(Decoration precision, Id typeId, Id source, const std::vector<unsigned>& channels);
  362. // Take a copy of an lvalue (target) and a source of components, and set the
  363. // source components into the lvalue where the 'channels' say to put them.
  364. // An updated version of the target is returned.
  365. // (No true lvalue or stores are used.)
  366. Id createLvalueSwizzle(Id typeId, Id target, Id source, const std::vector<unsigned>& channels);
  367. // If both the id and precision are valid, the id
  368. // gets tagged with the requested precision.
  369. // The passed in id is always the returned id, to simplify use patterns.
  370. Id setPrecision(Id id, Decoration precision)
  371. {
  372. if (precision != NoPrecision && id != NoResult)
  373. addDecoration(id, precision);
  374. return id;
  375. }
  376. // Can smear a scalar to a vector for the following forms:
  377. // - promoteScalar(scalar, vector) // smear scalar to width of vector
  378. // - promoteScalar(vector, scalar) // smear scalar to width of vector
  379. // - promoteScalar(pointer, scalar) // smear scalar to width of what pointer points to
  380. // - promoteScalar(scalar, scalar) // do nothing
  381. // Other forms are not allowed.
  382. //
  383. // Generally, the type of 'scalar' does not need to be the same type as the components in 'vector'.
  384. // The type of the created vector is a vector of components of the same type as the scalar.
  385. //
  386. // Note: One of the arguments will change, with the result coming back that way rather than
  387. // through the return value.
  388. void promoteScalar(Decoration precision, Id& left, Id& right);
  389. // Make a value by smearing the scalar to fill the type.
  390. // vectorType should be the correct type for making a vector of scalarVal.
  391. // (No conversions are done.)
  392. Id smearScalar(Decoration precision, Id scalarVal, Id vectorType);
  393. // Create a call to a built-in function.
  394. Id createBuiltinCall(Id resultType, Id builtins, int entryPoint, const std::vector<Id>& args);
  395. // List of parameters used to create a texture operation
  396. struct TextureParameters {
  397. Id sampler;
  398. Id coords;
  399. Id bias;
  400. Id lod;
  401. Id Dref;
  402. Id offset;
  403. Id offsets;
  404. Id gradX;
  405. Id gradY;
  406. Id sample;
  407. Id component;
  408. Id texelOut;
  409. Id lodClamp;
  410. Id granularity;
  411. Id coarse;
  412. bool nonprivate;
  413. bool volatil;
  414. };
  415. // Select the correct texture operation based on all inputs, and emit the correct instruction
  416. Id createTextureCall(Decoration precision, Id resultType, bool sparse, bool fetch, bool proj, bool gather,
  417. bool noImplicit, const TextureParameters&, ImageOperandsMask);
  418. // Emit the OpTextureQuery* instruction that was passed in.
  419. // Figure out the right return value and type, and return it.
  420. Id createTextureQueryCall(Op, const TextureParameters&, bool isUnsignedResult);
  421. Id createSamplePositionCall(Decoration precision, Id, Id);
  422. Id createBitFieldExtractCall(Decoration precision, Id, Id, Id, bool isSigned);
  423. Id createBitFieldInsertCall(Decoration precision, Id, Id, Id, Id);
  424. // Reduction comparison for composites: For equal and not-equal resulting in a scalar.
  425. Id createCompositeCompare(Decoration precision, Id, Id, bool /* true if for equal, false if for not-equal */);
  426. // OpCompositeConstruct
  427. Id createCompositeConstruct(Id typeId, const std::vector<Id>& constituents);
  428. // vector or scalar constructor
  429. Id createConstructor(Decoration precision, const std::vector<Id>& sources, Id resultTypeId);
  430. // matrix constructor
  431. Id createMatrixConstructor(Decoration precision, const std::vector<Id>& sources, Id constructee);
  432. // Helper to use for building nested control flow with if-then-else.
  433. class If {
  434. public:
  435. If(Id condition, unsigned int ctrl, Builder& builder);
  436. ~If() {}
  437. void makeBeginElse();
  438. void makeEndIf();
  439. private:
  440. If(const If&);
  441. If& operator=(If&);
  442. Builder& builder;
  443. Id condition;
  444. unsigned int control;
  445. Function* function;
  446. Block* headerBlock;
  447. Block* thenBlock;
  448. Block* elseBlock;
  449. Block* mergeBlock;
  450. };
  451. // Make a switch statement. A switch has 'numSegments' of pieces of code, not containing
  452. // any case/default labels, all separated by one or more case/default labels. Each possible
  453. // case value v is a jump to the caseValues[v] segment. The defaultSegment is also in this
  454. // number space. How to compute the value is given by 'condition', as in switch(condition).
  455. //
  456. // The SPIR-V Builder will maintain the stack of post-switch merge blocks for nested switches.
  457. //
  458. // Use a defaultSegment < 0 if there is no default segment (to branch to post switch).
  459. //
  460. // Returns the right set of basic blocks to start each code segment with, so that the caller's
  461. // recursion stack can hold the memory for it.
  462. //
  463. void makeSwitch(Id condition, unsigned int control, int numSegments, const std::vector<int>& caseValues,
  464. const std::vector<int>& valueToSegment, int defaultSegment, std::vector<Block*>& segmentBB);
  465. // Add a branch to the innermost switch's merge block.
  466. void addSwitchBreak();
  467. // Move to the next code segment, passing in the return argument in makeSwitch()
  468. void nextSwitchSegment(std::vector<Block*>& segmentBB, int segment);
  469. // Finish off the innermost switch.
  470. void endSwitch(std::vector<Block*>& segmentBB);
  471. struct LoopBlocks {
  472. LoopBlocks(Block& head, Block& body, Block& merge, Block& continue_target) :
  473. head(head), body(body), merge(merge), continue_target(continue_target) { }
  474. Block &head, &body, &merge, &continue_target;
  475. private:
  476. LoopBlocks();
  477. LoopBlocks& operator=(const LoopBlocks&) = delete;
  478. };
  479. // Start a new loop and prepare the builder to generate code for it. Until
  480. // closeLoop() is called for this loop, createLoopContinue() and
  481. // createLoopExit() will target its corresponding blocks.
  482. LoopBlocks& makeNewLoop();
  483. // Create a new block in the function containing the build point. Memory is
  484. // owned by the function object.
  485. Block& makeNewBlock();
  486. // Add a branch to the continue_target of the current (innermost) loop.
  487. void createLoopContinue();
  488. // Add an exit (e.g. "break") from the innermost loop that we're currently
  489. // in.
  490. void createLoopExit();
  491. // Close the innermost loop that you're in
  492. void closeLoop();
  493. //
  494. // Access chain design for an R-Value vs. L-Value:
  495. //
  496. // There is a single access chain the builder is building at
  497. // any particular time. Such a chain can be used to either to a load or
  498. // a store, when desired.
  499. //
  500. // Expressions can be r-values, l-values, or both, or only r-values:
  501. // a[b.c].d = .... // l-value
  502. // ... = a[b.c].d; // r-value, that also looks like an l-value
  503. // ++a[b.c].d; // r-value and l-value
  504. // (x + y)[2]; // r-value only, can't possibly be l-value
  505. //
  506. // Computing an r-value means generating code. Hence,
  507. // r-values should only be computed when they are needed, not speculatively.
  508. //
  509. // Computing an l-value means saving away information for later use in the compiler,
  510. // no code is generated until the l-value is later dereferenced. It is okay
  511. // to speculatively generate an l-value, just not okay to speculatively dereference it.
  512. //
  513. // The base of the access chain (the left-most variable or expression
  514. // from which everything is based) can be set either as an l-value
  515. // or as an r-value. Most efficient would be to set an l-value if one
  516. // is available. If an expression was evaluated, the resulting r-value
  517. // can be set as the chain base.
  518. //
  519. // The users of this single access chain can save and restore if they
  520. // want to nest or manage multiple chains.
  521. //
  522. struct AccessChain {
  523. Id base; // for l-values, pointer to the base object, for r-values, the base object
  524. std::vector<Id> indexChain;
  525. Id instr; // cache the instruction that generates this access chain
  526. std::vector<unsigned> swizzle; // each std::vector element selects the next GLSL component number
  527. Id component; // a dynamic component index, can coexist with a swizzle,
  528. // done after the swizzle, NoResult if not present
  529. Id preSwizzleBaseType; // dereferenced type, before swizzle or component is applied;
  530. // NoType unless a swizzle or component is present
  531. bool isRValue; // true if 'base' is an r-value, otherwise, base is an l-value
  532. unsigned int alignment; // bitwise OR of alignment values passed in. Accumulates worst alignment.
  533. // Only tracks base and (optional) component selection alignment.
  534. // Accumulate whether anything in the chain of structures has coherent decorations.
  535. struct CoherentFlags {
  536. CoherentFlags() { clear(); }
  537. #ifdef GLSLANG_WEB
  538. void clear() { }
  539. bool isVolatile() const { return false; }
  540. CoherentFlags operator |=(const CoherentFlags &other) { return *this; }
  541. #else
  542. bool isVolatile() const { return volatil; }
  543. bool anyCoherent() const {
  544. return coherent || devicecoherent || queuefamilycoherent || workgroupcoherent ||
  545. subgroupcoherent || shadercallcoherent;
  546. }
  547. unsigned coherent : 1;
  548. unsigned devicecoherent : 1;
  549. unsigned queuefamilycoherent : 1;
  550. unsigned workgroupcoherent : 1;
  551. unsigned subgroupcoherent : 1;
  552. unsigned shadercallcoherent : 1;
  553. unsigned nonprivate : 1;
  554. unsigned volatil : 1;
  555. unsigned isImage : 1;
  556. void clear() {
  557. coherent = 0;
  558. devicecoherent = 0;
  559. queuefamilycoherent = 0;
  560. workgroupcoherent = 0;
  561. subgroupcoherent = 0;
  562. shadercallcoherent = 0;
  563. nonprivate = 0;
  564. volatil = 0;
  565. isImage = 0;
  566. }
  567. CoherentFlags operator |=(const CoherentFlags &other) {
  568. coherent |= other.coherent;
  569. devicecoherent |= other.devicecoherent;
  570. queuefamilycoherent |= other.queuefamilycoherent;
  571. workgroupcoherent |= other.workgroupcoherent;
  572. subgroupcoherent |= other.subgroupcoherent;
  573. shadercallcoherent |= other.shadercallcoherent;
  574. nonprivate |= other.nonprivate;
  575. volatil |= other.volatil;
  576. isImage |= other.isImage;
  577. return *this;
  578. }
  579. #endif
  580. };
  581. CoherentFlags coherentFlags;
  582. };
  583. //
  584. // the SPIR-V builder maintains a single active chain that
  585. // the following methods operate on
  586. //
  587. // for external save and restore
  588. AccessChain getAccessChain() { return accessChain; }
  589. void setAccessChain(AccessChain newChain) { accessChain = newChain; }
  590. // clear accessChain
  591. void clearAccessChain();
  592. // set new base as an l-value base
  593. void setAccessChainLValue(Id lValue)
  594. {
  595. assert(isPointer(lValue));
  596. accessChain.base = lValue;
  597. }
  598. // set new base value as an r-value
  599. void setAccessChainRValue(Id rValue)
  600. {
  601. accessChain.isRValue = true;
  602. accessChain.base = rValue;
  603. }
  604. // push offset onto the end of the chain
  605. void accessChainPush(Id offset, AccessChain::CoherentFlags coherentFlags, unsigned int alignment)
  606. {
  607. accessChain.indexChain.push_back(offset);
  608. accessChain.coherentFlags |= coherentFlags;
  609. accessChain.alignment |= alignment;
  610. }
  611. // push new swizzle onto the end of any existing swizzle, merging into a single swizzle
  612. void accessChainPushSwizzle(std::vector<unsigned>& swizzle, Id preSwizzleBaseType,
  613. AccessChain::CoherentFlags coherentFlags, unsigned int alignment);
  614. // push a dynamic component selection onto the access chain, only applicable with a
  615. // non-trivial swizzle or no swizzle
  616. void accessChainPushComponent(Id component, Id preSwizzleBaseType, AccessChain::CoherentFlags coherentFlags,
  617. unsigned int alignment)
  618. {
  619. if (accessChain.swizzle.size() != 1) {
  620. accessChain.component = component;
  621. if (accessChain.preSwizzleBaseType == NoType)
  622. accessChain.preSwizzleBaseType = preSwizzleBaseType;
  623. }
  624. accessChain.coherentFlags |= coherentFlags;
  625. accessChain.alignment |= alignment;
  626. }
  627. // use accessChain and swizzle to store value
  628. void accessChainStore(Id rvalue, spv::MemoryAccessMask memoryAccess = spv::MemoryAccessMaskNone,
  629. spv::Scope scope = spv::ScopeMax, unsigned int alignment = 0);
  630. // use accessChain and swizzle to load an r-value
  631. Id accessChainLoad(Decoration precision, Decoration nonUniform, Id ResultType,
  632. spv::MemoryAccessMask memoryAccess = spv::MemoryAccessMaskNone, spv::Scope scope = spv::ScopeMax,
  633. unsigned int alignment = 0);
  634. // Return whether or not the access chain can be represented in SPIR-V
  635. // as an l-value.
  636. // E.g., a[3].yx cannot be, while a[3].y and a[3].y[x] can be.
  637. bool isSpvLvalue() const { return accessChain.swizzle.size() <= 1; }
  638. // get the direct pointer for an l-value
  639. Id accessChainGetLValue();
  640. // Get the inferred SPIR-V type of the result of the current access chain,
  641. // based on the type of the base and the chain of dereferences.
  642. Id accessChainGetInferredType();
  643. // Add capabilities, extensions, remove unneeded decorations, etc.,
  644. // based on the resulting SPIR-V.
  645. void postProcess();
  646. // Prune unreachable blocks in the CFG and remove unneeded decorations.
  647. void postProcessCFG();
  648. #ifndef GLSLANG_WEB
  649. // Add capabilities, extensions based on instructions in the module.
  650. void postProcessFeatures();
  651. // Hook to visit each instruction in a block in a function
  652. void postProcess(Instruction&);
  653. // Hook to visit each non-32-bit sized float/int operation in a block.
  654. void postProcessType(const Instruction&, spv::Id typeId);
  655. #endif
  656. void dump(std::vector<unsigned int>&) const;
  657. void createBranch(Block* block);
  658. void createConditionalBranch(Id condition, Block* thenBlock, Block* elseBlock);
  659. void createLoopMerge(Block* mergeBlock, Block* continueBlock, unsigned int control,
  660. const std::vector<unsigned int>& operands);
  661. // Sets to generate opcode for specialization constants.
  662. void setToSpecConstCodeGenMode() { generatingOpCodeForSpecConst = true; }
  663. // Sets to generate opcode for non-specialization constants (normal mode).
  664. void setToNormalCodeGenMode() { generatingOpCodeForSpecConst = false; }
  665. // Check if the builder is generating code for spec constants.
  666. bool isInSpecConstCodeGenMode() { return generatingOpCodeForSpecConst; }
  667. protected:
  668. Id makeIntConstant(Id typeId, unsigned value, bool specConstant);
  669. Id makeInt64Constant(Id typeId, unsigned long long value, bool specConstant);
  670. Id findScalarConstant(Op typeClass, Op opcode, Id typeId, unsigned value);
  671. Id findScalarConstant(Op typeClass, Op opcode, Id typeId, unsigned v1, unsigned v2);
  672. Id findCompositeConstant(Op typeClass, Id typeId, const std::vector<Id>& comps);
  673. Id findStructConstant(Id typeId, const std::vector<Id>& comps);
  674. Id collapseAccessChain();
  675. void remapDynamicSwizzle();
  676. void transferAccessChainSwizzle(bool dynamic);
  677. void simplifyAccessChainSwizzle();
  678. void createAndSetNoPredecessorBlock(const char*);
  679. void createSelectionMerge(Block* mergeBlock, unsigned int control);
  680. void dumpSourceInstructions(std::vector<unsigned int>&) const;
  681. void dumpSourceInstructions(const spv::Id fileId, const std::string& text, std::vector<unsigned int>&) const;
  682. void dumpInstructions(std::vector<unsigned int>&, const std::vector<std::unique_ptr<Instruction> >&) const;
  683. void dumpModuleProcesses(std::vector<unsigned int>&) const;
  684. spv::MemoryAccessMask sanitizeMemoryAccessForStorageClass(spv::MemoryAccessMask memoryAccess, StorageClass sc)
  685. const;
  686. unsigned int spvVersion; // the version of SPIR-V to emit in the header
  687. SourceLanguage source;
  688. int sourceVersion;
  689. spv::Id sourceFileStringId;
  690. std::string sourceText;
  691. int currentLine;
  692. const char* currentFile;
  693. bool emitOpLines;
  694. std::set<std::string> extensions;
  695. std::vector<const char*> sourceExtensions;
  696. std::vector<const char*> moduleProcesses;
  697. AddressingModel addressModel;
  698. MemoryModel memoryModel;
  699. std::set<spv::Capability> capabilities;
  700. int builderNumber;
  701. Module module;
  702. Block* buildPoint;
  703. Id uniqueId;
  704. Function* entryPointFunction;
  705. bool generatingOpCodeForSpecConst;
  706. AccessChain accessChain;
  707. // special blocks of instructions for output
  708. std::vector<std::unique_ptr<Instruction> > strings;
  709. std::vector<std::unique_ptr<Instruction> > imports;
  710. std::vector<std::unique_ptr<Instruction> > entryPoints;
  711. std::vector<std::unique_ptr<Instruction> > executionModes;
  712. std::vector<std::unique_ptr<Instruction> > names;
  713. std::vector<std::unique_ptr<Instruction> > decorations;
  714. std::vector<std::unique_ptr<Instruction> > constantsTypesGlobals;
  715. std::vector<std::unique_ptr<Instruction> > externals;
  716. std::vector<std::unique_ptr<Function> > functions;
  717. // not output, internally used for quick & dirty canonical (unique) creation
  718. // map type opcodes to constant inst.
  719. std::unordered_map<unsigned int, std::vector<Instruction*>> groupedConstants;
  720. // map struct-id to constant instructions
  721. std::unordered_map<unsigned int, std::vector<Instruction*>> groupedStructConstants;
  722. // map type opcodes to type instructions
  723. std::unordered_map<unsigned int, std::vector<Instruction*>> groupedTypes;
  724. // stack of switches
  725. std::stack<Block*> switchMerges;
  726. // Our loop stack.
  727. std::stack<LoopBlocks> loops;
  728. // map from strings to their string ids
  729. std::unordered_map<std::string, spv::Id> stringIds;
  730. // map from include file name ids to their contents
  731. std::map<spv::Id, const std::string*> includeFiles;
  732. // The stream for outputting warnings and errors.
  733. SpvBuildLogger* logger;
  734. }; // end Builder class
  735. }; // end spv namespace
  736. #endif // SpvBuilder_H