Structure.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. //===--- Structure.cpp - SPIR-V representation structures -----*- C++ -*---===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "clang/SPIRV/Structure.h"
  10. #include "BlockReadableOrder.h"
  11. namespace clang {
  12. namespace spirv {
  13. namespace {
  14. constexpr uint32_t kGeneratorNumber = 14;
  15. constexpr uint32_t kToolVersion = 0;
  16. } // namespace
  17. // === Instruction implementations ===
  18. spv::Op Instruction::getOpcode() const {
  19. if (!isEmpty()) {
  20. return static_cast<spv::Op>(words.front() & spv::OpCodeMask);
  21. }
  22. return spv::Op::Max;
  23. }
  24. bool Instruction::isTerminator() const {
  25. switch (getOpcode()) {
  26. case spv::Op::OpBranch:
  27. case spv::Op::OpBranchConditional:
  28. case spv::Op::OpReturn:
  29. case spv::Op::OpReturnValue:
  30. case spv::Op::OpSwitch:
  31. case spv::Op::OpKill:
  32. case spv::Op::OpUnreachable:
  33. return true;
  34. default:
  35. return false;
  36. }
  37. }
  38. // === Basic block implementations ===
  39. BasicBlock::BasicBlock(BasicBlock &&that)
  40. : labelId(that.labelId), debugName(that.debugName),
  41. instructions(std::move(that.instructions)) {
  42. that.clear();
  43. }
  44. BasicBlock &BasicBlock::operator=(BasicBlock &&that) {
  45. labelId = that.labelId;
  46. debugName = that.debugName;
  47. instructions = std::move(that.instructions);
  48. that.clear();
  49. return *this;
  50. }
  51. void BasicBlock::take(InstBuilder *builder) {
  52. // Make sure we have a terminator instruction at the end.
  53. assert(isTerminated() && "found basic block without terminator");
  54. builder->opLabel(labelId).x();
  55. for (auto &inst : instructions) {
  56. builder->getConsumer()(inst.take());
  57. }
  58. clear();
  59. }
  60. bool BasicBlock::isTerminated() const {
  61. return !instructions.empty() && instructions.back().isTerminator();
  62. }
  63. // === Function implementations ===
  64. Function::Function(Function &&that)
  65. : resultType(that.resultType), resultId(that.resultId),
  66. funcControl(that.funcControl), funcType(that.funcType),
  67. parameters(std::move(that.parameters)),
  68. variables(std::move(that.variables)), blocks(std::move(that.blocks)) {
  69. that.clear();
  70. }
  71. Function &Function::operator=(Function &&that) {
  72. resultType = that.resultType;
  73. resultId = that.resultId;
  74. funcControl = that.funcControl;
  75. funcType = that.funcType;
  76. parameters = std::move(that.parameters);
  77. variables = std::move(that.variables);
  78. blocks = std::move(that.blocks);
  79. that.clear();
  80. return *this;
  81. }
  82. void Function::clear() {
  83. resultType = 0;
  84. resultId = 0;
  85. funcControl = spv::FunctionControlMask::MaskNone;
  86. funcType = 0;
  87. parameters.clear();
  88. variables.clear();
  89. blocks.clear();
  90. }
  91. void Function::take(InstBuilder *builder) {
  92. builder->opFunction(resultType, resultId, funcControl, funcType).x();
  93. // Write out all parameters.
  94. for (auto &param : parameters) {
  95. builder->opFunctionParameter(param.first, param.second).x();
  96. }
  97. if (!variables.empty()) {
  98. assert(!blocks.empty());
  99. }
  100. // Preprend all local variables to the entry block.
  101. // This is necessary since SPIR-V requires all local variables to be defined
  102. // at the very begining of the entry block.
  103. // We need to do it in the reverse order to guarantee variables have the
  104. // same definition order in SPIR-V as in the source code.
  105. for (auto it = variables.rbegin(), ie = variables.rend(); it != ie; ++it) {
  106. blocks.front()->prependInstruction(std::move(*it));
  107. }
  108. // Collect basic blocks in a human-readable order that satisfies SPIR-V
  109. // validation rules.
  110. std::vector<BasicBlock *> orderedBlocks;
  111. if (!blocks.empty()) {
  112. BlockReadableOrderVisitor(
  113. [&orderedBlocks](BasicBlock *block) { orderedBlocks.push_back(block); })
  114. .visit(blocks.front().get());
  115. }
  116. // Write out all basic blocks.
  117. for (auto *block : orderedBlocks) {
  118. block->take(builder);
  119. }
  120. builder->opFunctionEnd().x();
  121. clear();
  122. }
  123. void Function::addVariable(uint32_t varType, uint32_t varId,
  124. llvm::Optional<uint32_t> init) {
  125. variables.emplace_back(
  126. InstBuilder(nullptr)
  127. .opVariable(varType, varId, spv::StorageClass::Function, init)
  128. .take());
  129. }
  130. void Function::getReachableBasicBlocks(std::vector<BasicBlock *> *bbVec) const {
  131. if (!blocks.empty()) {
  132. BlockReadableOrderVisitor(
  133. [&bbVec](BasicBlock *block) { bbVec->push_back(block); })
  134. .visit(blocks.front().get());
  135. }
  136. }
  137. // === Module components implementations ===
  138. Header::Header()
  139. // We are using the unfied header, which shows spv::Version as the newest
  140. // version. But we need to stick to 1.0 for Vulkan consumption by default.
  141. : magicNumber(spv::MagicNumber), version(0x00010000),
  142. generator((kGeneratorNumber << 16) | kToolVersion), bound(0),
  143. reserved(0) {}
  144. void Header::collect(const WordConsumer &consumer) {
  145. std::vector<uint32_t> words;
  146. words.push_back(magicNumber);
  147. words.push_back(version);
  148. words.push_back(generator);
  149. words.push_back(bound);
  150. words.push_back(reserved);
  151. consumer(std::move(words));
  152. }
  153. bool DebugName::operator==(const DebugName &that) const {
  154. if (targetId == that.targetId && name == that.name) {
  155. if (memberIndex.hasValue()) {
  156. return that.memberIndex.hasValue() &&
  157. memberIndex.getValue() == that.memberIndex.getValue();
  158. }
  159. return !that.memberIndex.hasValue();
  160. }
  161. return false;
  162. }
  163. bool DebugName::operator<(const DebugName &that) const {
  164. // Sort according to target id first
  165. if (targetId != that.targetId)
  166. return targetId < that.targetId;
  167. if (memberIndex.hasValue()) {
  168. // Sort member decorations according to member index
  169. if (that.memberIndex.hasValue())
  170. return memberIndex.getValue() < that.memberIndex.getValue();
  171. // Decorations on the id itself goes before those on its members
  172. return false;
  173. }
  174. // Decorations on the id itself goes before those on its members
  175. if (that.memberIndex.hasValue())
  176. return true;
  177. return name < that.name;
  178. }
  179. // === Module implementations ===
  180. bool SPIRVModule::isEmpty() const {
  181. return header.bound == 0 && capabilities.empty() && extensions.empty() &&
  182. extInstSets.empty() && !addressingModel.hasValue() &&
  183. !memoryModel.hasValue() && entryPoints.empty() &&
  184. executionModes.empty() && debugNames.empty() && decorations.empty() &&
  185. types.empty() && constants.empty() && variables.empty() &&
  186. functions.empty();
  187. }
  188. void SPIRVModule::clear() {
  189. header.bound = 0;
  190. capabilities.clear();
  191. extensions.clear();
  192. extInstSets.clear();
  193. addressingModel = llvm::None;
  194. memoryModel = llvm::None;
  195. entryPoints.clear();
  196. executionModes.clear();
  197. debugNames.clear();
  198. decorations.clear();
  199. types.clear();
  200. constants.clear();
  201. variables.clear();
  202. functions.clear();
  203. }
  204. void SPIRVModule::take(InstBuilder *builder) {
  205. const auto &consumer = builder->getConsumer();
  206. // Order matters here.
  207. header.collect(consumer);
  208. for (auto &cap : capabilities) {
  209. builder->opCapability(cap).x();
  210. }
  211. for (auto &ext : extensions) {
  212. builder->opExtension(ext).x();
  213. }
  214. for (auto &inst : extInstSets) {
  215. builder->opExtInstImport(inst.second, inst.first).x();
  216. }
  217. if (addressingModel.hasValue() && memoryModel.hasValue()) {
  218. builder->opMemoryModel(*addressingModel, *memoryModel).x();
  219. }
  220. for (auto &inst : entryPoints) {
  221. builder
  222. ->opEntryPoint(inst.executionModel, inst.targetId,
  223. std::move(inst.targetName), inst.interfaces)
  224. .x();
  225. }
  226. for (auto &inst : executionModes) {
  227. consumer(inst.take());
  228. }
  229. if (shaderModelVersion != 0) {
  230. llvm::Optional<uint32_t> fileName = llvm::None;
  231. if (!sourceFileName.empty() && sourceFileNameId) {
  232. builder->opString(sourceFileNameId, sourceFileName).x();
  233. fileName = sourceFileNameId;
  234. }
  235. builder
  236. ->opSource(spv::SourceLanguage::HLSL, shaderModelVersion, fileName,
  237. llvm::None)
  238. .x();
  239. }
  240. // BasicBlock debug names should be emitted only for blocks that are
  241. // reachable.
  242. // The debug name for a basic block is stored in the basic block object.
  243. std::vector<BasicBlock *> reachableBasicBlocks;
  244. for (const auto &fn : functions)
  245. fn->getReachableBasicBlocks(&reachableBasicBlocks);
  246. for (BasicBlock *bb : reachableBasicBlocks)
  247. if (!bb->getDebugName().empty())
  248. builder->opName(bb->getLabelId(), bb->getDebugName()).x();
  249. // Emit other debug names
  250. for (auto &inst : debugNames) {
  251. if (inst.memberIndex.hasValue()) {
  252. builder
  253. ->opMemberName(inst.targetId, *inst.memberIndex, std::move(inst.name))
  254. .x();
  255. } else {
  256. builder->opName(inst.targetId, std::move(inst.name)).x();
  257. }
  258. }
  259. for (const auto &idDecorPair : decorations) {
  260. consumer(idDecorPair.second->withTargetId(idDecorPair.first));
  261. }
  262. // Note on interdependence of types and constants:
  263. // There is only one type (OpTypeArray) that requires the result-id of a
  264. // constant. As a result, the constant integer should be defined before the
  265. // array is defined. The integer type should also be defined before the
  266. // constant integer is defined.
  267. for (auto &v : typeConstant) {
  268. consumer(v.take());
  269. }
  270. for (auto &v : variables) {
  271. consumer(v.take());
  272. }
  273. for (uint32_t i = 0; i < functions.size(); ++i) {
  274. functions[i]->take(builder);
  275. }
  276. clear();
  277. }
  278. void SPIRVModule::addType(const Type *type, uint32_t resultId) {
  279. bool inserted = false;
  280. std::tie(std::ignore, inserted) = types.insert(type);
  281. if (inserted) {
  282. typeConstant.push_back(type->withResultId(resultId));
  283. for (const Decoration *d : type->getDecorations()) {
  284. addDecoration(d, resultId);
  285. }
  286. }
  287. }
  288. void SPIRVModule::addConstant(const Constant *constant, uint32_t resultId) {
  289. bool inserted = false;
  290. std::tie(std::ignore, inserted) = constants.insert(constant);
  291. if (inserted) {
  292. typeConstant.push_back(constant->withResultId(resultId));
  293. }
  294. }
  295. } // end namespace spirv
  296. } // end namespace clang