SpvBuilder.h 30 KB

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