ModuleBuilder.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. //===--- ModuleBuilder.cpp - SPIR-V builder implementation ----*- 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/ModuleBuilder.h"
  10. #include "spirv/1.0//spirv.hpp11"
  11. #include "clang/SPIRV/InstBuilder.h"
  12. #include "llvm/llvm_assert/assert.h"
  13. namespace clang {
  14. namespace spirv {
  15. ModuleBuilder::ModuleBuilder(SPIRVContext *C)
  16. : theContext(*C), theModule(), theFunction(nullptr), insertPoint(nullptr),
  17. instBuilder(nullptr), glslExtSetId(0) {
  18. instBuilder.setConsumer([this](std::vector<uint32_t> &&words) {
  19. this->constructSite = std::move(words);
  20. });
  21. }
  22. std::vector<uint32_t> ModuleBuilder::takeModule() {
  23. theModule.setBound(theContext.getNextId());
  24. std::vector<uint32_t> binary;
  25. auto ib = InstBuilder([&binary](std::vector<uint32_t> &&words) {
  26. binary.insert(binary.end(), words.begin(), words.end());
  27. });
  28. theModule.take(&ib);
  29. return binary;
  30. }
  31. uint32_t ModuleBuilder::beginFunction(uint32_t funcType, uint32_t returnType,
  32. llvm::StringRef funcName, uint32_t fId) {
  33. if (theFunction) {
  34. assert(false && "found nested function");
  35. return 0;
  36. }
  37. // If the caller doesn't supply a function <result-id>, we need to get one.
  38. if (!fId)
  39. fId = theContext.takeNextId();
  40. theFunction = llvm::make_unique<Function>(
  41. returnType, fId, spv::FunctionControlMask::MaskNone, funcType);
  42. theModule.addDebugName(fId, funcName);
  43. return fId;
  44. }
  45. uint32_t ModuleBuilder::addFnParam(uint32_t ptrType, llvm::StringRef name) {
  46. assert(theFunction && "found detached parameter");
  47. const uint32_t paramId = theContext.takeNextId();
  48. theFunction->addParameter(ptrType, paramId);
  49. theModule.addDebugName(paramId, name);
  50. return paramId;
  51. }
  52. uint32_t ModuleBuilder::addFnVar(uint32_t varType, llvm::StringRef name,
  53. llvm::Optional<uint32_t> init) {
  54. assert(theFunction && "found detached local variable");
  55. const uint32_t ptrType = getPointerType(varType, spv::StorageClass::Function);
  56. const uint32_t varId = theContext.takeNextId();
  57. theFunction->addVariable(ptrType, varId, init);
  58. theModule.addDebugName(varId, name);
  59. return varId;
  60. }
  61. bool ModuleBuilder::endFunction() {
  62. if (theFunction == nullptr) {
  63. assert(false && "no active function");
  64. return false;
  65. }
  66. // Move all basic blocks into the current function.
  67. // TODO: we should adjust the order the basic blocks according to
  68. // SPIR-V validation rules.
  69. for (auto &bb : basicBlocks) {
  70. theFunction->addBasicBlock(std::move(bb.second));
  71. }
  72. basicBlocks.clear();
  73. theModule.addFunction(std::move(theFunction));
  74. theFunction.reset(nullptr);
  75. insertPoint = nullptr;
  76. return true;
  77. }
  78. uint32_t ModuleBuilder::createBasicBlock(llvm::StringRef name) {
  79. if (theFunction == nullptr) {
  80. assert(false && "found detached basic block");
  81. return 0;
  82. }
  83. const uint32_t labelId = theContext.takeNextId();
  84. basicBlocks[labelId] = llvm::make_unique<BasicBlock>(labelId, name);
  85. return labelId;
  86. }
  87. void ModuleBuilder::addSuccessor(uint32_t successorLabel) {
  88. assert(insertPoint && "null insert point");
  89. insertPoint->addSuccessor(getBasicBlock(successorLabel));
  90. }
  91. void ModuleBuilder::setMergeTarget(uint32_t mergeLabel) {
  92. assert(insertPoint && "null insert point");
  93. insertPoint->setMergeTarget(getBasicBlock(mergeLabel));
  94. }
  95. void ModuleBuilder::setContinueTarget(uint32_t continueLabel) {
  96. assert(insertPoint && "null insert point");
  97. insertPoint->setContinueTarget(getBasicBlock(continueLabel));
  98. }
  99. void ModuleBuilder::setInsertPoint(uint32_t labelId) {
  100. insertPoint = getBasicBlock(labelId);
  101. }
  102. uint32_t
  103. ModuleBuilder::createCompositeConstruct(uint32_t resultType,
  104. llvm::ArrayRef<uint32_t> constituents) {
  105. assert(insertPoint && "null insert point");
  106. const uint32_t resultId = theContext.takeNextId();
  107. instBuilder.opCompositeConstruct(resultType, resultId, constituents).x();
  108. insertPoint->appendInstruction(std::move(constructSite));
  109. return resultId;
  110. }
  111. uint32_t
  112. ModuleBuilder::createCompositeExtract(uint32_t resultType, uint32_t composite,
  113. llvm::ArrayRef<uint32_t> indexes) {
  114. assert(insertPoint && "null insert point");
  115. const uint32_t resultId = theContext.takeNextId();
  116. instBuilder.opCompositeExtract(resultType, resultId, composite, indexes).x();
  117. insertPoint->appendInstruction(std::move(constructSite));
  118. return resultId;
  119. }
  120. uint32_t
  121. ModuleBuilder::createVectorShuffle(uint32_t resultType, uint32_t vector1,
  122. uint32_t vector2,
  123. llvm::ArrayRef<uint32_t> selectors) {
  124. assert(insertPoint && "null insert point");
  125. const uint32_t resultId = theContext.takeNextId();
  126. instBuilder.opVectorShuffle(resultType, resultId, vector1, vector2, selectors)
  127. .x();
  128. insertPoint->appendInstruction(std::move(constructSite));
  129. return resultId;
  130. }
  131. uint32_t ModuleBuilder::createLoad(uint32_t resultType, uint32_t pointer) {
  132. assert(insertPoint && "null insert point");
  133. const uint32_t resultId = theContext.takeNextId();
  134. instBuilder.opLoad(resultType, resultId, pointer, llvm::None).x();
  135. insertPoint->appendInstruction(std::move(constructSite));
  136. return resultId;
  137. }
  138. void ModuleBuilder::createStore(uint32_t address, uint32_t value) {
  139. assert(insertPoint && "null insert point");
  140. instBuilder.opStore(address, value, llvm::None).x();
  141. insertPoint->appendInstruction(std::move(constructSite));
  142. }
  143. uint32_t ModuleBuilder::createFunctionCall(uint32_t returnType,
  144. uint32_t functionId,
  145. llvm::ArrayRef<uint32_t> params) {
  146. assert(insertPoint && "null insert point");
  147. const uint32_t id = theContext.takeNextId();
  148. instBuilder.opFunctionCall(returnType, id, functionId, params).x();
  149. insertPoint->appendInstruction(std::move(constructSite));
  150. return id;
  151. }
  152. uint32_t ModuleBuilder::createAccessChain(uint32_t resultType, uint32_t base,
  153. llvm::ArrayRef<uint32_t> indexes) {
  154. assert(insertPoint && "null insert point");
  155. const uint32_t id = theContext.takeNextId();
  156. instBuilder.opAccessChain(resultType, id, base, indexes).x();
  157. insertPoint->appendInstruction(std::move(constructSite));
  158. return id;
  159. }
  160. uint32_t ModuleBuilder::createUnaryOp(spv::Op op, uint32_t resultType,
  161. uint32_t operand) {
  162. assert(insertPoint && "null insert point");
  163. const uint32_t id = theContext.takeNextId();
  164. instBuilder.unaryOp(op, resultType, id, operand).x();
  165. insertPoint->appendInstruction(std::move(constructSite));
  166. return id;
  167. }
  168. uint32_t ModuleBuilder::createBinaryOp(spv::Op op, uint32_t resultType,
  169. uint32_t lhs, uint32_t rhs) {
  170. assert(insertPoint && "null insert point");
  171. const uint32_t id = theContext.takeNextId();
  172. instBuilder.binaryOp(op, resultType, id, lhs, rhs).x();
  173. insertPoint->appendInstruction(std::move(constructSite));
  174. return id;
  175. }
  176. spv::ImageOperandsMask ModuleBuilder::composeImageOperandsMask(
  177. uint32_t bias, uint32_t lod, const std::pair<uint32_t, uint32_t> &grad,
  178. uint32_t constOffset, uint32_t varOffset,
  179. llvm::SmallVectorImpl<uint32_t> *orderedParams) {
  180. using spv::ImageOperandsMask;
  181. // SPIR-V Image Operands from least significant bit to most significant bit
  182. // Bias, Lod, Grad, ConstOffset, Offset, ConstOffsets, Sample, MinLod
  183. auto mask = ImageOperandsMask::MaskNone;
  184. orderedParams->clear();
  185. if (bias) {
  186. mask = mask | ImageOperandsMask::Bias;
  187. orderedParams->push_back(bias);
  188. }
  189. if (lod) {
  190. mask = mask | ImageOperandsMask::Lod;
  191. orderedParams->push_back(lod);
  192. }
  193. if (grad.first && grad.second) {
  194. mask = mask | ImageOperandsMask::Grad;
  195. orderedParams->push_back(grad.first);
  196. orderedParams->push_back(grad.second);
  197. }
  198. if (constOffset) {
  199. mask = mask | ImageOperandsMask::ConstOffset;
  200. orderedParams->push_back(constOffset);
  201. }
  202. if (varOffset) {
  203. mask = mask | ImageOperandsMask::Offset;
  204. requireCapability(spv::Capability::ImageGatherExtended);
  205. orderedParams->push_back(varOffset);
  206. }
  207. return mask;
  208. }
  209. uint32_t ModuleBuilder::createImageSample(uint32_t texelType,
  210. uint32_t imageType, uint32_t image,
  211. uint32_t sampler, uint32_t coordinate,
  212. uint32_t bias, uint32_t lod,
  213. std::pair<uint32_t, uint32_t> grad,
  214. uint32_t constOffset,
  215. uint32_t varOffset) {
  216. assert(insertPoint && "null insert point");
  217. // An OpSampledImage is required to do the image sampling.
  218. const uint32_t sampledImgId = theContext.takeNextId();
  219. const uint32_t sampledImgTy = getSampledImageType(imageType);
  220. instBuilder.opSampledImage(sampledImgTy, sampledImgId, image, sampler).x();
  221. insertPoint->appendInstruction(std::move(constructSite));
  222. const uint32_t texelId = theContext.takeNextId();
  223. llvm::SmallVector<uint32_t, 4> params;
  224. const auto mask = composeImageOperandsMask(bias, lod, grad, constOffset,
  225. varOffset, &params);
  226. // The Lod and Grad image operands requires explicit-lod instructions.
  227. if (lod || (grad.first && grad.second)) {
  228. instBuilder.opImageSampleExplicitLod(texelType, texelId, sampledImgId,
  229. coordinate, mask);
  230. } else {
  231. instBuilder.opImageSampleImplicitLod(
  232. texelType, texelId, sampledImgId, coordinate,
  233. llvm::Optional<spv::ImageOperandsMask>(mask));
  234. }
  235. for (const auto param : params)
  236. instBuilder.idRef(param);
  237. instBuilder.x();
  238. insertPoint->appendInstruction(std::move(constructSite));
  239. return texelId;
  240. }
  241. void ModuleBuilder::createImageWrite(uint32_t imageId, uint32_t coordId,
  242. uint32_t texelId) {
  243. assert(insertPoint && "null insert point");
  244. instBuilder.opImageWrite(imageId, coordId, texelId, llvm::None).x();
  245. insertPoint->appendInstruction(std::move(constructSite));
  246. }
  247. uint32_t ModuleBuilder::createImageFetchOrRead(
  248. bool doImageFetch, uint32_t texelType, uint32_t image, uint32_t coordinate,
  249. uint32_t lod, uint32_t constOffset, uint32_t varOffset) {
  250. assert(insertPoint && "null insert point");
  251. llvm::SmallVector<uint32_t, 2> params;
  252. const auto mask =
  253. llvm::Optional<spv::ImageOperandsMask>(composeImageOperandsMask(
  254. /*bias*/ 0, lod, std::make_pair(0, 0), constOffset, varOffset,
  255. &params));
  256. const uint32_t texelId = theContext.takeNextId();
  257. if (doImageFetch)
  258. instBuilder.opImageFetch(texelType, texelId, image, coordinate, mask);
  259. else
  260. instBuilder.opImageRead(texelType, texelId, image, coordinate, mask);
  261. for (const auto param : params)
  262. instBuilder.idRef(param);
  263. instBuilder.x();
  264. insertPoint->appendInstruction(std::move(constructSite));
  265. return texelId;
  266. }
  267. uint32_t ModuleBuilder::createImageGather(uint32_t texelType,
  268. uint32_t imageType, uint32_t image,
  269. uint32_t sampler, uint32_t coordinate,
  270. uint32_t component,
  271. uint32_t constOffset,
  272. uint32_t varOffset) {
  273. assert(insertPoint && "null insert point");
  274. // An OpSampledImage is required to do the image sampling.
  275. const uint32_t sampledImgId = theContext.takeNextId();
  276. const uint32_t sampledImgTy = getSampledImageType(imageType);
  277. instBuilder.opSampledImage(sampledImgTy, sampledImgId, image, sampler).x();
  278. insertPoint->appendInstruction(std::move(constructSite));
  279. llvm::SmallVector<uint32_t, 2> params;
  280. const auto mask =
  281. llvm::Optional<spv::ImageOperandsMask>(composeImageOperandsMask(
  282. /*bias*/ 0, /*lod*/ 0, std::make_pair(0, 0), constOffset, varOffset,
  283. &params));
  284. const uint32_t texelId = theContext.takeNextId();
  285. instBuilder.opImageGather(texelType, texelId, sampledImgId, coordinate,
  286. component, mask);
  287. for (const auto param : params)
  288. instBuilder.idRef(param);
  289. instBuilder.x();
  290. insertPoint->appendInstruction(std::move(constructSite));
  291. return texelId;
  292. }
  293. uint32_t ModuleBuilder::createSelect(uint32_t resultType, uint32_t condition,
  294. uint32_t trueValue, uint32_t falseValue) {
  295. assert(insertPoint && "null insert point");
  296. const uint32_t id = theContext.takeNextId();
  297. instBuilder.opSelect(resultType, id, condition, trueValue, falseValue).x();
  298. insertPoint->appendInstruction(std::move(constructSite));
  299. return id;
  300. }
  301. void ModuleBuilder::createSwitch(
  302. uint32_t mergeLabel, uint32_t selector, uint32_t defaultLabel,
  303. llvm::ArrayRef<std::pair<uint32_t, uint32_t>> target) {
  304. assert(insertPoint && "null insert point");
  305. // Create the OpSelectioMerege.
  306. instBuilder.opSelectionMerge(mergeLabel, spv::SelectionControlMask::MaskNone)
  307. .x();
  308. insertPoint->appendInstruction(std::move(constructSite));
  309. // Create the OpSwitch.
  310. instBuilder.opSwitch(selector, defaultLabel, target).x();
  311. insertPoint->appendInstruction(std::move(constructSite));
  312. }
  313. void ModuleBuilder::createKill() {
  314. assert(insertPoint && "null insert point");
  315. assert(!isCurrentBasicBlockTerminated());
  316. instBuilder.opKill().x();
  317. insertPoint->appendInstruction(std::move(constructSite));
  318. }
  319. void ModuleBuilder::createBranch(uint32_t targetLabel, uint32_t mergeBB,
  320. uint32_t continueBB,
  321. spv::LoopControlMask loopControl) {
  322. assert(insertPoint && "null insert point");
  323. if (mergeBB && continueBB) {
  324. instBuilder.opLoopMerge(mergeBB, continueBB, loopControl).x();
  325. insertPoint->appendInstruction(std::move(constructSite));
  326. }
  327. instBuilder.opBranch(targetLabel).x();
  328. insertPoint->appendInstruction(std::move(constructSite));
  329. }
  330. void ModuleBuilder::createConditionalBranch(
  331. uint32_t condition, uint32_t trueLabel, uint32_t falseLabel,
  332. uint32_t mergeLabel, uint32_t continueLabel,
  333. spv::SelectionControlMask selectionControl,
  334. spv::LoopControlMask loopControl) {
  335. assert(insertPoint && "null insert point");
  336. if (mergeLabel) {
  337. if (continueLabel) {
  338. instBuilder.opLoopMerge(mergeLabel, continueLabel, loopControl).x();
  339. insertPoint->appendInstruction(std::move(constructSite));
  340. } else {
  341. instBuilder.opSelectionMerge(mergeLabel, selectionControl).x();
  342. insertPoint->appendInstruction(std::move(constructSite));
  343. }
  344. }
  345. instBuilder.opBranchConditional(condition, trueLabel, falseLabel, {}).x();
  346. insertPoint->appendInstruction(std::move(constructSite));
  347. }
  348. void ModuleBuilder::createReturn() {
  349. assert(insertPoint && "null insert point");
  350. instBuilder.opReturn().x();
  351. insertPoint->appendInstruction(std::move(constructSite));
  352. }
  353. void ModuleBuilder::createReturnValue(uint32_t value) {
  354. assert(insertPoint && "null insert point");
  355. instBuilder.opReturnValue(value).x();
  356. insertPoint->appendInstruction(std::move(constructSite));
  357. }
  358. uint32_t ModuleBuilder::createExtInst(uint32_t resultType, uint32_t setId,
  359. uint32_t instId,
  360. llvm::ArrayRef<uint32_t> operands) {
  361. assert(insertPoint && "null insert point");
  362. uint32_t resultId = theContext.takeNextId();
  363. instBuilder.opExtInst(resultType, resultId, setId, instId, operands).x();
  364. insertPoint->appendInstruction(std::move(constructSite));
  365. return resultId;
  366. }
  367. void ModuleBuilder::addExecutionMode(uint32_t entryPointId,
  368. spv::ExecutionMode em,
  369. llvm::ArrayRef<uint32_t> params) {
  370. instBuilder.opExecutionMode(entryPointId, em);
  371. for (const auto &param : params) {
  372. instBuilder.literalInteger(param);
  373. }
  374. instBuilder.x();
  375. theModule.addExecutionMode(std::move(constructSite));
  376. }
  377. uint32_t ModuleBuilder::getGLSLExtInstSet() {
  378. if (glslExtSetId == 0) {
  379. glslExtSetId = theContext.takeNextId();
  380. theModule.addExtInstSet(glslExtSetId, "GLSL.std.450");
  381. }
  382. return glslExtSetId;
  383. }
  384. uint32_t ModuleBuilder::addStageIOVar(uint32_t type,
  385. spv::StorageClass storageClass,
  386. std::string name) {
  387. const uint32_t pointerType = getPointerType(type, storageClass);
  388. const uint32_t varId = theContext.takeNextId();
  389. instBuilder.opVariable(pointerType, varId, storageClass, llvm::None).x();
  390. theModule.addVariable(std::move(constructSite));
  391. theModule.addDebugName(varId, name);
  392. return varId;
  393. }
  394. uint32_t ModuleBuilder::addStageBuiltinVar(uint32_t type, spv::StorageClass sc,
  395. spv::BuiltIn builtin) {
  396. const uint32_t pointerType = getPointerType(type, sc);
  397. const uint32_t varId = theContext.takeNextId();
  398. instBuilder.opVariable(pointerType, varId, sc, llvm::None).x();
  399. theModule.addVariable(std::move(constructSite));
  400. // Decorate with the specified Builtin
  401. const Decoration *d = Decoration::getBuiltIn(theContext, builtin);
  402. theModule.addDecoration(d, varId);
  403. return varId;
  404. }
  405. uint32_t ModuleBuilder::addModuleVar(uint32_t type, spv::StorageClass sc,
  406. llvm::StringRef name,
  407. llvm::Optional<uint32_t> init) {
  408. assert(sc != spv::StorageClass::Function);
  409. // TODO: basically duplicated code of addFileVar()
  410. const uint32_t pointerType = getPointerType(type, sc);
  411. const uint32_t varId = theContext.takeNextId();
  412. instBuilder.opVariable(pointerType, varId, sc, init).x();
  413. theModule.addVariable(std::move(constructSite));
  414. theModule.addDebugName(varId, name);
  415. return varId;
  416. }
  417. void ModuleBuilder::decorateDSetBinding(uint32_t targetId, uint32_t setNumber,
  418. uint32_t bindingNumber) {
  419. const auto *d = Decoration::getDescriptorSet(theContext, setNumber);
  420. theModule.addDecoration(d, targetId);
  421. d = Decoration::getBinding(theContext, bindingNumber);
  422. theModule.addDecoration(d, targetId);
  423. }
  424. void ModuleBuilder::decorateLocation(uint32_t targetId, uint32_t location) {
  425. const Decoration *d =
  426. Decoration::getLocation(theContext, location, llvm::None);
  427. theModule.addDecoration(d, targetId);
  428. }
  429. void ModuleBuilder::decorate(uint32_t targetId, spv::Decoration decoration) {
  430. const Decoration *d = nullptr;
  431. switch (decoration) {
  432. case spv::Decoration::Centroid:
  433. d = Decoration::getCentroid(theContext);
  434. break;
  435. case spv::Decoration::Flat:
  436. d = Decoration::getFlat(theContext);
  437. break;
  438. case spv::Decoration::NoPerspective:
  439. d = Decoration::getNoPerspective(theContext);
  440. break;
  441. case spv::Decoration::Sample:
  442. d = Decoration::getSample(theContext);
  443. break;
  444. case spv::Decoration::Block:
  445. d = Decoration::getBlock(theContext);
  446. break;
  447. }
  448. assert(d && "unimplemented decoration");
  449. theModule.addDecoration(d, targetId);
  450. }
  451. #define IMPL_GET_PRIMITIVE_TYPE(ty) \
  452. \
  453. uint32_t ModuleBuilder::get##ty##Type() { \
  454. const Type *type = Type::get##ty(theContext); \
  455. const uint32_t typeId = theContext.getResultIdForType(type); \
  456. theModule.addType(type, typeId); \
  457. return typeId; \
  458. \
  459. }
  460. IMPL_GET_PRIMITIVE_TYPE(Void)
  461. IMPL_GET_PRIMITIVE_TYPE(Bool)
  462. IMPL_GET_PRIMITIVE_TYPE(Int32)
  463. IMPL_GET_PRIMITIVE_TYPE(Uint32)
  464. IMPL_GET_PRIMITIVE_TYPE(Float32)
  465. #undef IMPL_GET_PRIMITIVE_TYPE
  466. uint32_t ModuleBuilder::getVecType(uint32_t elemType, uint32_t elemCount) {
  467. const Type *type = nullptr;
  468. switch (elemCount) {
  469. case 2:
  470. type = Type::getVec2(theContext, elemType);
  471. break;
  472. case 3:
  473. type = Type::getVec3(theContext, elemType);
  474. break;
  475. case 4:
  476. type = Type::getVec4(theContext, elemType);
  477. break;
  478. default:
  479. assert(false && "unhandled vector size");
  480. // Error found. Return 0 as the <result-id> directly.
  481. return 0;
  482. }
  483. const uint32_t typeId = theContext.getResultIdForType(type);
  484. theModule.addType(type, typeId);
  485. return typeId;
  486. }
  487. uint32_t ModuleBuilder::getMatType(uint32_t colType, uint32_t colCount) {
  488. const Type *type = Type::getMatrix(theContext, colType, colCount);
  489. const uint32_t typeId = theContext.getResultIdForType(type);
  490. theModule.addType(type, typeId);
  491. return typeId;
  492. }
  493. uint32_t ModuleBuilder::getPointerType(uint32_t pointeeType,
  494. spv::StorageClass storageClass) {
  495. const Type *type = Type::getPointer(theContext, storageClass, pointeeType);
  496. const uint32_t typeId = theContext.getResultIdForType(type);
  497. theModule.addType(type, typeId);
  498. return typeId;
  499. }
  500. uint32_t
  501. ModuleBuilder::getStructType(llvm::ArrayRef<uint32_t> fieldTypes,
  502. llvm::StringRef structName,
  503. llvm::ArrayRef<llvm::StringRef> fieldNames,
  504. Type::DecorationSet decorations) {
  505. const Type *type = Type::getStruct(theContext, fieldTypes, decorations);
  506. bool isRegistered = false;
  507. const uint32_t typeId = theContext.getResultIdForType(type, &isRegistered);
  508. theModule.addType(type, typeId);
  509. if (!isRegistered) {
  510. theModule.addDebugName(typeId, structName);
  511. if (!fieldNames.empty()) {
  512. assert(fieldNames.size() == fieldTypes.size());
  513. for (uint32_t i = 0; i < fieldNames.size(); ++i)
  514. theModule.addDebugName(typeId, fieldNames[i],
  515. llvm::Optional<uint32_t>(i));
  516. }
  517. }
  518. return typeId;
  519. }
  520. uint32_t ModuleBuilder::getArrayType(uint32_t elemType, uint32_t count,
  521. Type::DecorationSet decorations) {
  522. const Type *type = Type::getArray(theContext, elemType, count, decorations);
  523. const uint32_t typeId = theContext.getResultIdForType(type);
  524. theModule.addType(type, typeId);
  525. return typeId;
  526. }
  527. uint32_t ModuleBuilder::getRuntimeArrayType(uint32_t elemType,
  528. Type::DecorationSet decorations) {
  529. const Type *type = Type::getRuntimeArray(theContext, elemType, decorations);
  530. const uint32_t typeId = theContext.getResultIdForType(type);
  531. theModule.addType(type, typeId);
  532. return typeId;
  533. }
  534. uint32_t ModuleBuilder::getFunctionType(uint32_t returnType,
  535. llvm::ArrayRef<uint32_t> paramTypes) {
  536. const Type *type = Type::getFunction(theContext, returnType, paramTypes);
  537. const uint32_t typeId = theContext.getResultIdForType(type);
  538. theModule.addType(type, typeId);
  539. return typeId;
  540. }
  541. uint32_t ModuleBuilder::getImageType(uint32_t sampledType, spv::Dim dim,
  542. uint32_t depth, bool isArray, uint32_t ms,
  543. uint32_t sampled,
  544. spv::ImageFormat format) {
  545. const Type *type = Type::getImage(theContext, sampledType, dim, depth,
  546. isArray, ms, sampled, format);
  547. bool isRegistered = false;
  548. const uint32_t typeId = theContext.getResultIdForType(type, &isRegistered);
  549. theModule.addType(type, typeId);
  550. switch (format) {
  551. case spv::ImageFormat::Rg32f:
  552. case spv::ImageFormat::Rg16f:
  553. case spv::ImageFormat::R11fG11fB10f:
  554. case spv::ImageFormat::R16f:
  555. case spv::ImageFormat::Rgba16:
  556. case spv::ImageFormat::Rgb10A2:
  557. case spv::ImageFormat::Rg16:
  558. case spv::ImageFormat::Rg8:
  559. case spv::ImageFormat::R16:
  560. case spv::ImageFormat::R8:
  561. case spv::ImageFormat::Rgba16Snorm:
  562. case spv::ImageFormat::Rg16Snorm:
  563. case spv::ImageFormat::Rg8Snorm:
  564. case spv::ImageFormat::R16Snorm:
  565. case spv::ImageFormat::R8Snorm:
  566. case spv::ImageFormat::Rg32i:
  567. case spv::ImageFormat::Rg16i:
  568. case spv::ImageFormat::Rg8i:
  569. case spv::ImageFormat::R16i:
  570. case spv::ImageFormat::R8i:
  571. case spv::ImageFormat::Rgb10a2ui:
  572. case spv::ImageFormat::Rg32ui:
  573. case spv::ImageFormat::Rg16ui:
  574. case spv::ImageFormat::Rg8ui:
  575. case spv::ImageFormat::R16ui:
  576. case spv::ImageFormat::R8ui:
  577. requireCapability(spv::Capability::StorageImageExtendedFormats);
  578. }
  579. if (dim == spv::Dim::Buffer)
  580. requireCapability(spv::Capability::SampledBuffer);
  581. // Skip constructing the debug name if we have already done it before.
  582. if (!isRegistered) {
  583. const char *dimStr = "";
  584. switch (dim) {
  585. case spv::Dim::Dim1D:
  586. dimStr = "1d.";
  587. break;
  588. case spv::Dim::Dim2D:
  589. dimStr = "2d.";
  590. break;
  591. case spv::Dim::Dim3D:
  592. dimStr = "3d.";
  593. break;
  594. case spv::Dim::Cube:
  595. dimStr = "cube.";
  596. break;
  597. case spv::Dim::Rect:
  598. dimStr = "rect.";
  599. break;
  600. case spv::Dim::Buffer:
  601. dimStr = "buffer.";
  602. break;
  603. case spv::Dim::SubpassData:
  604. dimStr = "subpass.";
  605. break;
  606. default:
  607. break;
  608. }
  609. std::string name =
  610. std::string("type.") + dimStr + "image" + (isArray ? ".array" : "");
  611. theModule.addDebugName(typeId, name);
  612. }
  613. return typeId;
  614. }
  615. uint32_t ModuleBuilder::getSamplerType() {
  616. const Type *type = Type::getSampler(theContext);
  617. const uint32_t typeId = theContext.getResultIdForType(type);
  618. theModule.addType(type, typeId);
  619. theModule.addDebugName(typeId, "type.sampler");
  620. return typeId;
  621. }
  622. uint32_t ModuleBuilder::getSampledImageType(uint32_t imageType) {
  623. const Type *type = Type::getSampledImage(theContext, imageType);
  624. const uint32_t typeId = theContext.getResultIdForType(type);
  625. theModule.addType(type, typeId);
  626. theModule.addDebugName(typeId, "type.sampled.image");
  627. return typeId;
  628. }
  629. uint32_t ModuleBuilder::getByteAddressBufferType(bool isRW) {
  630. // Create a uint RuntimeArray with Array Stride of 4.
  631. const uint32_t uintType = getUint32Type();
  632. const auto *arrStride4 = Decoration::getArrayStride(theContext, 4u);
  633. const Type *raType =
  634. Type::getRuntimeArray(theContext, uintType, {arrStride4});
  635. const uint32_t raTypeId = theContext.getResultIdForType(raType);
  636. theModule.addType(raType, raTypeId);
  637. // Create a struct containing the runtime array as its only member.
  638. // The struct must also be decorated as BufferBlock. The offset decoration
  639. // should also be applied to the first (only) member. NonWritable decoration
  640. // should also be applied to the first member if isRW is true.
  641. llvm::SmallVector<const Decoration *, 3> typeDecs;
  642. typeDecs.push_back(Decoration::getBufferBlock(theContext));
  643. typeDecs.push_back(Decoration::getOffset(theContext, 0, 0));
  644. if (!isRW)
  645. typeDecs.push_back(Decoration::getNonWritable(theContext, 0));
  646. const Type *type = Type::getStruct(theContext, {raTypeId}, typeDecs);
  647. const uint32_t typeId = theContext.getResultIdForType(type);
  648. theModule.addType(type, typeId);
  649. theModule.addDebugName(
  650. typeId, isRW ? "type.RWByteAddressBuffer" : "type.ByteAddressBuffer");
  651. return typeId;
  652. }
  653. uint32_t ModuleBuilder::getConstantBool(bool value) {
  654. const uint32_t typeId = getBoolType();
  655. const Constant *constant = value ? Constant::getTrue(theContext, typeId)
  656. : Constant::getFalse(theContext, typeId);
  657. const uint32_t constId = theContext.getResultIdForConstant(constant);
  658. theModule.addConstant(constant, constId);
  659. return constId;
  660. }
  661. #define IMPL_GET_PRIMITIVE_CONST(builderTy, cppTy) \
  662. \
  663. uint32_t ModuleBuilder::getConstant##builderTy(cppTy value) { \
  664. const uint32_t typeId = get##builderTy##Type(); \
  665. const Constant *constant = \
  666. Constant::get##builderTy(theContext, typeId, value); \
  667. const uint32_t constId = theContext.getResultIdForConstant(constant); \
  668. theModule.addConstant(constant, constId); \
  669. return constId; \
  670. \
  671. }
  672. IMPL_GET_PRIMITIVE_CONST(Int32, int32_t)
  673. IMPL_GET_PRIMITIVE_CONST(Uint32, uint32_t)
  674. IMPL_GET_PRIMITIVE_CONST(Float32, float)
  675. #undef IMPL_GET_PRIMITIVE_VALUE
  676. uint32_t
  677. ModuleBuilder::getConstantComposite(uint32_t typeId,
  678. llvm::ArrayRef<uint32_t> constituents) {
  679. const Constant *constant =
  680. Constant::getComposite(theContext, typeId, constituents);
  681. const uint32_t constId = theContext.getResultIdForConstant(constant);
  682. theModule.addConstant(constant, constId);
  683. return constId;
  684. }
  685. uint32_t ModuleBuilder::getConstantNull(uint32_t typeId) {
  686. const Constant *constant = Constant::getNull(theContext, typeId);
  687. const uint32_t constId = theContext.getResultIdForConstant(constant);
  688. theModule.addConstant(constant, constId);
  689. return constId;
  690. }
  691. BasicBlock *ModuleBuilder::getBasicBlock(uint32_t labelId) {
  692. auto it = basicBlocks.find(labelId);
  693. if (it == basicBlocks.end()) {
  694. assert(false && "invalid <label-id>");
  695. return nullptr;
  696. }
  697. return it->second.get();
  698. }
  699. } // end namespace spirv
  700. } // end namespace clang