ModuleBuilder.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  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. uint32_t coordinate, uint32_t compareVal, uint32_t bias, uint32_t lod,
  388. 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. uint32_t texelId = theContext.takeNextId();
  411. llvm::SmallVector<uint32_t, 4> params;
  412. const auto mask =
  413. composeImageOperandsMask(bias, lod, grad, constOffset, varOffset,
  414. constOffsets, sample, minLod, &params);
  415. instBuilder.opImageSample(retType, texelId, sampledImgId, coordinate,
  416. compareVal, mask, isExplicit, isSparse);
  417. for (const auto param : params)
  418. instBuilder.idRef(param);
  419. instBuilder.x();
  420. insertPoint->appendInstruction(std::move(constructSite));
  421. if (isSparse) {
  422. // Write the Residency Code
  423. const auto status = createCompositeExtract(getUint32Type(), texelId, {0});
  424. createStore(residencyCodeId, status);
  425. // Extract the real result from the struct
  426. texelId = createCompositeExtract(texelType, texelId, {1});
  427. }
  428. return texelId;
  429. }
  430. void ModuleBuilder::createImageWrite(QualType imageType, uint32_t imageId,
  431. uint32_t coordId, uint32_t texelId) {
  432. assert(insertPoint && "null insert point");
  433. requireCapability(
  434. TypeTranslator::getCapabilityForStorageImageReadWrite(imageType));
  435. instBuilder.opImageWrite(imageId, coordId, texelId, llvm::None).x();
  436. insertPoint->appendInstruction(std::move(constructSite));
  437. }
  438. uint32_t ModuleBuilder::createImageFetchOrRead(
  439. bool doImageFetch, uint32_t texelType, QualType imageType, uint32_t image,
  440. uint32_t coordinate, uint32_t lod, uint32_t constOffset, uint32_t varOffset,
  441. uint32_t constOffsets, uint32_t sample, uint32_t residencyCodeId) {
  442. assert(insertPoint && "null insert point");
  443. llvm::SmallVector<uint32_t, 2> params;
  444. const auto mask =
  445. llvm::Optional<spv::ImageOperandsMask>(composeImageOperandsMask(
  446. /*bias*/ 0, lod, std::make_pair(0, 0), constOffset, varOffset,
  447. constOffsets, sample, /*minLod*/ 0, &params));
  448. const bool isSparse = (residencyCodeId != 0);
  449. uint32_t retType = texelType;
  450. if (isSparse) {
  451. requireCapability(spv::Capability::SparseResidency);
  452. retType = getSparseResidencyStructType(texelType);
  453. }
  454. if (!doImageFetch) {
  455. requireCapability(
  456. TypeTranslator::getCapabilityForStorageImageReadWrite(imageType));
  457. }
  458. uint32_t texelId = theContext.takeNextId();
  459. instBuilder.opImageFetchRead(retType, texelId, image, coordinate, mask,
  460. doImageFetch, isSparse);
  461. for (const auto param : params)
  462. instBuilder.idRef(param);
  463. instBuilder.x();
  464. insertPoint->appendInstruction(std::move(constructSite));
  465. if (isSparse) {
  466. // Write the Residency Code
  467. const auto status = createCompositeExtract(getUint32Type(), texelId, {0});
  468. createStore(residencyCodeId, status);
  469. // Extract the real result from the struct
  470. texelId = createCompositeExtract(texelType, texelId, {1});
  471. }
  472. return texelId;
  473. }
  474. uint32_t ModuleBuilder::createImageGather(
  475. uint32_t texelType, uint32_t imageType, uint32_t image, uint32_t sampler,
  476. uint32_t coordinate, uint32_t component, uint32_t compareVal,
  477. uint32_t constOffset, uint32_t varOffset, uint32_t constOffsets,
  478. uint32_t sample, uint32_t residencyCodeId) {
  479. assert(insertPoint && "null insert point");
  480. uint32_t sparseRetType = 0;
  481. if (residencyCodeId) {
  482. requireCapability(spv::Capability::SparseResidency);
  483. sparseRetType = getSparseResidencyStructType(texelType);
  484. }
  485. // An OpSampledImage is required to do the image sampling.
  486. const uint32_t sampledImgId = theContext.takeNextId();
  487. const uint32_t sampledImgTy = getSampledImageType(imageType);
  488. instBuilder.opSampledImage(sampledImgTy, sampledImgId, image, sampler).x();
  489. insertPoint->appendInstruction(std::move(constructSite));
  490. llvm::SmallVector<uint32_t, 2> params;
  491. // TODO: Update ImageGather to accept minLod if necessary.
  492. const auto mask =
  493. llvm::Optional<spv::ImageOperandsMask>(composeImageOperandsMask(
  494. /*bias*/ 0, /*lod*/ 0, std::make_pair(0, 0), constOffset, varOffset,
  495. constOffsets, sample, /*minLod*/ 0, &params));
  496. uint32_t texelId = theContext.takeNextId();
  497. if (compareVal) {
  498. if (residencyCodeId) {
  499. // Note: OpImageSparseDrefGather does not take the component parameter.
  500. instBuilder.opImageSparseDrefGather(sparseRetType, texelId, sampledImgId,
  501. coordinate, compareVal, mask);
  502. } else {
  503. // Note: OpImageDrefGather does not take the component parameter.
  504. instBuilder.opImageDrefGather(texelType, texelId, sampledImgId,
  505. coordinate, compareVal, mask);
  506. }
  507. } else {
  508. if (residencyCodeId) {
  509. instBuilder.opImageSparseGather(sparseRetType, texelId, sampledImgId,
  510. coordinate, component, mask);
  511. } else {
  512. instBuilder.opImageGather(texelType, texelId, sampledImgId, coordinate,
  513. component, mask);
  514. }
  515. }
  516. for (const auto param : params)
  517. instBuilder.idRef(param);
  518. instBuilder.x();
  519. insertPoint->appendInstruction(std::move(constructSite));
  520. if (residencyCodeId) {
  521. // Write the Residency Code
  522. const auto status = createCompositeExtract(getUint32Type(), texelId, {0});
  523. createStore(residencyCodeId, status);
  524. // Extract the real result from the struct
  525. texelId = createCompositeExtract(texelType, texelId, {1});
  526. }
  527. return texelId;
  528. }
  529. uint32_t ModuleBuilder::createSelect(uint32_t resultType, uint32_t condition,
  530. uint32_t trueValue, uint32_t falseValue) {
  531. assert(insertPoint && "null insert point");
  532. const uint32_t id = theContext.takeNextId();
  533. instBuilder.opSelect(resultType, id, condition, trueValue, falseValue).x();
  534. insertPoint->appendInstruction(std::move(constructSite));
  535. return id;
  536. }
  537. void ModuleBuilder::createSwitch(
  538. uint32_t mergeLabel, uint32_t selector, uint32_t defaultLabel,
  539. llvm::ArrayRef<std::pair<uint32_t, uint32_t>> target) {
  540. assert(insertPoint && "null insert point");
  541. // Create the OpSelectioMerege.
  542. instBuilder.opSelectionMerge(mergeLabel, spv::SelectionControlMask::MaskNone)
  543. .x();
  544. insertPoint->appendInstruction(std::move(constructSite));
  545. // Create the OpSwitch.
  546. instBuilder.opSwitch(selector, defaultLabel, target).x();
  547. insertPoint->appendInstruction(std::move(constructSite));
  548. }
  549. void ModuleBuilder::createKill() {
  550. assert(insertPoint && "null insert point");
  551. assert(!isCurrentBasicBlockTerminated());
  552. instBuilder.opKill().x();
  553. insertPoint->appendInstruction(std::move(constructSite));
  554. }
  555. void ModuleBuilder::createBranch(uint32_t targetLabel, uint32_t mergeBB,
  556. uint32_t continueBB,
  557. spv::LoopControlMask loopControl) {
  558. assert(insertPoint && "null insert point");
  559. if (mergeBB && continueBB) {
  560. instBuilder.opLoopMerge(mergeBB, continueBB, loopControl).x();
  561. insertPoint->appendInstruction(std::move(constructSite));
  562. }
  563. instBuilder.opBranch(targetLabel).x();
  564. insertPoint->appendInstruction(std::move(constructSite));
  565. }
  566. void ModuleBuilder::createConditionalBranch(
  567. uint32_t condition, uint32_t trueLabel, uint32_t falseLabel,
  568. uint32_t mergeLabel, uint32_t continueLabel,
  569. spv::SelectionControlMask selectionControl,
  570. spv::LoopControlMask loopControl) {
  571. assert(insertPoint && "null insert point");
  572. if (mergeLabel) {
  573. if (continueLabel) {
  574. instBuilder.opLoopMerge(mergeLabel, continueLabel, loopControl).x();
  575. insertPoint->appendInstruction(std::move(constructSite));
  576. } else {
  577. instBuilder.opSelectionMerge(mergeLabel, selectionControl).x();
  578. insertPoint->appendInstruction(std::move(constructSite));
  579. }
  580. }
  581. instBuilder.opBranchConditional(condition, trueLabel, falseLabel, {}).x();
  582. insertPoint->appendInstruction(std::move(constructSite));
  583. }
  584. void ModuleBuilder::createReturn() {
  585. assert(insertPoint && "null insert point");
  586. instBuilder.opReturn().x();
  587. insertPoint->appendInstruction(std::move(constructSite));
  588. }
  589. void ModuleBuilder::createReturnValue(uint32_t value) {
  590. assert(insertPoint && "null insert point");
  591. instBuilder.opReturnValue(value).x();
  592. insertPoint->appendInstruction(std::move(constructSite));
  593. }
  594. uint32_t ModuleBuilder::createExtInst(uint32_t resultType, uint32_t setId,
  595. uint32_t instId,
  596. llvm::ArrayRef<uint32_t> operands) {
  597. assert(insertPoint && "null insert point");
  598. uint32_t resultId = theContext.takeNextId();
  599. instBuilder.opExtInst(resultType, resultId, setId, instId, operands).x();
  600. insertPoint->appendInstruction(std::move(constructSite));
  601. return resultId;
  602. }
  603. void ModuleBuilder::createBarrier(uint32_t execution, uint32_t memory,
  604. uint32_t semantics) {
  605. assert(insertPoint && "null insert point");
  606. if (execution)
  607. instBuilder.opControlBarrier(execution, memory, semantics).x();
  608. else
  609. instBuilder.opMemoryBarrier(memory, semantics).x();
  610. insertPoint->appendInstruction(std::move(constructSite));
  611. }
  612. uint32_t ModuleBuilder::createBitFieldExtract(uint32_t resultType,
  613. uint32_t base, uint32_t offset,
  614. uint32_t count, bool isSigned) {
  615. assert(insertPoint && "null insert point");
  616. uint32_t resultId = theContext.takeNextId();
  617. if (isSigned)
  618. instBuilder.opBitFieldSExtract(resultType, resultId, base, offset, count);
  619. else
  620. instBuilder.opBitFieldUExtract(resultType, resultId, base, offset, count);
  621. instBuilder.x();
  622. insertPoint->appendInstruction(std::move(constructSite));
  623. return resultId;
  624. }
  625. uint32_t ModuleBuilder::createBitFieldInsert(uint32_t resultType, uint32_t base,
  626. uint32_t insert, uint32_t offset,
  627. uint32_t count) {
  628. assert(insertPoint && "null insert point");
  629. uint32_t resultId = theContext.takeNextId();
  630. instBuilder
  631. .opBitFieldInsert(resultType, resultId, base, insert, offset, count)
  632. .x();
  633. insertPoint->appendInstruction(std::move(constructSite));
  634. return resultId;
  635. }
  636. void ModuleBuilder::createEmitVertex() {
  637. assert(insertPoint && "null insert point");
  638. instBuilder.opEmitVertex().x();
  639. insertPoint->appendInstruction(std::move(constructSite));
  640. }
  641. void ModuleBuilder::createEndPrimitive() {
  642. assert(insertPoint && "null insert point");
  643. instBuilder.opEndPrimitive().x();
  644. insertPoint->appendInstruction(std::move(constructSite));
  645. }
  646. void ModuleBuilder::addExecutionMode(uint32_t entryPointId,
  647. spv::ExecutionMode em,
  648. llvm::ArrayRef<uint32_t> params) {
  649. instBuilder.opExecutionMode(entryPointId, em);
  650. for (const auto &param : params) {
  651. instBuilder.literalInteger(param);
  652. }
  653. instBuilder.x();
  654. theModule.addExecutionMode(std::move(constructSite));
  655. }
  656. void ModuleBuilder::addExtension(Extension ext, llvm::StringRef target,
  657. SourceLocation srcLoc) {
  658. assert(featureManager);
  659. featureManager->requestExtension(ext, target, srcLoc);
  660. // Do not emit OpExtension if the given extension is natively supported in the
  661. // target environment.
  662. if (featureManager->isExtensionRequiredForTargetEnv(ext))
  663. theModule.addExtension(featureManager->getExtensionName(ext));
  664. }
  665. uint32_t ModuleBuilder::getGLSLExtInstSet() {
  666. if (glslExtSetId == 0) {
  667. glslExtSetId = theContext.takeNextId();
  668. theModule.addExtInstSet(glslExtSetId, "GLSL.std.450");
  669. }
  670. return glslExtSetId;
  671. }
  672. uint32_t ModuleBuilder::addStageIOVar(uint32_t type,
  673. spv::StorageClass storageClass,
  674. std::string name) {
  675. const uint32_t pointerType = getPointerType(type, storageClass);
  676. const uint32_t varId = theContext.takeNextId();
  677. instBuilder.opVariable(pointerType, varId, storageClass, llvm::None).x();
  678. theModule.addVariable(std::move(constructSite));
  679. theModule.addDebugName(varId, name);
  680. return varId;
  681. }
  682. uint32_t ModuleBuilder::addStageBuiltinVar(uint32_t type, spv::StorageClass sc,
  683. spv::BuiltIn builtin) {
  684. const uint32_t pointerType = getPointerType(type, sc);
  685. const uint32_t varId = theContext.takeNextId();
  686. instBuilder.opVariable(pointerType, varId, sc, llvm::None).x();
  687. theModule.addVariable(std::move(constructSite));
  688. // Decorate with the specified Builtin
  689. const Decoration *d = Decoration::getBuiltIn(theContext, builtin);
  690. theModule.addDecoration(d, varId);
  691. return varId;
  692. }
  693. uint32_t ModuleBuilder::addModuleVar(uint32_t type, spv::StorageClass sc,
  694. llvm::StringRef name,
  695. llvm::Optional<uint32_t> init) {
  696. assert(sc != spv::StorageClass::Function);
  697. // TODO: basically duplicated code of addFileVar()
  698. const uint32_t pointerType = getPointerType(type, sc);
  699. const uint32_t varId = theContext.takeNextId();
  700. instBuilder.opVariable(pointerType, varId, sc, init).x();
  701. theModule.addVariable(std::move(constructSite));
  702. theModule.addDebugName(varId, name);
  703. return varId;
  704. }
  705. void ModuleBuilder::decorateDSetBinding(uint32_t targetId, uint32_t setNumber,
  706. uint32_t bindingNumber) {
  707. const auto *d = Decoration::getDescriptorSet(theContext, setNumber);
  708. theModule.addDecoration(d, targetId);
  709. d = Decoration::getBinding(theContext, bindingNumber);
  710. theModule.addDecoration(d, targetId);
  711. }
  712. void ModuleBuilder::decorateInputAttachmentIndex(uint32_t targetId,
  713. uint32_t indexNumber) {
  714. const auto *d = Decoration::getInputAttachmentIndex(theContext, indexNumber);
  715. theModule.addDecoration(d, targetId);
  716. }
  717. void ModuleBuilder::decorateCounterBufferId(uint32_t mainBufferId,
  718. uint32_t counterBufferId) {
  719. if (allowReflect) {
  720. addExtension(Extension::GOOGLE_hlsl_functionality1, "SPIR-V reflection",
  721. {});
  722. theModule.addDecoration(
  723. Decoration::getHlslCounterBufferGOOGLE(theContext, counterBufferId),
  724. mainBufferId);
  725. }
  726. }
  727. void ModuleBuilder::decorateHlslSemantic(uint32_t targetId,
  728. llvm::StringRef semantic,
  729. llvm::Optional<uint32_t> memberIdx) {
  730. if (allowReflect) {
  731. addExtension(Extension::GOOGLE_hlsl_functionality1, "SPIR-V reflection",
  732. {});
  733. theModule.addDecoration(
  734. Decoration::getHlslSemanticGOOGLE(theContext, semantic, memberIdx),
  735. targetId);
  736. }
  737. }
  738. void ModuleBuilder::decorateLocation(uint32_t targetId, uint32_t location) {
  739. const Decoration *d =
  740. Decoration::getLocation(theContext, location, llvm::None);
  741. theModule.addDecoration(d, targetId);
  742. }
  743. void ModuleBuilder::decorateSpecId(uint32_t targetId, uint32_t specId) {
  744. const Decoration *d = Decoration::getSpecId(theContext, specId);
  745. theModule.addDecoration(d, targetId);
  746. }
  747. void ModuleBuilder::decorate(uint32_t targetId, spv::Decoration decoration) {
  748. const Decoration *d = nullptr;
  749. switch (decoration) {
  750. case spv::Decoration::Centroid:
  751. d = Decoration::getCentroid(theContext);
  752. break;
  753. case spv::Decoration::Flat:
  754. d = Decoration::getFlat(theContext);
  755. break;
  756. case spv::Decoration::NoPerspective:
  757. d = Decoration::getNoPerspective(theContext);
  758. break;
  759. case spv::Decoration::Sample:
  760. d = Decoration::getSample(theContext);
  761. break;
  762. case spv::Decoration::Block:
  763. d = Decoration::getBlock(theContext);
  764. break;
  765. case spv::Decoration::RelaxedPrecision:
  766. d = Decoration::getRelaxedPrecision(theContext);
  767. break;
  768. case spv::Decoration::Patch:
  769. d = Decoration::getPatch(theContext);
  770. break;
  771. }
  772. assert(d && "unimplemented decoration");
  773. theModule.addDecoration(d, targetId);
  774. }
  775. #define IMPL_GET_PRIMITIVE_TYPE(ty) \
  776. \
  777. uint32_t ModuleBuilder::get##ty##Type() { \
  778. const Type *type = Type::get##ty(theContext); \
  779. const uint32_t typeId = theContext.getResultIdForType(type); \
  780. theModule.addType(type, typeId); \
  781. return typeId; \
  782. }
  783. IMPL_GET_PRIMITIVE_TYPE(Void)
  784. IMPL_GET_PRIMITIVE_TYPE(Bool)
  785. IMPL_GET_PRIMITIVE_TYPE(Int32)
  786. IMPL_GET_PRIMITIVE_TYPE(Uint32)
  787. IMPL_GET_PRIMITIVE_TYPE(Float32)
  788. #undef IMPL_GET_PRIMITIVE_TYPE
  789. // Note: At the moment, Float16 capability should not be added for Vulkan 1.0.
  790. // It is not a required capability, and adding the SPV_AMD_gpu_half_float does
  791. // not enable this capability. Any driver that supports float16 in Vulkan 1.0
  792. // should accept this extension.
  793. #define IMPL_GET_PRIMITIVE_TYPE_WITH_CAPABILITY(ty, cap) \
  794. \
  795. uint32_t ModuleBuilder::get##ty##Type() { \
  796. if (spv::Capability::cap == spv::Capability::Float16) \
  797. addExtension(Extension::AMD_gpu_shader_half_float, "16-bit float", {}); \
  798. else \
  799. requireCapability(spv::Capability::cap); \
  800. const Type *type = Type::get##ty(theContext); \
  801. const uint32_t typeId = theContext.getResultIdForType(type); \
  802. theModule.addType(type, typeId); \
  803. return typeId; \
  804. }
  805. IMPL_GET_PRIMITIVE_TYPE_WITH_CAPABILITY(Int64, Int64)
  806. IMPL_GET_PRIMITIVE_TYPE_WITH_CAPABILITY(Uint64, Int64)
  807. IMPL_GET_PRIMITIVE_TYPE_WITH_CAPABILITY(Float64, Float64)
  808. IMPL_GET_PRIMITIVE_TYPE_WITH_CAPABILITY(Int16, Int16)
  809. IMPL_GET_PRIMITIVE_TYPE_WITH_CAPABILITY(Uint16, Int16)
  810. IMPL_GET_PRIMITIVE_TYPE_WITH_CAPABILITY(Float16, Float16)
  811. #undef IMPL_GET_PRIMITIVE_TYPE_WITH_CAPABILITY
  812. uint32_t ModuleBuilder::getVecType(uint32_t elemType, uint32_t elemCount) {
  813. const Type *type = nullptr;
  814. switch (elemCount) {
  815. case 2:
  816. type = Type::getVec2(theContext, elemType);
  817. break;
  818. case 3:
  819. type = Type::getVec3(theContext, elemType);
  820. break;
  821. case 4:
  822. type = Type::getVec4(theContext, elemType);
  823. break;
  824. default:
  825. assert(false && "unhandled vector size");
  826. // Error found. Return 0 as the <result-id> directly.
  827. return 0;
  828. }
  829. const uint32_t typeId = theContext.getResultIdForType(type);
  830. theModule.addType(type, typeId);
  831. return typeId;
  832. }
  833. uint32_t ModuleBuilder::getMatType(QualType elemType, uint32_t colType,
  834. uint32_t colCount,
  835. Type::DecorationSet decorations) {
  836. // NOTE: According to Item "Data rules" of SPIR-V Spec 2.16.1 "Universal
  837. // Validation Rules":
  838. // Matrix types can only be parameterized with floating-point types.
  839. //
  840. // So we need special handling of non-fp matrices. We emulate non-fp
  841. // matrices as an array of vectors.
  842. if (!elemType->isFloatingType())
  843. return getArrayType(colType, getConstantUint32(colCount), decorations);
  844. const Type *type = Type::getMatrix(theContext, colType, colCount);
  845. const uint32_t typeId = theContext.getResultIdForType(type);
  846. theModule.addType(type, typeId);
  847. return typeId;
  848. }
  849. uint32_t ModuleBuilder::getPointerType(uint32_t pointeeType,
  850. spv::StorageClass storageClass) {
  851. const Type *type = Type::getPointer(theContext, storageClass, pointeeType);
  852. const uint32_t typeId = theContext.getResultIdForType(type);
  853. theModule.addType(type, typeId);
  854. return typeId;
  855. }
  856. uint32_t
  857. ModuleBuilder::getStructType(llvm::ArrayRef<uint32_t> fieldTypes,
  858. llvm::StringRef structName,
  859. llvm::ArrayRef<llvm::StringRef> fieldNames,
  860. Type::DecorationSet decorations) {
  861. const Type *type = Type::getStruct(theContext, fieldTypes, decorations);
  862. bool isRegistered = false;
  863. const uint32_t typeId = theContext.getResultIdForType(type, &isRegistered);
  864. theModule.addType(type, typeId);
  865. if (!isRegistered) {
  866. theModule.addDebugName(typeId, structName);
  867. if (!fieldNames.empty()) {
  868. assert(fieldNames.size() == fieldTypes.size());
  869. for (uint32_t i = 0; i < fieldNames.size(); ++i)
  870. theModule.addDebugName(typeId, fieldNames[i],
  871. llvm::Optional<uint32_t>(i));
  872. }
  873. }
  874. return typeId;
  875. }
  876. uint32_t ModuleBuilder::getSparseResidencyStructType(uint32_t type) {
  877. const auto uintType = getUint32Type();
  878. return getStructType({uintType, type}, "SparseResidencyStruct",
  879. {"Residency.Code", "Result.Type"});
  880. }
  881. uint32_t ModuleBuilder::getArrayType(uint32_t elemType, uint32_t count,
  882. Type::DecorationSet decorations) {
  883. const Type *type = Type::getArray(theContext, elemType, count, decorations);
  884. const uint32_t typeId = theContext.getResultIdForType(type);
  885. theModule.addType(type, typeId);
  886. return typeId;
  887. }
  888. uint32_t ModuleBuilder::getRuntimeArrayType(uint32_t elemType,
  889. Type::DecorationSet decorations) {
  890. const Type *type = Type::getRuntimeArray(theContext, elemType, decorations);
  891. const uint32_t typeId = theContext.getResultIdForType(type);
  892. theModule.addType(type, typeId);
  893. return typeId;
  894. }
  895. uint32_t ModuleBuilder::getFunctionType(uint32_t returnType,
  896. llvm::ArrayRef<uint32_t> paramTypes) {
  897. const Type *type = Type::getFunction(theContext, returnType, paramTypes);
  898. const uint32_t typeId = theContext.getResultIdForType(type);
  899. theModule.addType(type, typeId);
  900. return typeId;
  901. }
  902. uint32_t ModuleBuilder::getImageType(uint32_t sampledType, spv::Dim dim,
  903. uint32_t depth, bool isArray, uint32_t ms,
  904. uint32_t sampled,
  905. spv::ImageFormat format) {
  906. const Type *type = Type::getImage(theContext, sampledType, dim, depth,
  907. isArray, ms, sampled, format);
  908. bool isRegistered = false;
  909. const uint32_t typeId = theContext.getResultIdForType(type, &isRegistered);
  910. theModule.addType(type, typeId);
  911. switch (format) {
  912. case spv::ImageFormat::Rg32f:
  913. case spv::ImageFormat::Rg16f:
  914. case spv::ImageFormat::R11fG11fB10f:
  915. case spv::ImageFormat::R16f:
  916. case spv::ImageFormat::Rgba16:
  917. case spv::ImageFormat::Rgb10A2:
  918. case spv::ImageFormat::Rg16:
  919. case spv::ImageFormat::Rg8:
  920. case spv::ImageFormat::R16:
  921. case spv::ImageFormat::R8:
  922. case spv::ImageFormat::Rgba16Snorm:
  923. case spv::ImageFormat::Rg16Snorm:
  924. case spv::ImageFormat::Rg8Snorm:
  925. case spv::ImageFormat::R16Snorm:
  926. case spv::ImageFormat::R8Snorm:
  927. case spv::ImageFormat::Rg32i:
  928. case spv::ImageFormat::Rg16i:
  929. case spv::ImageFormat::Rg8i:
  930. case spv::ImageFormat::R16i:
  931. case spv::ImageFormat::R8i:
  932. case spv::ImageFormat::Rgb10a2ui:
  933. case spv::ImageFormat::Rg32ui:
  934. case spv::ImageFormat::Rg16ui:
  935. case spv::ImageFormat::Rg8ui:
  936. case spv::ImageFormat::R16ui:
  937. case spv::ImageFormat::R8ui:
  938. requireCapability(spv::Capability::StorageImageExtendedFormats);
  939. }
  940. if (dim == spv::Dim::Dim1D) {
  941. if (sampled == 2u) {
  942. requireCapability(spv::Capability::Image1D);
  943. } else {
  944. requireCapability(spv::Capability::Sampled1D);
  945. }
  946. } else if (dim == spv::Dim::Buffer) {
  947. requireCapability(spv::Capability::SampledBuffer);
  948. } else if (dim == spv::Dim::SubpassData) {
  949. requireCapability(spv::Capability::InputAttachment);
  950. }
  951. if (isArray && ms) {
  952. requireCapability(spv::Capability::ImageMSArray);
  953. }
  954. // Skip constructing the debug name if we have already done it before.
  955. if (!isRegistered) {
  956. const char *dimStr = "";
  957. switch (dim) {
  958. case spv::Dim::Dim1D:
  959. dimStr = "1d.";
  960. break;
  961. case spv::Dim::Dim2D:
  962. dimStr = "2d.";
  963. break;
  964. case spv::Dim::Dim3D:
  965. dimStr = "3d.";
  966. break;
  967. case spv::Dim::Cube:
  968. dimStr = "cube.";
  969. break;
  970. case spv::Dim::Rect:
  971. dimStr = "rect.";
  972. break;
  973. case spv::Dim::Buffer:
  974. dimStr = "buffer.";
  975. break;
  976. case spv::Dim::SubpassData:
  977. dimStr = "subpass.";
  978. break;
  979. default:
  980. break;
  981. }
  982. std::string name =
  983. std::string("type.") + dimStr + "image" + (isArray ? ".array" : "");
  984. theModule.addDebugName(typeId, name);
  985. }
  986. return typeId;
  987. }
  988. uint32_t ModuleBuilder::getSamplerType() {
  989. const Type *type = Type::getSampler(theContext);
  990. const uint32_t typeId = theContext.getResultIdForType(type);
  991. theModule.addType(type, typeId);
  992. theModule.addDebugName(typeId, "type.sampler");
  993. return typeId;
  994. }
  995. uint32_t ModuleBuilder::getSampledImageType(uint32_t imageType) {
  996. const Type *type = Type::getSampledImage(theContext, imageType);
  997. const uint32_t typeId = theContext.getResultIdForType(type);
  998. theModule.addType(type, typeId);
  999. theModule.addDebugName(typeId, "type.sampled.image");
  1000. return typeId;
  1001. }
  1002. uint32_t ModuleBuilder::getByteAddressBufferType(bool isRW) {
  1003. // Create a uint RuntimeArray with Array Stride of 4.
  1004. const uint32_t uintType = getUint32Type();
  1005. const auto *arrStride4 = Decoration::getArrayStride(theContext, 4u);
  1006. const Type *raType =
  1007. Type::getRuntimeArray(theContext, uintType, {arrStride4});
  1008. const uint32_t raTypeId = theContext.getResultIdForType(raType);
  1009. theModule.addType(raType, raTypeId);
  1010. // Create a struct containing the runtime array as its only member.
  1011. // The struct must also be decorated as BufferBlock. The offset decoration
  1012. // should also be applied to the first (only) member. NonWritable decoration
  1013. // should also be applied to the first member if isRW is true.
  1014. llvm::SmallVector<const Decoration *, 3> typeDecs;
  1015. typeDecs.push_back(Decoration::getBufferBlock(theContext));
  1016. typeDecs.push_back(Decoration::getOffset(theContext, 0, 0));
  1017. if (!isRW)
  1018. typeDecs.push_back(Decoration::getNonWritable(theContext, 0));
  1019. const Type *type = Type::getStruct(theContext, {raTypeId}, typeDecs);
  1020. const uint32_t typeId = theContext.getResultIdForType(type);
  1021. theModule.addType(type, typeId);
  1022. theModule.addDebugName(typeId, isRW ? "type.RWByteAddressBuffer"
  1023. : "type.ByteAddressBuffer");
  1024. return typeId;
  1025. }
  1026. uint32_t ModuleBuilder::getConstantBool(bool value, bool isSpecConst) {
  1027. if (isSpecConst) {
  1028. const uint32_t constId = theContext.takeNextId();
  1029. if (value) {
  1030. instBuilder.opSpecConstantTrue(getBoolType(), constId).x();
  1031. } else {
  1032. instBuilder.opSpecConstantFalse(getBoolType(), constId).x();
  1033. }
  1034. theModule.addVariable(std::move(constructSite));
  1035. return constId;
  1036. }
  1037. const uint32_t typeId = getBoolType();
  1038. const Constant *constant = value ? Constant::getTrue(theContext, typeId)
  1039. : Constant::getFalse(theContext, typeId);
  1040. const uint32_t constId = theContext.getResultIdForConstant(constant);
  1041. theModule.addConstant(constant, constId);
  1042. return constId;
  1043. }
  1044. #define IMPL_GET_PRIMITIVE_CONST(builderTy, cppTy) \
  1045. \
  1046. uint32_t ModuleBuilder::getConstant##builderTy(cppTy value) { \
  1047. const uint32_t typeId = get##builderTy##Type(); \
  1048. const Constant *constant = \
  1049. Constant::get##builderTy(theContext, typeId, value); \
  1050. const uint32_t constId = theContext.getResultIdForConstant(constant); \
  1051. theModule.addConstant(constant, constId); \
  1052. return constId; \
  1053. }
  1054. #define IMPL_GET_PRIMITIVE_CONST_SPEC_CONST(builderTy, cppTy) \
  1055. \
  1056. uint32_t ModuleBuilder::getConstant##builderTy(cppTy value, \
  1057. bool isSpecConst) { \
  1058. if (isSpecConst) { \
  1059. const uint32_t constId = theContext.takeNextId(); \
  1060. instBuilder \
  1061. .opSpecConstant(get##builderTy##Type(), constId, \
  1062. cast::BitwiseCast<uint32_t>(value)) \
  1063. .x(); \
  1064. theModule.addVariable(std::move(constructSite)); \
  1065. return constId; \
  1066. } \
  1067. \
  1068. const uint32_t typeId = get##builderTy##Type(); \
  1069. const Constant *constant = \
  1070. Constant::get##builderTy(theContext, typeId, value); \
  1071. const uint32_t constId = theContext.getResultIdForConstant(constant); \
  1072. theModule.addConstant(constant, constId); \
  1073. return constId; \
  1074. }
  1075. IMPL_GET_PRIMITIVE_CONST(Int16, int16_t)
  1076. IMPL_GET_PRIMITIVE_CONST_SPEC_CONST(Int32, int32_t)
  1077. IMPL_GET_PRIMITIVE_CONST(Uint16, uint16_t)
  1078. IMPL_GET_PRIMITIVE_CONST_SPEC_CONST(Uint32, uint32_t)
  1079. IMPL_GET_PRIMITIVE_CONST(Float16, int16_t)
  1080. IMPL_GET_PRIMITIVE_CONST_SPEC_CONST(Float32, float)
  1081. IMPL_GET_PRIMITIVE_CONST(Float64, double)
  1082. IMPL_GET_PRIMITIVE_CONST(Int64, int64_t)
  1083. IMPL_GET_PRIMITIVE_CONST(Uint64, uint64_t)
  1084. #undef IMPL_GET_PRIMITIVE_CONST
  1085. #undef IMPL_GET_PRIMITIVE_CONST_SPEC_CONST
  1086. uint32_t
  1087. ModuleBuilder::getConstantComposite(uint32_t typeId,
  1088. llvm::ArrayRef<uint32_t> constituents) {
  1089. const Constant *constant =
  1090. Constant::getComposite(theContext, typeId, constituents);
  1091. const uint32_t constId = theContext.getResultIdForConstant(constant);
  1092. theModule.addConstant(constant, constId);
  1093. return constId;
  1094. }
  1095. uint32_t ModuleBuilder::getConstantNull(uint32_t typeId) {
  1096. const Constant *constant = Constant::getNull(theContext, typeId);
  1097. const uint32_t constId = theContext.getResultIdForConstant(constant);
  1098. theModule.addConstant(constant, constId);
  1099. return constId;
  1100. }
  1101. BasicBlock *ModuleBuilder::getBasicBlock(uint32_t labelId) {
  1102. auto it = basicBlocks.find(labelId);
  1103. if (it == basicBlocks.end()) {
  1104. assert(false && "invalid <label-id>");
  1105. return nullptr;
  1106. }
  1107. return it->second.get();
  1108. }
  1109. } // end namespace spirv
  1110. } // end namespace clang