ModuleBuilder.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  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 "TypeTranslator.h"
  11. #include "spirv/unified1//spirv.hpp11"
  12. #include "clang/SPIRV/BitwiseCast.h"
  13. #include "clang/SPIRV/InstBuilder.h"
  14. #include "llvm/llvm_assert/assert.h"
  15. namespace clang {
  16. namespace spirv {
  17. ModuleBuilder::ModuleBuilder(SPIRVContext *C, FeatureManager *features,
  18. bool reflect)
  19. : theContext(*C), featureManager(features), allowReflect(reflect),
  20. theModule(), theFunction(nullptr), insertPoint(nullptr),
  21. instBuilder(nullptr), glslExtSetId(0) {
  22. instBuilder.setConsumer([this](std::vector<uint32_t> &&words) {
  23. this->constructSite = std::move(words);
  24. });
  25. // Set the SPIR-V version if needed.
  26. if (featureManager && featureManager->getTargetEnv() == SPV_ENV_VULKAN_1_1)
  27. theModule.setVersion(0x00010300);
  28. }
  29. std::vector<uint32_t> ModuleBuilder::takeModule() {
  30. theModule.setBound(theContext.getNextId());
  31. std::vector<uint32_t> binary;
  32. auto ib = InstBuilder([&binary](std::vector<uint32_t> &&words) {
  33. binary.insert(binary.end(), words.begin(), words.end());
  34. });
  35. theModule.take(&ib);
  36. return binary;
  37. }
  38. uint32_t ModuleBuilder::beginFunction(uint32_t funcType, uint32_t returnType,
  39. llvm::StringRef funcName, uint32_t fId) {
  40. if (theFunction) {
  41. assert(false && "found nested function");
  42. return 0;
  43. }
  44. // If the caller doesn't supply a function <result-id>, we need to get one.
  45. if (!fId)
  46. fId = theContext.takeNextId();
  47. theFunction = llvm::make_unique<Function>(
  48. returnType, fId, spv::FunctionControlMask::MaskNone, funcType);
  49. theModule.addDebugName(fId, funcName);
  50. return fId;
  51. }
  52. uint32_t ModuleBuilder::addFnParam(uint32_t ptrType, llvm::StringRef name) {
  53. assert(theFunction && "found detached parameter");
  54. const uint32_t paramId = theContext.takeNextId();
  55. theFunction->addParameter(ptrType, paramId);
  56. theModule.addDebugName(paramId, name);
  57. return paramId;
  58. }
  59. uint32_t ModuleBuilder::addFnVar(uint32_t varType, llvm::StringRef name,
  60. llvm::Optional<uint32_t> init) {
  61. assert(theFunction && "found detached local variable");
  62. const uint32_t ptrType = getPointerType(varType, spv::StorageClass::Function);
  63. const uint32_t varId = theContext.takeNextId();
  64. theFunction->addVariable(ptrType, varId, init);
  65. theModule.addDebugName(varId, name);
  66. return varId;
  67. }
  68. bool ModuleBuilder::endFunction() {
  69. if (theFunction == nullptr) {
  70. assert(false && "no active function");
  71. return false;
  72. }
  73. // Move all basic blocks into the current function.
  74. // TODO: we should adjust the order the basic blocks according to
  75. // SPIR-V validation rules.
  76. for (auto &bb : basicBlocks) {
  77. theFunction->addBasicBlock(std::move(bb.second));
  78. }
  79. basicBlocks.clear();
  80. theModule.addFunction(std::move(theFunction));
  81. theFunction.reset(nullptr);
  82. insertPoint = nullptr;
  83. return true;
  84. }
  85. uint32_t ModuleBuilder::createBasicBlock(llvm::StringRef name) {
  86. if (theFunction == nullptr) {
  87. assert(false && "found detached basic block");
  88. return 0;
  89. }
  90. const uint32_t labelId = theContext.takeNextId();
  91. basicBlocks[labelId] = llvm::make_unique<BasicBlock>(labelId, name);
  92. return labelId;
  93. }
  94. void ModuleBuilder::addSuccessor(uint32_t successorLabel) {
  95. assert(insertPoint && "null insert point");
  96. insertPoint->addSuccessor(getBasicBlock(successorLabel));
  97. }
  98. void ModuleBuilder::setMergeTarget(uint32_t mergeLabel) {
  99. assert(insertPoint && "null insert point");
  100. insertPoint->setMergeTarget(getBasicBlock(mergeLabel));
  101. }
  102. void ModuleBuilder::setContinueTarget(uint32_t continueLabel) {
  103. assert(insertPoint && "null insert point");
  104. insertPoint->setContinueTarget(getBasicBlock(continueLabel));
  105. }
  106. void ModuleBuilder::setInsertPoint(uint32_t labelId) {
  107. insertPoint = getBasicBlock(labelId);
  108. }
  109. uint32_t
  110. ModuleBuilder::createCompositeConstruct(uint32_t resultType,
  111. llvm::ArrayRef<uint32_t> constituents) {
  112. assert(insertPoint && "null insert point");
  113. const uint32_t resultId = theContext.takeNextId();
  114. instBuilder.opCompositeConstruct(resultType, resultId, constituents).x();
  115. insertPoint->appendInstruction(std::move(constructSite));
  116. return resultId;
  117. }
  118. uint32_t
  119. ModuleBuilder::createCompositeExtract(uint32_t resultType, uint32_t composite,
  120. llvm::ArrayRef<uint32_t> indexes) {
  121. assert(insertPoint && "null insert point");
  122. const uint32_t resultId = theContext.takeNextId();
  123. instBuilder.opCompositeExtract(resultType, resultId, composite, indexes).x();
  124. insertPoint->appendInstruction(std::move(constructSite));
  125. return resultId;
  126. }
  127. uint32_t ModuleBuilder::createCompositeInsert(uint32_t resultType,
  128. uint32_t composite,
  129. llvm::ArrayRef<uint32_t> indices,
  130. uint32_t object) {
  131. assert(insertPoint && "null insert point");
  132. const uint32_t resultId = theContext.takeNextId();
  133. instBuilder
  134. .opCompositeInsert(resultType, resultId, object, composite, indices)
  135. .x();
  136. insertPoint->appendInstruction(std::move(constructSite));
  137. return resultId;
  138. }
  139. uint32_t
  140. ModuleBuilder::createVectorShuffle(uint32_t resultType, uint32_t vector1,
  141. uint32_t vector2,
  142. llvm::ArrayRef<uint32_t> selectors) {
  143. assert(insertPoint && "null insert point");
  144. const uint32_t resultId = theContext.takeNextId();
  145. instBuilder.opVectorShuffle(resultType, resultId, vector1, vector2, selectors)
  146. .x();
  147. insertPoint->appendInstruction(std::move(constructSite));
  148. return resultId;
  149. }
  150. uint32_t ModuleBuilder::createLoad(uint32_t resultType, uint32_t pointer) {
  151. assert(insertPoint && "null insert point");
  152. const uint32_t resultId = theContext.takeNextId();
  153. instBuilder.opLoad(resultType, resultId, pointer, llvm::None).x();
  154. insertPoint->appendInstruction(std::move(constructSite));
  155. return resultId;
  156. }
  157. void ModuleBuilder::createStore(uint32_t address, uint32_t value) {
  158. assert(insertPoint && "null insert point");
  159. instBuilder.opStore(address, value, llvm::None).x();
  160. insertPoint->appendInstruction(std::move(constructSite));
  161. }
  162. uint32_t ModuleBuilder::createFunctionCall(uint32_t returnType,
  163. uint32_t functionId,
  164. llvm::ArrayRef<uint32_t> params) {
  165. assert(insertPoint && "null insert point");
  166. const uint32_t id = theContext.takeNextId();
  167. instBuilder.opFunctionCall(returnType, id, functionId, params).x();
  168. insertPoint->appendInstruction(std::move(constructSite));
  169. return id;
  170. }
  171. uint32_t ModuleBuilder::createAccessChain(uint32_t resultType, uint32_t base,
  172. llvm::ArrayRef<uint32_t> indexes) {
  173. assert(insertPoint && "null insert point");
  174. const uint32_t id = theContext.takeNextId();
  175. instBuilder.opAccessChain(resultType, id, base, indexes).x();
  176. insertPoint->appendInstruction(std::move(constructSite));
  177. return id;
  178. }
  179. uint32_t ModuleBuilder::createUnaryOp(spv::Op op, uint32_t resultType,
  180. uint32_t operand) {
  181. assert(insertPoint && "null insert point");
  182. const uint32_t id = theContext.takeNextId();
  183. instBuilder.unaryOp(op, resultType, id, operand).x();
  184. insertPoint->appendInstruction(std::move(constructSite));
  185. switch (op) {
  186. case spv::Op::OpImageQuerySize:
  187. case spv::Op::OpImageQueryLevels:
  188. case spv::Op::OpImageQuerySamples:
  189. requireCapability(spv::Capability::ImageQuery);
  190. break;
  191. }
  192. return id;
  193. }
  194. uint32_t ModuleBuilder::createBinaryOp(spv::Op op, uint32_t resultType,
  195. uint32_t lhs, uint32_t rhs) {
  196. assert(insertPoint && "null insert point");
  197. const uint32_t id = theContext.takeNextId();
  198. instBuilder.binaryOp(op, resultType, id, lhs, rhs).x();
  199. insertPoint->appendInstruction(std::move(constructSite));
  200. switch (op) {
  201. case spv::Op::OpImageQueryLod:
  202. case spv::Op::OpImageQuerySizeLod:
  203. requireCapability(spv::Capability::ImageQuery);
  204. break;
  205. }
  206. return id;
  207. }
  208. uint32_t ModuleBuilder::createSpecConstantBinaryOp(spv::Op op,
  209. uint32_t resultType,
  210. uint32_t lhs, uint32_t rhs) {
  211. const uint32_t id = theContext.takeNextId();
  212. instBuilder.specConstantBinaryOp(op, resultType, id, lhs, rhs).x();
  213. theModule.addVariable(std::move(constructSite));
  214. return id;
  215. }
  216. uint32_t ModuleBuilder::createGroupNonUniformOp(spv::Op op, uint32_t resultType,
  217. uint32_t execScope) {
  218. assert(insertPoint && "null insert point");
  219. const uint32_t id = theContext.takeNextId();
  220. instBuilder.groupNonUniformOp(op, resultType, id, execScope).x();
  221. insertPoint->appendInstruction(std::move(constructSite));
  222. return id;
  223. }
  224. uint32_t ModuleBuilder::createGroupNonUniformUnaryOp(
  225. spv::Op op, uint32_t resultType, uint32_t execScope, uint32_t operand,
  226. llvm::Optional<spv::GroupOperation> groupOp) {
  227. assert(insertPoint && "null insert point");
  228. const uint32_t id = theContext.takeNextId();
  229. instBuilder
  230. .groupNonUniformUnaryOp(op, resultType, id, execScope, groupOp, operand)
  231. .x();
  232. insertPoint->appendInstruction(std::move(constructSite));
  233. return id;
  234. }
  235. uint32_t ModuleBuilder::createGroupNonUniformBinaryOp(spv::Op op,
  236. uint32_t resultType,
  237. uint32_t execScope,
  238. uint32_t operand1,
  239. uint32_t operand2) {
  240. assert(insertPoint && "null insert point");
  241. const uint32_t id = theContext.takeNextId();
  242. instBuilder
  243. .groupNonUniformBinaryOp(op, resultType, id, execScope, operand1,
  244. operand2)
  245. .x();
  246. insertPoint->appendInstruction(std::move(constructSite));
  247. return id;
  248. }
  249. uint32_t ModuleBuilder::createAtomicOp(spv::Op opcode, uint32_t resultType,
  250. uint32_t orignalValuePtr,
  251. uint32_t scopeId,
  252. uint32_t memorySemanticsId,
  253. uint32_t valueToOp) {
  254. assert(insertPoint && "null insert point");
  255. const uint32_t id = theContext.takeNextId();
  256. switch (opcode) {
  257. case spv::Op::OpAtomicIAdd:
  258. instBuilder.opAtomicIAdd(resultType, id, orignalValuePtr, scopeId,
  259. memorySemanticsId, valueToOp);
  260. break;
  261. case spv::Op::OpAtomicISub:
  262. instBuilder.opAtomicISub(resultType, id, orignalValuePtr, scopeId,
  263. memorySemanticsId, valueToOp);
  264. break;
  265. case spv::Op::OpAtomicAnd:
  266. instBuilder.opAtomicAnd(resultType, id, orignalValuePtr, scopeId,
  267. memorySemanticsId, valueToOp);
  268. break;
  269. case spv::Op::OpAtomicOr:
  270. instBuilder.opAtomicOr(resultType, id, orignalValuePtr, scopeId,
  271. memorySemanticsId, valueToOp);
  272. break;
  273. case spv::Op::OpAtomicXor:
  274. instBuilder.opAtomicXor(resultType, id, orignalValuePtr, scopeId,
  275. memorySemanticsId, valueToOp);
  276. break;
  277. case spv::Op::OpAtomicUMax:
  278. instBuilder.opAtomicUMax(resultType, id, orignalValuePtr, scopeId,
  279. memorySemanticsId, valueToOp);
  280. break;
  281. case spv::Op::OpAtomicUMin:
  282. instBuilder.opAtomicUMin(resultType, id, orignalValuePtr, scopeId,
  283. memorySemanticsId, valueToOp);
  284. break;
  285. case spv::Op::OpAtomicSMax:
  286. instBuilder.opAtomicSMax(resultType, id, orignalValuePtr, scopeId,
  287. memorySemanticsId, valueToOp);
  288. break;
  289. case spv::Op::OpAtomicSMin:
  290. instBuilder.opAtomicSMin(resultType, id, orignalValuePtr, scopeId,
  291. memorySemanticsId, valueToOp);
  292. break;
  293. case spv::Op::OpAtomicExchange:
  294. instBuilder.opAtomicExchange(resultType, id, orignalValuePtr, scopeId,
  295. memorySemanticsId, valueToOp);
  296. break;
  297. default:
  298. assert(false && "unimplemented atomic opcode");
  299. }
  300. instBuilder.x();
  301. insertPoint->appendInstruction(std::move(constructSite));
  302. return id;
  303. }
  304. uint32_t ModuleBuilder::createAtomicCompareExchange(
  305. uint32_t resultType, uint32_t orignalValuePtr, uint32_t scopeId,
  306. uint32_t equalMemorySemanticsId, uint32_t unequalMemorySemanticsId,
  307. uint32_t valueToOp, uint32_t comparator) {
  308. assert(insertPoint && "null insert point");
  309. const uint32_t id = theContext.takeNextId();
  310. instBuilder.opAtomicCompareExchange(
  311. resultType, id, orignalValuePtr, scopeId, equalMemorySemanticsId,
  312. unequalMemorySemanticsId, valueToOp, comparator);
  313. instBuilder.x();
  314. insertPoint->appendInstruction(std::move(constructSite));
  315. return id;
  316. }
  317. spv::ImageOperandsMask ModuleBuilder::composeImageOperandsMask(
  318. uint32_t bias, uint32_t lod, const std::pair<uint32_t, uint32_t> &grad,
  319. uint32_t constOffset, uint32_t varOffset, uint32_t constOffsets,
  320. uint32_t sample, uint32_t minLod,
  321. llvm::SmallVectorImpl<uint32_t> *orderedParams) {
  322. using spv::ImageOperandsMask;
  323. // SPIR-V Image Operands from least significant bit to most significant bit
  324. // Bias, Lod, Grad, ConstOffset, Offset, ConstOffsets, Sample, MinLod
  325. auto mask = ImageOperandsMask::MaskNone;
  326. orderedParams->clear();
  327. if (bias) {
  328. mask = mask | ImageOperandsMask::Bias;
  329. orderedParams->push_back(bias);
  330. }
  331. if (lod) {
  332. mask = mask | ImageOperandsMask::Lod;
  333. orderedParams->push_back(lod);
  334. }
  335. if (grad.first && grad.second) {
  336. mask = mask | ImageOperandsMask::Grad;
  337. orderedParams->push_back(grad.first);
  338. orderedParams->push_back(grad.second);
  339. }
  340. if (constOffset) {
  341. mask = mask | ImageOperandsMask::ConstOffset;
  342. orderedParams->push_back(constOffset);
  343. }
  344. if (varOffset) {
  345. mask = mask | ImageOperandsMask::Offset;
  346. requireCapability(spv::Capability::ImageGatherExtended);
  347. orderedParams->push_back(varOffset);
  348. }
  349. if (constOffsets) {
  350. mask = mask | ImageOperandsMask::ConstOffsets;
  351. orderedParams->push_back(constOffsets);
  352. }
  353. if (sample) {
  354. mask = mask | ImageOperandsMask::Sample;
  355. orderedParams->push_back(sample);
  356. }
  357. if (minLod) {
  358. requireCapability(spv::Capability::MinLod);
  359. mask = mask | ImageOperandsMask::MinLod;
  360. orderedParams->push_back(minLod);
  361. }
  362. return mask;
  363. }
  364. uint32_t
  365. ModuleBuilder::createImageSparseTexelsResident(uint32_t resident_code) {
  366. assert(insertPoint && "null insert point");
  367. // Result type must be a boolean
  368. const uint32_t result_type = getBoolType();
  369. const uint32_t id = theContext.takeNextId();
  370. instBuilder.opImageSparseTexelsResident(result_type, id, resident_code).x();
  371. insertPoint->appendInstruction(std::move(constructSite));
  372. return id;
  373. }
  374. uint32_t ModuleBuilder::createImageTexelPointer(uint32_t resultType,
  375. uint32_t imageId,
  376. uint32_t coordinate,
  377. uint32_t sample) {
  378. assert(insertPoint && "null insert point");
  379. const uint32_t id = theContext.takeNextId();
  380. instBuilder.opImageTexelPointer(resultType, id, imageId, coordinate, sample)
  381. .x();
  382. insertPoint->appendInstruction(std::move(constructSite));
  383. return id;
  384. }
  385. uint32_t ModuleBuilder::createImageSample(
  386. uint32_t texelType, uint32_t imageType, uint32_t image, uint32_t sampler,
  387. bool isNonUniform, uint32_t coordinate, uint32_t compareVal, uint32_t bias,
  388. uint32_t lod, std::pair<uint32_t, uint32_t> grad, uint32_t constOffset,
  389. uint32_t varOffset, uint32_t constOffsets, uint32_t sample, uint32_t minLod,
  390. uint32_t residencyCodeId) {
  391. assert(insertPoint && "null insert point");
  392. // The Lod and Grad image operands requires explicit-lod instructions.
  393. // Otherwise we use implicit-lod instructions.
  394. const bool isExplicit = lod || (grad.first && grad.second);
  395. const bool isSparse = (residencyCodeId != 0);
  396. // minLod is only valid with Implicit instructions and Grad instructions.
  397. // This means that we cannot have Lod and minLod together because Lod requires
  398. // explicit insturctions. So either lod or minLod or both must be zero.
  399. assert(lod == 0 || minLod == 0);
  400. uint32_t retType = texelType;
  401. if (isSparse) {
  402. requireCapability(spv::Capability::SparseResidency);
  403. retType = getSparseResidencyStructType(texelType);
  404. }
  405. // An OpSampledImage is required to do the image sampling.
  406. const uint32_t sampledImgId = theContext.takeNextId();
  407. const uint32_t sampledImgTy = getSampledImageType(imageType);
  408. instBuilder.opSampledImage(sampledImgTy, sampledImgId, image, sampler).x();
  409. insertPoint->appendInstruction(std::move(constructSite));
  410. if (isNonUniform) {
  411. // The sampled image will be used to access resource's memory, so we need
  412. // to decorate it with NonUniformEXT.
  413. decorate(sampledImgId, spv::Decoration::NonUniformEXT);
  414. }
  415. uint32_t texelId = theContext.takeNextId();
  416. llvm::SmallVector<uint32_t, 4> params;
  417. const auto mask =
  418. composeImageOperandsMask(bias, lod, grad, constOffset, varOffset,
  419. constOffsets, sample, minLod, &params);
  420. instBuilder.opImageSample(retType, texelId, sampledImgId, coordinate,
  421. compareVal, mask, isExplicit, isSparse);
  422. for (const auto param : params)
  423. instBuilder.idRef(param);
  424. instBuilder.x();
  425. insertPoint->appendInstruction(std::move(constructSite));
  426. if (isSparse) {
  427. // Write the Residency Code
  428. const auto status = createCompositeExtract(getUint32Type(), texelId, {0});
  429. createStore(residencyCodeId, status);
  430. // Extract the real result from the struct
  431. texelId = createCompositeExtract(texelType, texelId, {1});
  432. }
  433. return texelId;
  434. }
  435. void ModuleBuilder::createImageWrite(QualType imageType, uint32_t imageId,
  436. uint32_t coordId, uint32_t texelId) {
  437. assert(insertPoint && "null insert point");
  438. requireCapability(
  439. TypeTranslator::getCapabilityForStorageImageReadWrite(imageType));
  440. instBuilder.opImageWrite(imageId, coordId, texelId, llvm::None).x();
  441. insertPoint->appendInstruction(std::move(constructSite));
  442. }
  443. uint32_t ModuleBuilder::createImageFetchOrRead(
  444. bool doImageFetch, uint32_t texelType, QualType imageType, uint32_t image,
  445. uint32_t coordinate, uint32_t lod, uint32_t constOffset, uint32_t varOffset,
  446. uint32_t constOffsets, uint32_t sample, uint32_t residencyCodeId) {
  447. assert(insertPoint && "null insert point");
  448. llvm::SmallVector<uint32_t, 2> params;
  449. const auto mask =
  450. llvm::Optional<spv::ImageOperandsMask>(composeImageOperandsMask(
  451. /*bias*/ 0, lod, std::make_pair(0, 0), constOffset, varOffset,
  452. constOffsets, sample, /*minLod*/ 0, &params));
  453. const bool isSparse = (residencyCodeId != 0);
  454. uint32_t retType = texelType;
  455. if (isSparse) {
  456. requireCapability(spv::Capability::SparseResidency);
  457. retType = getSparseResidencyStructType(texelType);
  458. }
  459. if (!doImageFetch) {
  460. requireCapability(
  461. TypeTranslator::getCapabilityForStorageImageReadWrite(imageType));
  462. }
  463. uint32_t texelId = theContext.takeNextId();
  464. instBuilder.opImageFetchRead(retType, texelId, image, coordinate, mask,
  465. doImageFetch, isSparse);
  466. for (const auto param : params)
  467. instBuilder.idRef(param);
  468. instBuilder.x();
  469. insertPoint->appendInstruction(std::move(constructSite));
  470. if (isSparse) {
  471. // Write the Residency Code
  472. const auto status = createCompositeExtract(getUint32Type(), texelId, {0});
  473. createStore(residencyCodeId, status);
  474. // Extract the real result from the struct
  475. texelId = createCompositeExtract(texelType, texelId, {1});
  476. }
  477. return texelId;
  478. }
  479. uint32_t ModuleBuilder::createImageGather(
  480. uint32_t texelType, uint32_t imageType, uint32_t image, uint32_t sampler,
  481. bool isNonUniform, uint32_t coordinate, uint32_t component,
  482. uint32_t compareVal, uint32_t constOffset, uint32_t varOffset,
  483. uint32_t constOffsets, uint32_t sample, uint32_t residencyCodeId) {
  484. assert(insertPoint && "null insert point");
  485. uint32_t sparseRetType = 0;
  486. if (residencyCodeId) {
  487. requireCapability(spv::Capability::SparseResidency);
  488. sparseRetType = getSparseResidencyStructType(texelType);
  489. }
  490. // An OpSampledImage is required to do the image sampling.
  491. const uint32_t sampledImgId = theContext.takeNextId();
  492. const uint32_t sampledImgTy = getSampledImageType(imageType);
  493. instBuilder.opSampledImage(sampledImgTy, sampledImgId, image, sampler).x();
  494. insertPoint->appendInstruction(std::move(constructSite));
  495. if (isNonUniform) {
  496. // The sampled image will be used to access resource's memory, so we need
  497. // to decorate it with NonUniformEXT.
  498. decorate(sampledImgId, spv::Decoration::NonUniformEXT);
  499. }
  500. llvm::SmallVector<uint32_t, 2> params;
  501. // TODO: Update ImageGather to accept minLod if necessary.
  502. const auto mask =
  503. llvm::Optional<spv::ImageOperandsMask>(composeImageOperandsMask(
  504. /*bias*/ 0, /*lod*/ 0, std::make_pair(0, 0), constOffset, varOffset,
  505. constOffsets, sample, /*minLod*/ 0, &params));
  506. uint32_t texelId = theContext.takeNextId();
  507. if (compareVal) {
  508. if (residencyCodeId) {
  509. // Note: OpImageSparseDrefGather does not take the component parameter.
  510. instBuilder.opImageSparseDrefGather(sparseRetType, texelId, sampledImgId,
  511. coordinate, compareVal, mask);
  512. } else {
  513. // Note: OpImageDrefGather does not take the component parameter.
  514. instBuilder.opImageDrefGather(texelType, texelId, sampledImgId,
  515. coordinate, compareVal, mask);
  516. }
  517. } else {
  518. if (residencyCodeId) {
  519. instBuilder.opImageSparseGather(sparseRetType, texelId, sampledImgId,
  520. coordinate, component, mask);
  521. } else {
  522. instBuilder.opImageGather(texelType, texelId, sampledImgId, coordinate,
  523. component, mask);
  524. }
  525. }
  526. for (const auto param : params)
  527. instBuilder.idRef(param);
  528. instBuilder.x();
  529. insertPoint->appendInstruction(std::move(constructSite));
  530. if (residencyCodeId) {
  531. // Write the Residency Code
  532. const auto status = createCompositeExtract(getUint32Type(), texelId, {0});
  533. createStore(residencyCodeId, status);
  534. // Extract the real result from the struct
  535. texelId = createCompositeExtract(texelType, texelId, {1});
  536. }
  537. return texelId;
  538. }
  539. uint32_t ModuleBuilder::createSelect(uint32_t resultType, uint32_t condition,
  540. uint32_t trueValue, uint32_t falseValue) {
  541. assert(insertPoint && "null insert point");
  542. const uint32_t id = theContext.takeNextId();
  543. instBuilder.opSelect(resultType, id, condition, trueValue, falseValue).x();
  544. insertPoint->appendInstruction(std::move(constructSite));
  545. return id;
  546. }
  547. void ModuleBuilder::createSwitch(
  548. uint32_t mergeLabel, uint32_t selector, uint32_t defaultLabel,
  549. llvm::ArrayRef<std::pair<uint32_t, uint32_t>> target) {
  550. assert(insertPoint && "null insert point");
  551. // Create the OpSelectioMerege.
  552. instBuilder.opSelectionMerge(mergeLabel, spv::SelectionControlMask::MaskNone)
  553. .x();
  554. insertPoint->appendInstruction(std::move(constructSite));
  555. // Create the OpSwitch.
  556. instBuilder.opSwitch(selector, defaultLabel, target).x();
  557. insertPoint->appendInstruction(std::move(constructSite));
  558. }
  559. void ModuleBuilder::createKill() {
  560. assert(insertPoint && "null insert point");
  561. assert(!isCurrentBasicBlockTerminated());
  562. instBuilder.opKill().x();
  563. insertPoint->appendInstruction(std::move(constructSite));
  564. }
  565. void ModuleBuilder::createBranch(uint32_t targetLabel, uint32_t mergeBB,
  566. uint32_t continueBB,
  567. spv::LoopControlMask loopControl) {
  568. assert(insertPoint && "null insert point");
  569. if (mergeBB && continueBB) {
  570. instBuilder.opLoopMerge(mergeBB, continueBB, loopControl).x();
  571. insertPoint->appendInstruction(std::move(constructSite));
  572. }
  573. instBuilder.opBranch(targetLabel).x();
  574. insertPoint->appendInstruction(std::move(constructSite));
  575. }
  576. void ModuleBuilder::createConditionalBranch(
  577. uint32_t condition, uint32_t trueLabel, uint32_t falseLabel,
  578. uint32_t mergeLabel, uint32_t continueLabel,
  579. spv::SelectionControlMask selectionControl,
  580. spv::LoopControlMask loopControl) {
  581. assert(insertPoint && "null insert point");
  582. if (mergeLabel) {
  583. if (continueLabel) {
  584. instBuilder.opLoopMerge(mergeLabel, continueLabel, loopControl).x();
  585. insertPoint->appendInstruction(std::move(constructSite));
  586. } else {
  587. instBuilder.opSelectionMerge(mergeLabel, selectionControl).x();
  588. insertPoint->appendInstruction(std::move(constructSite));
  589. }
  590. }
  591. instBuilder.opBranchConditional(condition, trueLabel, falseLabel, {}).x();
  592. insertPoint->appendInstruction(std::move(constructSite));
  593. }
  594. void ModuleBuilder::createReturn() {
  595. assert(insertPoint && "null insert point");
  596. instBuilder.opReturn().x();
  597. insertPoint->appendInstruction(std::move(constructSite));
  598. }
  599. void ModuleBuilder::createReturnValue(uint32_t value) {
  600. assert(insertPoint && "null insert point");
  601. instBuilder.opReturnValue(value).x();
  602. insertPoint->appendInstruction(std::move(constructSite));
  603. }
  604. uint32_t ModuleBuilder::createExtInst(uint32_t resultType, uint32_t setId,
  605. uint32_t instId,
  606. llvm::ArrayRef<uint32_t> operands) {
  607. assert(insertPoint && "null insert point");
  608. uint32_t resultId = theContext.takeNextId();
  609. instBuilder.opExtInst(resultType, resultId, setId, instId, operands).x();
  610. insertPoint->appendInstruction(std::move(constructSite));
  611. return resultId;
  612. }
  613. void ModuleBuilder::createBarrier(uint32_t execution, uint32_t memory,
  614. uint32_t semantics) {
  615. assert(insertPoint && "null insert point");
  616. if (execution)
  617. instBuilder.opControlBarrier(execution, memory, semantics).x();
  618. else
  619. instBuilder.opMemoryBarrier(memory, semantics).x();
  620. insertPoint->appendInstruction(std::move(constructSite));
  621. }
  622. uint32_t ModuleBuilder::createBitFieldExtract(uint32_t resultType,
  623. uint32_t base, uint32_t offset,
  624. uint32_t count, bool isSigned) {
  625. assert(insertPoint && "null insert point");
  626. uint32_t resultId = theContext.takeNextId();
  627. if (isSigned)
  628. instBuilder.opBitFieldSExtract(resultType, resultId, base, offset, count);
  629. else
  630. instBuilder.opBitFieldUExtract(resultType, resultId, base, offset, count);
  631. instBuilder.x();
  632. insertPoint->appendInstruction(std::move(constructSite));
  633. return resultId;
  634. }
  635. uint32_t ModuleBuilder::createBitFieldInsert(uint32_t resultType, uint32_t base,
  636. uint32_t insert, uint32_t offset,
  637. uint32_t count) {
  638. assert(insertPoint && "null insert point");
  639. uint32_t resultId = theContext.takeNextId();
  640. instBuilder
  641. .opBitFieldInsert(resultType, resultId, base, insert, offset, count)
  642. .x();
  643. insertPoint->appendInstruction(std::move(constructSite));
  644. return resultId;
  645. }
  646. void ModuleBuilder::createEmitVertex() {
  647. assert(insertPoint && "null insert point");
  648. instBuilder.opEmitVertex().x();
  649. insertPoint->appendInstruction(std::move(constructSite));
  650. }
  651. void ModuleBuilder::createEndPrimitive() {
  652. assert(insertPoint && "null insert point");
  653. instBuilder.opEndPrimitive().x();
  654. insertPoint->appendInstruction(std::move(constructSite));
  655. }
  656. void ModuleBuilder::addExecutionMode(uint32_t entryPointId,
  657. spv::ExecutionMode em,
  658. llvm::ArrayRef<uint32_t> params) {
  659. instBuilder.opExecutionMode(entryPointId, em);
  660. for (const auto &param : params) {
  661. instBuilder.literalInteger(param);
  662. }
  663. instBuilder.x();
  664. theModule.addExecutionMode(std::move(constructSite));
  665. }
  666. void ModuleBuilder::addExtension(Extension ext, llvm::StringRef target,
  667. SourceLocation srcLoc) {
  668. assert(featureManager);
  669. featureManager->requestExtension(ext, target, srcLoc);
  670. // Do not emit OpExtension if the given extension is natively supported in the
  671. // target environment.
  672. if (featureManager->isExtensionRequiredForTargetEnv(ext))
  673. theModule.addExtension(featureManager->getExtensionName(ext));
  674. }
  675. uint32_t ModuleBuilder::getGLSLExtInstSet() {
  676. if (glslExtSetId == 0) {
  677. glslExtSetId = theContext.takeNextId();
  678. theModule.addExtInstSet(glslExtSetId, "GLSL.std.450");
  679. }
  680. return glslExtSetId;
  681. }
  682. uint32_t ModuleBuilder::addStageIOVar(uint32_t type,
  683. spv::StorageClass storageClass,
  684. std::string name) {
  685. const uint32_t pointerType = getPointerType(type, storageClass);
  686. const uint32_t varId = theContext.takeNextId();
  687. instBuilder.opVariable(pointerType, varId, storageClass, llvm::None).x();
  688. theModule.addVariable(std::move(constructSite));
  689. theModule.addDebugName(varId, name);
  690. return varId;
  691. }
  692. uint32_t ModuleBuilder::addStageBuiltinVar(uint32_t type, spv::StorageClass sc,
  693. spv::BuiltIn builtin) {
  694. const uint32_t pointerType = getPointerType(type, sc);
  695. const uint32_t varId = theContext.takeNextId();
  696. instBuilder.opVariable(pointerType, varId, sc, llvm::None).x();
  697. theModule.addVariable(std::move(constructSite));
  698. // Decorate with the specified Builtin
  699. const Decoration *d = Decoration::getBuiltIn(theContext, builtin);
  700. theModule.addDecoration(d, varId);
  701. return varId;
  702. }
  703. uint32_t ModuleBuilder::addModuleVar(uint32_t type, spv::StorageClass sc,
  704. llvm::StringRef name,
  705. llvm::Optional<uint32_t> init) {
  706. assert(sc != spv::StorageClass::Function);
  707. // TODO: basically duplicated code of addFileVar()
  708. const uint32_t pointerType = getPointerType(type, sc);
  709. const uint32_t varId = theContext.takeNextId();
  710. instBuilder.opVariable(pointerType, varId, sc, init).x();
  711. theModule.addVariable(std::move(constructSite));
  712. theModule.addDebugName(varId, name);
  713. return varId;
  714. }
  715. void ModuleBuilder::decorateDSetBinding(uint32_t targetId, uint32_t setNumber,
  716. uint32_t bindingNumber) {
  717. const auto *d = Decoration::getDescriptorSet(theContext, setNumber);
  718. theModule.addDecoration(d, targetId);
  719. d = Decoration::getBinding(theContext, bindingNumber);
  720. theModule.addDecoration(d, targetId);
  721. }
  722. void ModuleBuilder::decorateInputAttachmentIndex(uint32_t targetId,
  723. uint32_t indexNumber) {
  724. const auto *d = Decoration::getInputAttachmentIndex(theContext, indexNumber);
  725. theModule.addDecoration(d, targetId);
  726. }
  727. void ModuleBuilder::decorateCounterBufferId(uint32_t mainBufferId,
  728. uint32_t counterBufferId) {
  729. if (allowReflect) {
  730. addExtension(Extension::GOOGLE_hlsl_functionality1, "SPIR-V reflection",
  731. {});
  732. theModule.addDecoration(
  733. Decoration::getHlslCounterBufferGOOGLE(theContext, counterBufferId),
  734. mainBufferId);
  735. }
  736. }
  737. void ModuleBuilder::decorateHlslSemantic(uint32_t targetId,
  738. llvm::StringRef semantic,
  739. llvm::Optional<uint32_t> memberIdx) {
  740. if (allowReflect) {
  741. addExtension(Extension::GOOGLE_hlsl_functionality1, "SPIR-V reflection",
  742. {});
  743. theModule.addDecoration(
  744. Decoration::getHlslSemanticGOOGLE(theContext, semantic, memberIdx),
  745. targetId);
  746. }
  747. }
  748. void ModuleBuilder::decorateLocation(uint32_t targetId, uint32_t location) {
  749. const Decoration *d =
  750. Decoration::getLocation(theContext, location, llvm::None);
  751. theModule.addDecoration(d, targetId);
  752. }
  753. void ModuleBuilder::decorateIndex(uint32_t targetId, uint32_t index) {
  754. const Decoration *d = Decoration::getIndex(theContext, index);
  755. theModule.addDecoration(d, targetId);
  756. }
  757. void ModuleBuilder::decorateSpecId(uint32_t targetId, uint32_t specId) {
  758. const Decoration *d = Decoration::getSpecId(theContext, specId);
  759. theModule.addDecoration(d, targetId);
  760. }
  761. void ModuleBuilder::decorate(uint32_t targetId, spv::Decoration decoration) {
  762. const Decoration *d = nullptr;
  763. switch (decoration) {
  764. case spv::Decoration::Centroid:
  765. d = Decoration::getCentroid(theContext);
  766. break;
  767. case spv::Decoration::Flat:
  768. d = Decoration::getFlat(theContext);
  769. break;
  770. case spv::Decoration::NoPerspective:
  771. d = Decoration::getNoPerspective(theContext);
  772. break;
  773. case spv::Decoration::Sample:
  774. d = Decoration::getSample(theContext);
  775. break;
  776. case spv::Decoration::Block:
  777. d = Decoration::getBlock(theContext);
  778. break;
  779. case spv::Decoration::RelaxedPrecision:
  780. d = Decoration::getRelaxedPrecision(theContext);
  781. break;
  782. case spv::Decoration::Patch:
  783. d = Decoration::getPatch(theContext);
  784. break;
  785. case spv::Decoration::NonUniformEXT:
  786. d = Decoration::getNonUniformEXT(theContext);
  787. break;
  788. }
  789. assert(d && "unimplemented decoration");
  790. theModule.addDecoration(d, targetId);
  791. }
  792. #define IMPL_GET_PRIMITIVE_TYPE(ty) \
  793. \
  794. uint32_t ModuleBuilder::get##ty##Type() { \
  795. const Type *type = Type::get##ty(theContext); \
  796. const uint32_t typeId = theContext.getResultIdForType(type); \
  797. theModule.addType(type, typeId); \
  798. return typeId; \
  799. }
  800. IMPL_GET_PRIMITIVE_TYPE(Void)
  801. IMPL_GET_PRIMITIVE_TYPE(Bool)
  802. IMPL_GET_PRIMITIVE_TYPE(Int32)
  803. IMPL_GET_PRIMITIVE_TYPE(Uint32)
  804. IMPL_GET_PRIMITIVE_TYPE(Float32)
  805. #undef IMPL_GET_PRIMITIVE_TYPE
  806. // Note: At the moment, Float16 capability should not be added for Vulkan 1.0.
  807. // It is not a required capability, and adding the SPV_AMD_gpu_half_float does
  808. // not enable this capability. Any driver that supports float16 in Vulkan 1.0
  809. // should accept this extension.
  810. #define IMPL_GET_PRIMITIVE_TYPE_WITH_CAPABILITY(ty, cap) \
  811. \
  812. uint32_t ModuleBuilder::get##ty##Type() { \
  813. if (spv::Capability::cap == spv::Capability::Float16) \
  814. addExtension(Extension::AMD_gpu_shader_half_float, "16-bit float", {}); \
  815. else \
  816. requireCapability(spv::Capability::cap); \
  817. const Type *type = Type::get##ty(theContext); \
  818. const uint32_t typeId = theContext.getResultIdForType(type); \
  819. theModule.addType(type, typeId); \
  820. return typeId; \
  821. }
  822. IMPL_GET_PRIMITIVE_TYPE_WITH_CAPABILITY(Int64, Int64)
  823. IMPL_GET_PRIMITIVE_TYPE_WITH_CAPABILITY(Uint64, Int64)
  824. IMPL_GET_PRIMITIVE_TYPE_WITH_CAPABILITY(Float64, Float64)
  825. IMPL_GET_PRIMITIVE_TYPE_WITH_CAPABILITY(Int16, Int16)
  826. IMPL_GET_PRIMITIVE_TYPE_WITH_CAPABILITY(Uint16, Int16)
  827. IMPL_GET_PRIMITIVE_TYPE_WITH_CAPABILITY(Float16, Float16)
  828. #undef IMPL_GET_PRIMITIVE_TYPE_WITH_CAPABILITY
  829. uint32_t ModuleBuilder::getVecType(uint32_t elemType, uint32_t elemCount) {
  830. const Type *type = nullptr;
  831. switch (elemCount) {
  832. case 2:
  833. type = Type::getVec2(theContext, elemType);
  834. break;
  835. case 3:
  836. type = Type::getVec3(theContext, elemType);
  837. break;
  838. case 4:
  839. type = Type::getVec4(theContext, elemType);
  840. break;
  841. default:
  842. assert(false && "unhandled vector size");
  843. // Error found. Return 0 as the <result-id> directly.
  844. return 0;
  845. }
  846. const uint32_t typeId = theContext.getResultIdForType(type);
  847. theModule.addType(type, typeId);
  848. return typeId;
  849. }
  850. uint32_t ModuleBuilder::getMatType(QualType elemType, uint32_t colType,
  851. uint32_t colCount,
  852. Type::DecorationSet decorations) {
  853. // NOTE: According to Item "Data rules" of SPIR-V Spec 2.16.1 "Universal
  854. // Validation Rules":
  855. // Matrix types can only be parameterized with floating-point types.
  856. //
  857. // So we need special handling of non-fp matrices. We emulate non-fp
  858. // matrices as an array of vectors.
  859. if (!elemType->isFloatingType())
  860. return getArrayType(colType, getConstantUint32(colCount), decorations);
  861. const Type *type = Type::getMatrix(theContext, colType, colCount);
  862. const uint32_t typeId = theContext.getResultIdForType(type);
  863. theModule.addType(type, typeId);
  864. return typeId;
  865. }
  866. uint32_t ModuleBuilder::getPointerType(uint32_t pointeeType,
  867. spv::StorageClass storageClass) {
  868. const Type *type = Type::getPointer(theContext, storageClass, pointeeType);
  869. const uint32_t typeId = theContext.getResultIdForType(type);
  870. theModule.addType(type, typeId);
  871. return typeId;
  872. }
  873. uint32_t
  874. ModuleBuilder::getStructType(llvm::ArrayRef<uint32_t> fieldTypes,
  875. llvm::StringRef structName,
  876. llvm::ArrayRef<llvm::StringRef> fieldNames,
  877. Type::DecorationSet decorations) {
  878. const Type *type = Type::getStruct(theContext, fieldTypes, decorations);
  879. bool isRegistered = false;
  880. const uint32_t typeId = theContext.getResultIdForType(type, &isRegistered);
  881. theModule.addType(type, typeId);
  882. if (!isRegistered) {
  883. theModule.addDebugName(typeId, structName);
  884. if (!fieldNames.empty()) {
  885. assert(fieldNames.size() == fieldTypes.size());
  886. for (uint32_t i = 0; i < fieldNames.size(); ++i)
  887. theModule.addDebugName(typeId, fieldNames[i],
  888. llvm::Optional<uint32_t>(i));
  889. }
  890. }
  891. return typeId;
  892. }
  893. uint32_t ModuleBuilder::getSparseResidencyStructType(uint32_t type) {
  894. const auto uintType = getUint32Type();
  895. return getStructType({uintType, type}, "SparseResidencyStruct",
  896. {"Residency.Code", "Result.Type"});
  897. }
  898. uint32_t ModuleBuilder::getArrayType(uint32_t elemType, uint32_t count,
  899. Type::DecorationSet decorations) {
  900. const Type *type = Type::getArray(theContext, elemType, count, decorations);
  901. const uint32_t typeId = theContext.getResultIdForType(type);
  902. theModule.addType(type, typeId);
  903. return typeId;
  904. }
  905. uint32_t ModuleBuilder::getRuntimeArrayType(uint32_t elemType,
  906. Type::DecorationSet decorations) {
  907. const Type *type = Type::getRuntimeArray(theContext, elemType, decorations);
  908. const uint32_t typeId = theContext.getResultIdForType(type);
  909. theModule.addType(type, typeId);
  910. return typeId;
  911. }
  912. uint32_t ModuleBuilder::getFunctionType(uint32_t returnType,
  913. llvm::ArrayRef<uint32_t> paramTypes) {
  914. const Type *type = Type::getFunction(theContext, returnType, paramTypes);
  915. const uint32_t typeId = theContext.getResultIdForType(type);
  916. theModule.addType(type, typeId);
  917. return typeId;
  918. }
  919. uint32_t ModuleBuilder::getImageType(uint32_t sampledType, spv::Dim dim,
  920. uint32_t depth, bool isArray, uint32_t ms,
  921. uint32_t sampled,
  922. spv::ImageFormat format) {
  923. const Type *type = Type::getImage(theContext, sampledType, dim, depth,
  924. isArray, ms, sampled, format);
  925. bool isRegistered = false;
  926. const uint32_t typeId = theContext.getResultIdForType(type, &isRegistered);
  927. theModule.addType(type, typeId);
  928. switch (format) {
  929. case spv::ImageFormat::Rg32f:
  930. case spv::ImageFormat::Rg16f:
  931. case spv::ImageFormat::R11fG11fB10f:
  932. case spv::ImageFormat::R16f:
  933. case spv::ImageFormat::Rgba16:
  934. case spv::ImageFormat::Rgb10A2:
  935. case spv::ImageFormat::Rg16:
  936. case spv::ImageFormat::Rg8:
  937. case spv::ImageFormat::R16:
  938. case spv::ImageFormat::R8:
  939. case spv::ImageFormat::Rgba16Snorm:
  940. case spv::ImageFormat::Rg16Snorm:
  941. case spv::ImageFormat::Rg8Snorm:
  942. case spv::ImageFormat::R16Snorm:
  943. case spv::ImageFormat::R8Snorm:
  944. case spv::ImageFormat::Rg32i:
  945. case spv::ImageFormat::Rg16i:
  946. case spv::ImageFormat::Rg8i:
  947. case spv::ImageFormat::R16i:
  948. case spv::ImageFormat::R8i:
  949. case spv::ImageFormat::Rgb10a2ui:
  950. case spv::ImageFormat::Rg32ui:
  951. case spv::ImageFormat::Rg16ui:
  952. case spv::ImageFormat::Rg8ui:
  953. case spv::ImageFormat::R16ui:
  954. case spv::ImageFormat::R8ui:
  955. requireCapability(spv::Capability::StorageImageExtendedFormats);
  956. }
  957. if (dim == spv::Dim::Dim1D) {
  958. if (sampled == 2u) {
  959. requireCapability(spv::Capability::Image1D);
  960. } else {
  961. requireCapability(spv::Capability::Sampled1D);
  962. }
  963. } else if (dim == spv::Dim::Buffer) {
  964. requireCapability(spv::Capability::SampledBuffer);
  965. } else if (dim == spv::Dim::SubpassData) {
  966. requireCapability(spv::Capability::InputAttachment);
  967. }
  968. if (isArray && ms) {
  969. requireCapability(spv::Capability::ImageMSArray);
  970. }
  971. // Skip constructing the debug name if we have already done it before.
  972. if (!isRegistered) {
  973. const char *dimStr = "";
  974. switch (dim) {
  975. case spv::Dim::Dim1D:
  976. dimStr = "1d.";
  977. break;
  978. case spv::Dim::Dim2D:
  979. dimStr = "2d.";
  980. break;
  981. case spv::Dim::Dim3D:
  982. dimStr = "3d.";
  983. break;
  984. case spv::Dim::Cube:
  985. dimStr = "cube.";
  986. break;
  987. case spv::Dim::Rect:
  988. dimStr = "rect.";
  989. break;
  990. case spv::Dim::Buffer:
  991. dimStr = "buffer.";
  992. break;
  993. case spv::Dim::SubpassData:
  994. dimStr = "subpass.";
  995. break;
  996. default:
  997. break;
  998. }
  999. std::string name =
  1000. std::string("type.") + dimStr + "image" + (isArray ? ".array" : "");
  1001. theModule.addDebugName(typeId, name);
  1002. }
  1003. return typeId;
  1004. }
  1005. uint32_t ModuleBuilder::getSamplerType() {
  1006. const Type *type = Type::getSampler(theContext);
  1007. const uint32_t typeId = theContext.getResultIdForType(type);
  1008. theModule.addType(type, typeId);
  1009. theModule.addDebugName(typeId, "type.sampler");
  1010. return typeId;
  1011. }
  1012. uint32_t ModuleBuilder::getSampledImageType(uint32_t imageType) {
  1013. const Type *type = Type::getSampledImage(theContext, imageType);
  1014. const uint32_t typeId = theContext.getResultIdForType(type);
  1015. theModule.addType(type, typeId);
  1016. theModule.addDebugName(typeId, "type.sampled.image");
  1017. return typeId;
  1018. }
  1019. uint32_t ModuleBuilder::getByteAddressBufferType(bool isRW) {
  1020. // Create a uint RuntimeArray with Array Stride of 4.
  1021. const uint32_t uintType = getUint32Type();
  1022. const auto *arrStride4 = Decoration::getArrayStride(theContext, 4u);
  1023. const Type *raType =
  1024. Type::getRuntimeArray(theContext, uintType, {arrStride4});
  1025. const uint32_t raTypeId = theContext.getResultIdForType(raType);
  1026. theModule.addType(raType, raTypeId);
  1027. // Create a struct containing the runtime array as its only member.
  1028. // The struct must also be decorated as BufferBlock. The offset decoration
  1029. // should also be applied to the first (only) member. NonWritable decoration
  1030. // should also be applied to the first member if isRW is true.
  1031. llvm::SmallVector<const Decoration *, 3> typeDecs;
  1032. typeDecs.push_back(Decoration::getBufferBlock(theContext));
  1033. typeDecs.push_back(Decoration::getOffset(theContext, 0, 0));
  1034. if (!isRW)
  1035. typeDecs.push_back(Decoration::getNonWritable(theContext, 0));
  1036. const Type *type = Type::getStruct(theContext, {raTypeId}, typeDecs);
  1037. const uint32_t typeId = theContext.getResultIdForType(type);
  1038. theModule.addType(type, typeId);
  1039. theModule.addDebugName(typeId, isRW ? "type.RWByteAddressBuffer"
  1040. : "type.ByteAddressBuffer");
  1041. return typeId;
  1042. }
  1043. uint32_t ModuleBuilder::getConstantBool(bool value, bool isSpecConst) {
  1044. if (isSpecConst) {
  1045. const uint32_t constId = theContext.takeNextId();
  1046. if (value) {
  1047. instBuilder.opSpecConstantTrue(getBoolType(), constId).x();
  1048. } else {
  1049. instBuilder.opSpecConstantFalse(getBoolType(), constId).x();
  1050. }
  1051. theModule.addVariable(std::move(constructSite));
  1052. return constId;
  1053. }
  1054. const uint32_t typeId = getBoolType();
  1055. const Constant *constant = value ? Constant::getTrue(theContext, typeId)
  1056. : Constant::getFalse(theContext, typeId);
  1057. const uint32_t constId = theContext.getResultIdForConstant(constant);
  1058. theModule.addConstant(constant, constId);
  1059. return constId;
  1060. }
  1061. #define IMPL_GET_PRIMITIVE_CONST(builderTy, cppTy) \
  1062. \
  1063. uint32_t ModuleBuilder::getConstant##builderTy(cppTy value) { \
  1064. const uint32_t typeId = get##builderTy##Type(); \
  1065. const Constant *constant = \
  1066. Constant::get##builderTy(theContext, typeId, value); \
  1067. const uint32_t constId = theContext.getResultIdForConstant(constant); \
  1068. theModule.addConstant(constant, constId); \
  1069. return constId; \
  1070. }
  1071. #define IMPL_GET_PRIMITIVE_CONST_SPEC_CONST(builderTy, cppTy) \
  1072. \
  1073. uint32_t ModuleBuilder::getConstant##builderTy(cppTy value, \
  1074. bool isSpecConst) { \
  1075. if (isSpecConst) { \
  1076. const uint32_t constId = theContext.takeNextId(); \
  1077. instBuilder \
  1078. .opSpecConstant(get##builderTy##Type(), constId, \
  1079. cast::BitwiseCast<uint32_t>(value)) \
  1080. .x(); \
  1081. theModule.addVariable(std::move(constructSite)); \
  1082. return constId; \
  1083. } \
  1084. \
  1085. const uint32_t typeId = get##builderTy##Type(); \
  1086. const Constant *constant = \
  1087. Constant::get##builderTy(theContext, typeId, value); \
  1088. const uint32_t constId = theContext.getResultIdForConstant(constant); \
  1089. theModule.addConstant(constant, constId); \
  1090. return constId; \
  1091. }
  1092. IMPL_GET_PRIMITIVE_CONST(Int16, int16_t)
  1093. IMPL_GET_PRIMITIVE_CONST_SPEC_CONST(Int32, int32_t)
  1094. IMPL_GET_PRIMITIVE_CONST(Uint16, uint16_t)
  1095. IMPL_GET_PRIMITIVE_CONST_SPEC_CONST(Uint32, uint32_t)
  1096. IMPL_GET_PRIMITIVE_CONST(Float16, int16_t)
  1097. IMPL_GET_PRIMITIVE_CONST_SPEC_CONST(Float32, float)
  1098. IMPL_GET_PRIMITIVE_CONST(Float64, double)
  1099. IMPL_GET_PRIMITIVE_CONST(Int64, int64_t)
  1100. IMPL_GET_PRIMITIVE_CONST(Uint64, uint64_t)
  1101. #undef IMPL_GET_PRIMITIVE_CONST
  1102. #undef IMPL_GET_PRIMITIVE_CONST_SPEC_CONST
  1103. uint32_t
  1104. ModuleBuilder::getConstantComposite(uint32_t typeId,
  1105. llvm::ArrayRef<uint32_t> constituents) {
  1106. const Constant *constant =
  1107. Constant::getComposite(theContext, typeId, constituents);
  1108. const uint32_t constId = theContext.getResultIdForConstant(constant);
  1109. theModule.addConstant(constant, constId);
  1110. return constId;
  1111. }
  1112. uint32_t ModuleBuilder::getConstantNull(uint32_t typeId) {
  1113. const Constant *constant = Constant::getNull(theContext, typeId);
  1114. const uint32_t constId = theContext.getResultIdForConstant(constant);
  1115. theModule.addConstant(constant, constId);
  1116. return constId;
  1117. }
  1118. BasicBlock *ModuleBuilder::getBasicBlock(uint32_t labelId) {
  1119. auto it = basicBlocks.find(labelId);
  1120. if (it == basicBlocks.end()) {
  1121. assert(false && "invalid <label-id>");
  1122. return nullptr;
  1123. }
  1124. return it->second.get();
  1125. }
  1126. } // end namespace spirv
  1127. } // end namespace clang