DxilContainerAssembler.cpp 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // DxilContainerAssembler.cpp //
  4. // Copyright (C) Microsoft Corporation. All rights reserved. //
  5. // This file is distributed under the University of Illinois Open Source //
  6. // License. See LICENSE.TXT for details. //
  7. // //
  8. // Provides support for serializing a module into DXIL container structures. //
  9. // //
  10. ///////////////////////////////////////////////////////////////////////////////
  11. #include "llvm/ADT/MapVector.h"
  12. #include "llvm/ADT/SetVector.h"
  13. #include "llvm/IR/Module.h"
  14. #include "llvm/IR/DebugInfo.h"
  15. #include "llvm/IR/Instructions.h"
  16. #include "llvm/Bitcode/ReaderWriter.h"
  17. #include "llvm/Support/MD5.h"
  18. #include "llvm/ADT/STLExtras.h"
  19. #include "llvm/Transforms/Utils/Cloning.h"
  20. #include "dxc/DxilContainer/DxilContainer.h"
  21. #include "dxc/DXIL/DxilModule.h"
  22. #include "dxc/DXIL/DxilShaderModel.h"
  23. #include "dxc/DxilRootSignature/DxilRootSignature.h"
  24. #include "dxc/DxilContainer/DxilContainerAssembler.h"
  25. #include "dxc/DXIL/DxilUtil.h"
  26. #include "dxc/DXIL/DxilFunctionProps.h"
  27. #include "dxc/DXIL/DxilOperations.h"
  28. #include "dxc/DXIL/DxilInstructions.h"
  29. #include "dxc/Support/Global.h"
  30. #include "dxc/Support/Unicode.h"
  31. #include "dxc/Support/WinIncludes.h"
  32. #include "dxc/Support/FileIOHelper.h"
  33. #include "dxc/Support/dxcapi.impl.h"
  34. #include <assert.h> // Needed for DxilPipelineStateValidation.h
  35. #include "dxc/DxilContainer/DxilPipelineStateValidation.h"
  36. #include "dxc/DxilContainer/DxilRuntimeReflection.h"
  37. #include "dxc/DXIL/DxilCounters.h"
  38. #include <algorithm>
  39. #include <functional>
  40. using namespace llvm;
  41. using namespace hlsl;
  42. using namespace hlsl::RDAT;
  43. static_assert((unsigned)PSVShaderKind::Invalid == (unsigned)DXIL::ShaderKind::Invalid,
  44. "otherwise, PSVShaderKind enum out of sync.");
  45. static DxilProgramSigSemantic KindToSystemValue(Semantic::Kind kind, DXIL::TessellatorDomain domain) {
  46. switch (kind) {
  47. case Semantic::Kind::Arbitrary: return DxilProgramSigSemantic::Undefined;
  48. case Semantic::Kind::VertexID: return DxilProgramSigSemantic::VertexID;
  49. case Semantic::Kind::InstanceID: return DxilProgramSigSemantic::InstanceID;
  50. case Semantic::Kind::Position: return DxilProgramSigSemantic::Position;
  51. case Semantic::Kind::Coverage: return DxilProgramSigSemantic::Coverage;
  52. case Semantic::Kind::InnerCoverage: return DxilProgramSigSemantic::InnerCoverage;
  53. case Semantic::Kind::PrimitiveID: return DxilProgramSigSemantic::PrimitiveID;
  54. case Semantic::Kind::SampleIndex: return DxilProgramSigSemantic::SampleIndex;
  55. case Semantic::Kind::IsFrontFace: return DxilProgramSigSemantic::IsFrontFace;
  56. case Semantic::Kind::RenderTargetArrayIndex: return DxilProgramSigSemantic::RenderTargetArrayIndex;
  57. case Semantic::Kind::ViewPortArrayIndex: return DxilProgramSigSemantic::ViewPortArrayIndex;
  58. case Semantic::Kind::ClipDistance: return DxilProgramSigSemantic::ClipDistance;
  59. case Semantic::Kind::CullDistance: return DxilProgramSigSemantic::CullDistance;
  60. case Semantic::Kind::Barycentrics: return DxilProgramSigSemantic::Barycentrics;
  61. case Semantic::Kind::ShadingRate: return DxilProgramSigSemantic::ShadingRate;
  62. case Semantic::Kind::CullPrimitive: return DxilProgramSigSemantic::CullPrimitive;
  63. case Semantic::Kind::TessFactor: {
  64. switch (domain) {
  65. case DXIL::TessellatorDomain::IsoLine:
  66. // Will bu updated to DetailTessFactor in next row.
  67. return DxilProgramSigSemantic::FinalLineDensityTessfactor;
  68. case DXIL::TessellatorDomain::Tri:
  69. return DxilProgramSigSemantic::FinalTriEdgeTessfactor;
  70. case DXIL::TessellatorDomain::Quad:
  71. return DxilProgramSigSemantic::FinalQuadEdgeTessfactor;
  72. default:
  73. // No other valid TesselatorDomain options.
  74. return DxilProgramSigSemantic::Undefined;
  75. }
  76. }
  77. case Semantic::Kind::InsideTessFactor: {
  78. switch (domain) {
  79. case DXIL::TessellatorDomain::IsoLine:
  80. DXASSERT(0, "invalid semantic");
  81. return DxilProgramSigSemantic::Undefined;
  82. case DXIL::TessellatorDomain::Tri:
  83. return DxilProgramSigSemantic::FinalTriInsideTessfactor;
  84. case DXIL::TessellatorDomain::Quad:
  85. return DxilProgramSigSemantic::FinalQuadInsideTessfactor;
  86. default:
  87. // No other valid DxilProgramSigSemantic options.
  88. return DxilProgramSigSemantic::Undefined;
  89. }
  90. }
  91. case Semantic::Kind::Invalid:
  92. return DxilProgramSigSemantic::Undefined;
  93. case Semantic::Kind::Target: return DxilProgramSigSemantic::Target;
  94. case Semantic::Kind::Depth: return DxilProgramSigSemantic::Depth;
  95. case Semantic::Kind::DepthLessEqual: return DxilProgramSigSemantic::DepthLE;
  96. case Semantic::Kind::DepthGreaterEqual: return DxilProgramSigSemantic::DepthGE;
  97. case Semantic::Kind::StencilRef:
  98. __fallthrough;
  99. default:
  100. DXASSERT(kind == Semantic::Kind::StencilRef, "else Invalid or switch is missing a case");
  101. return DxilProgramSigSemantic::StencilRef;
  102. }
  103. // TODO: Final_* values need mappings
  104. }
  105. static DxilProgramSigCompType CompTypeToSigCompType(hlsl::CompType value, bool i1ToUnknownCompat) {
  106. switch (value.GetKind()) {
  107. case CompType::Kind::I32: return DxilProgramSigCompType::SInt32;
  108. case CompType::Kind::I1:
  109. // Validator 1.4 and below returned Unknown for i1
  110. if (i1ToUnknownCompat) return DxilProgramSigCompType::Unknown;
  111. else return DxilProgramSigCompType::UInt32;
  112. case CompType::Kind::U32: return DxilProgramSigCompType::UInt32;
  113. case CompType::Kind::F32: return DxilProgramSigCompType::Float32;
  114. case CompType::Kind::I16: return DxilProgramSigCompType::SInt16;
  115. case CompType::Kind::I64: return DxilProgramSigCompType::SInt64;
  116. case CompType::Kind::U16: return DxilProgramSigCompType::UInt16;
  117. case CompType::Kind::U64: return DxilProgramSigCompType::UInt64;
  118. case CompType::Kind::F16: return DxilProgramSigCompType::Float16;
  119. case CompType::Kind::F64: return DxilProgramSigCompType::Float64;
  120. case CompType::Kind::Invalid: __fallthrough;
  121. default:
  122. return DxilProgramSigCompType::Unknown;
  123. }
  124. }
  125. static DxilProgramSigMinPrecision CompTypeToSigMinPrecision(hlsl::CompType value) {
  126. switch (value.GetKind()) {
  127. case CompType::Kind::I32: return DxilProgramSigMinPrecision::Default;
  128. case CompType::Kind::U32: return DxilProgramSigMinPrecision::Default;
  129. case CompType::Kind::F32: return DxilProgramSigMinPrecision::Default;
  130. case CompType::Kind::I1: return DxilProgramSigMinPrecision::Default;
  131. case CompType::Kind::U64: __fallthrough;
  132. case CompType::Kind::I64: __fallthrough;
  133. case CompType::Kind::F64: return DxilProgramSigMinPrecision::Default;
  134. case CompType::Kind::I16: return DxilProgramSigMinPrecision::SInt16;
  135. case CompType::Kind::U16: return DxilProgramSigMinPrecision::UInt16;
  136. case CompType::Kind::F16: return DxilProgramSigMinPrecision::Float16; // Float2_8 is not supported in DXIL.
  137. case CompType::Kind::Invalid: __fallthrough;
  138. default:
  139. return DxilProgramSigMinPrecision::Default;
  140. }
  141. }
  142. template <typename T>
  143. struct sort_second {
  144. bool operator()(const T &a, const T &b) {
  145. return std::less<decltype(a.second)>()(a.second, b.second);
  146. }
  147. };
  148. struct sort_sig {
  149. bool operator()(const DxilProgramSignatureElement &a,
  150. const DxilProgramSignatureElement &b) {
  151. return (a.Stream < b.Stream) ||
  152. ((a.Stream == b.Stream) && (a.Register < b.Register)) ||
  153. ((a.Stream == b.Stream) && (a.Register == b.Register) &&
  154. (a.SemanticName < b.SemanticName));
  155. }
  156. };
  157. static uint8_t NegMask(uint8_t V) {
  158. V ^= 0xF;
  159. return V & 0xF;
  160. }
  161. class DxilProgramSignatureWriter : public DxilPartWriter {
  162. private:
  163. const DxilSignature &m_signature;
  164. DXIL::TessellatorDomain m_domain;
  165. bool m_isInput;
  166. bool m_useMinPrecision;
  167. bool m_bCompat_1_4;
  168. size_t m_fixedSize;
  169. typedef std::pair<const char *, uint32_t> NameOffsetPair;
  170. typedef llvm::SmallMapVector<const char *, uint32_t, 8> NameOffsetMap;
  171. uint32_t m_lastOffset;
  172. NameOffsetMap m_semanticNameOffsets;
  173. unsigned m_paramCount;
  174. const char *GetSemanticName(const hlsl::DxilSignatureElement *pElement) {
  175. DXASSERT_NOMSG(pElement != nullptr);
  176. DXASSERT(pElement->GetName() != nullptr, "else sig is malformed");
  177. return pElement->GetName();
  178. }
  179. uint32_t GetSemanticOffset(const hlsl::DxilSignatureElement *pElement) {
  180. const char *pName = GetSemanticName(pElement);
  181. NameOffsetMap::iterator nameOffset = m_semanticNameOffsets.find(pName);
  182. uint32_t result;
  183. if (nameOffset == m_semanticNameOffsets.end()) {
  184. result = m_lastOffset;
  185. m_semanticNameOffsets.insert(NameOffsetPair(pName, result));
  186. m_lastOffset += strlen(pName) + 1;
  187. }
  188. else {
  189. result = nameOffset->second;
  190. }
  191. return result;
  192. }
  193. void write(std::vector<DxilProgramSignatureElement> &orderedSig,
  194. const hlsl::DxilSignatureElement *pElement) {
  195. const std::vector<unsigned> &indexVec = pElement->GetSemanticIndexVec();
  196. unsigned eltCount = pElement->GetSemanticIndexVec().size();
  197. unsigned eltRows = 1;
  198. if (eltCount)
  199. eltRows = pElement->GetRows() / eltCount;
  200. DXASSERT_NOMSG(eltRows == 1);
  201. DxilProgramSignatureElement sig;
  202. memset(&sig, 0, sizeof(DxilProgramSignatureElement));
  203. sig.Stream = pElement->GetOutputStream();
  204. sig.SemanticName = GetSemanticOffset(pElement);
  205. sig.SystemValue = KindToSystemValue(pElement->GetKind(), m_domain);
  206. sig.CompType = CompTypeToSigCompType(pElement->GetCompType(), m_bCompat_1_4);
  207. sig.Register = pElement->GetStartRow();
  208. sig.Mask = pElement->GetColsAsMask();
  209. if (m_bCompat_1_4) {
  210. // Match what validator 1.4 and below expects
  211. // Only mark exist channel write for output.
  212. // All channel not used for input.
  213. if (!m_isInput)
  214. sig.NeverWrites_Mask = ~sig.Mask;
  215. else
  216. sig.AlwaysReads_Mask = 0;
  217. } else {
  218. unsigned UsageMask = pElement->GetUsageMask();
  219. if (pElement->IsAllocated())
  220. UsageMask <<= pElement->GetStartCol();
  221. if (!m_isInput)
  222. sig.NeverWrites_Mask = NegMask(UsageMask);
  223. else
  224. sig.AlwaysReads_Mask = UsageMask;
  225. }
  226. sig.MinPrecision = m_useMinPrecision
  227. ? CompTypeToSigMinPrecision(pElement->GetCompType())
  228. : DxilProgramSigMinPrecision::Default;
  229. for (unsigned i = 0; i < eltCount; ++i) {
  230. sig.SemanticIndex = indexVec[i];
  231. orderedSig.emplace_back(sig);
  232. if (pElement->IsAllocated())
  233. sig.Register += eltRows;
  234. if (sig.SystemValue == DxilProgramSigSemantic::FinalLineDensityTessfactor)
  235. sig.SystemValue = DxilProgramSigSemantic::FinalLineDetailTessfactor;
  236. }
  237. }
  238. void calcSizes() {
  239. // Calculate size for signature elements.
  240. const std::vector<std::unique_ptr<hlsl::DxilSignatureElement>> &elements = m_signature.GetElements();
  241. uint32_t result = sizeof(DxilProgramSignature);
  242. m_paramCount = 0;
  243. for (size_t i = 0; i < elements.size(); ++i) {
  244. DXIL::SemanticInterpretationKind I = elements[i]->GetInterpretation();
  245. if (I == DXIL::SemanticInterpretationKind::NA || I == DXIL::SemanticInterpretationKind::NotInSig)
  246. continue;
  247. unsigned semanticCount = elements[i]->GetSemanticIndexVec().size();
  248. result += semanticCount * sizeof(DxilProgramSignatureElement);
  249. m_paramCount += semanticCount;
  250. }
  251. m_fixedSize = result;
  252. m_lastOffset = m_fixedSize;
  253. // Calculate size for semantic strings.
  254. for (size_t i = 0; i < elements.size(); ++i) {
  255. GetSemanticOffset(elements[i].get());
  256. }
  257. }
  258. public:
  259. DxilProgramSignatureWriter(const DxilSignature &signature,
  260. DXIL::TessellatorDomain domain,
  261. bool isInput, bool UseMinPrecision,
  262. bool bCompat_1_4)
  263. : m_signature(signature), m_domain(domain),
  264. m_isInput(isInput), m_useMinPrecision(UseMinPrecision),
  265. m_bCompat_1_4(bCompat_1_4) {
  266. calcSizes();
  267. }
  268. uint32_t size() const override {
  269. return m_lastOffset;
  270. }
  271. void write(AbstractMemoryStream *pStream) override {
  272. UINT64 startPos = pStream->GetPosition();
  273. const std::vector<std::unique_ptr<hlsl::DxilSignatureElement>> &elements = m_signature.GetElements();
  274. DxilProgramSignature programSig;
  275. programSig.ParamCount = m_paramCount;
  276. programSig.ParamOffset = sizeof(DxilProgramSignature);
  277. IFT(WriteStreamValue(pStream, programSig));
  278. // Write structures in register order.
  279. std::vector<DxilProgramSignatureElement> orderedSig;
  280. for (size_t i = 0; i < elements.size(); ++i) {
  281. DXIL::SemanticInterpretationKind I = elements[i]->GetInterpretation();
  282. if (I == DXIL::SemanticInterpretationKind::NA || I == DXIL::SemanticInterpretationKind::NotInSig)
  283. continue;
  284. write(orderedSig, elements[i].get());
  285. }
  286. std::sort(orderedSig.begin(), orderedSig.end(), sort_sig());
  287. for (size_t i = 0; i < orderedSig.size(); ++i) {
  288. DxilProgramSignatureElement &sigElt = orderedSig[i];
  289. IFT(WriteStreamValue(pStream, sigElt));
  290. }
  291. // Write strings in the offset order.
  292. std::vector<NameOffsetPair> ordered;
  293. ordered.assign(m_semanticNameOffsets.begin(), m_semanticNameOffsets.end());
  294. std::sort(ordered.begin(), ordered.end(), sort_second<NameOffsetPair>());
  295. for (size_t i = 0; i < ordered.size(); ++i) {
  296. const char *pName = ordered[i].first;
  297. ULONG cbWritten;
  298. UINT64 offsetPos = pStream->GetPosition();
  299. DXASSERT_LOCALVAR(offsetPos, offsetPos - startPos == ordered[i].second, "else str offset is incorrect");
  300. IFT(pStream->Write(pName, strlen(pName) + 1, &cbWritten));
  301. }
  302. // Verify we wrote the bytes we though we would.
  303. UINT64 endPos = pStream->GetPosition();
  304. DXASSERT_LOCALVAR(endPos - startPos, endPos - startPos == size(), "else size is incorrect");
  305. }
  306. };
  307. DxilPartWriter *hlsl::NewProgramSignatureWriter(const DxilModule &M, DXIL::SignatureKind Kind) {
  308. DXIL::TessellatorDomain domain = DXIL::TessellatorDomain::Undefined;
  309. if (M.GetShaderModel()->IsHS() || M.GetShaderModel()->IsDS())
  310. domain = M.GetTessellatorDomain();
  311. unsigned ValMajor, ValMinor;
  312. M.GetValidatorVersion(ValMajor, ValMinor);
  313. bool bCompat_1_4 = DXIL::CompareVersions(ValMajor, ValMinor, 1, 5) < 0;
  314. switch (Kind) {
  315. case DXIL::SignatureKind::Input:
  316. return new DxilProgramSignatureWriter(
  317. M.GetInputSignature(), domain, true,
  318. M.GetUseMinPrecision(),
  319. bCompat_1_4);
  320. case DXIL::SignatureKind::Output:
  321. return new DxilProgramSignatureWriter(
  322. M.GetOutputSignature(), domain, false,
  323. M.GetUseMinPrecision(),
  324. bCompat_1_4);
  325. case DXIL::SignatureKind::PatchConstOrPrim:
  326. return new DxilProgramSignatureWriter(
  327. M.GetPatchConstOrPrimSignature(), domain,
  328. /*IsInput*/ M.GetShaderModel()->IsDS(),
  329. /*UseMinPrecision*/M.GetUseMinPrecision(),
  330. bCompat_1_4);
  331. case DXIL::SignatureKind::Invalid:
  332. return nullptr;
  333. }
  334. return nullptr;
  335. }
  336. class DxilProgramRootSignatureWriter : public DxilPartWriter {
  337. private:
  338. const RootSignatureHandle &m_Sig;
  339. public:
  340. DxilProgramRootSignatureWriter(const RootSignatureHandle &S) : m_Sig(S) {}
  341. uint32_t size() const {
  342. return m_Sig.GetSerializedSize();
  343. }
  344. void write(AbstractMemoryStream *pStream) {
  345. ULONG cbWritten;
  346. IFT(pStream->Write(m_Sig.GetSerializedBytes(), size(), &cbWritten));
  347. }
  348. };
  349. DxilPartWriter *hlsl::NewRootSignatureWriter(const RootSignatureHandle &S) {
  350. return new DxilProgramRootSignatureWriter(S);
  351. }
  352. class DxilFeatureInfoWriter : public DxilPartWriter {
  353. private:
  354. // Only save the shader properties after create class for it.
  355. DxilShaderFeatureInfo featureInfo;
  356. public:
  357. DxilFeatureInfoWriter(const DxilModule &M) {
  358. featureInfo.FeatureFlags = M.m_ShaderFlags.GetFeatureInfo();
  359. }
  360. uint32_t size() const override {
  361. return sizeof(DxilShaderFeatureInfo);
  362. }
  363. void write(AbstractMemoryStream *pStream) override {
  364. IFT(WriteStreamValue(pStream, featureInfo.FeatureFlags));
  365. }
  366. };
  367. DxilPartWriter *hlsl::NewFeatureInfoWriter(const DxilModule &M) {
  368. return new DxilFeatureInfoWriter(M);
  369. }
  370. class DxilPSVWriter : public DxilPartWriter {
  371. private:
  372. const DxilModule &m_Module;
  373. unsigned m_ValMajor, m_ValMinor;
  374. PSVInitInfo m_PSVInitInfo;
  375. DxilPipelineStateValidation m_PSV;
  376. uint32_t m_PSVBufferSize;
  377. SmallVector<char, 512> m_PSVBuffer;
  378. SmallVector<char, 256> m_StringBuffer;
  379. SmallVector<uint32_t, 8> m_SemanticIndexBuffer;
  380. std::vector<PSVSignatureElement0> m_SigInputElements;
  381. std::vector<PSVSignatureElement0> m_SigOutputElements;
  382. std::vector<PSVSignatureElement0> m_SigPatchConstOrPrimElements;
  383. void SetPSVSigElement(PSVSignatureElement0 &E, const DxilSignatureElement &SE) {
  384. memset(&E, 0, sizeof(PSVSignatureElement0));
  385. if (SE.GetKind() == DXIL::SemanticKind::Arbitrary && strlen(SE.GetName()) > 0) {
  386. E.SemanticName = (uint32_t)m_StringBuffer.size();
  387. StringRef Name(SE.GetName());
  388. m_StringBuffer.append(Name.size()+1, '\0');
  389. memcpy(m_StringBuffer.data() + E.SemanticName, Name.data(), Name.size());
  390. } else {
  391. // m_StringBuffer always starts with '\0' so offset 0 is empty string:
  392. E.SemanticName = 0;
  393. }
  394. // Search index buffer for matching semantic index sequence
  395. DXASSERT_NOMSG(SE.GetRows() == SE.GetSemanticIndexVec().size());
  396. auto &SemIdx = SE.GetSemanticIndexVec();
  397. bool match = false;
  398. for (uint32_t offset = 0; offset + SE.GetRows() - 1 < m_SemanticIndexBuffer.size(); offset++) {
  399. match = true;
  400. for (uint32_t row = 0; row < SE.GetRows(); row++) {
  401. if ((uint32_t)SemIdx[row] != m_SemanticIndexBuffer[offset + row]) {
  402. match = false;
  403. break;
  404. }
  405. }
  406. if (match) {
  407. E.SemanticIndexes = offset;
  408. break;
  409. }
  410. }
  411. if (!match) {
  412. E.SemanticIndexes = m_SemanticIndexBuffer.size();
  413. for (uint32_t row = 0; row < SemIdx.size(); row++) {
  414. m_SemanticIndexBuffer.push_back((uint32_t)SemIdx[row]);
  415. }
  416. }
  417. DXASSERT_NOMSG(SE.GetRows() <= 32);
  418. E.Rows = (uint8_t)SE.GetRows();
  419. DXASSERT_NOMSG(SE.GetCols() <= 4);
  420. E.ColsAndStart = (uint8_t)SE.GetCols() & 0xF;
  421. if (SE.IsAllocated()) {
  422. DXASSERT_NOMSG(SE.GetStartCol() < 4);
  423. DXASSERT_NOMSG(SE.GetStartRow() < 32);
  424. E.ColsAndStart |= 0x40 | (SE.GetStartCol() << 4);
  425. E.StartRow = (uint8_t)SE.GetStartRow();
  426. }
  427. E.SemanticKind = (uint8_t)SE.GetKind();
  428. E.ComponentType = (uint8_t)CompTypeToSigCompType(SE.GetCompType(),
  429. /*i1ToUnknownCompat*/DXIL::CompareVersions(m_ValMajor, m_ValMinor, 1, 5) < 0);
  430. E.InterpolationMode = (uint8_t)SE.GetInterpolationMode()->GetKind();
  431. DXASSERT_NOMSG(SE.GetOutputStream() < 4);
  432. E.DynamicMaskAndStream = (uint8_t)((SE.GetOutputStream() & 0x3) << 4);
  433. E.DynamicMaskAndStream |= (SE.GetDynIdxCompMask()) & 0xF;
  434. }
  435. const uint32_t *CopyViewIDState(const uint32_t *pSrc, uint32_t InputScalars, uint32_t OutputScalars, PSVComponentMask ViewIDMask, PSVDependencyTable IOTable) {
  436. unsigned MaskDwords = PSVComputeMaskDwordsFromVectors(PSVALIGN4(OutputScalars) / 4);
  437. if (ViewIDMask.IsValid()) {
  438. DXASSERT_NOMSG(!IOTable.Table || ViewIDMask.NumVectors == IOTable.OutputVectors);
  439. memcpy(ViewIDMask.Mask, pSrc, 4 * MaskDwords);
  440. pSrc += MaskDwords;
  441. }
  442. if (IOTable.IsValid() && IOTable.InputVectors && IOTable.OutputVectors) {
  443. DXASSERT_NOMSG((InputScalars <= IOTable.InputVectors * 4) && (IOTable.InputVectors * 4 - InputScalars < 4));
  444. DXASSERT_NOMSG((OutputScalars <= IOTable.OutputVectors * 4) && (IOTable.OutputVectors * 4 - OutputScalars < 4));
  445. memcpy(IOTable.Table, pSrc, 4 * MaskDwords * InputScalars);
  446. pSrc += MaskDwords * InputScalars;
  447. }
  448. return pSrc;
  449. }
  450. public:
  451. DxilPSVWriter(const DxilModule &mod, uint32_t PSVVersion = UINT_MAX)
  452. : m_Module(mod),
  453. m_PSVInitInfo(PSVVersion)
  454. {
  455. m_Module.GetValidatorVersion(m_ValMajor, m_ValMinor);
  456. // Constraint PSVVersion based on validator version
  457. if (PSVVersion > 0 && DXIL::CompareVersions(m_ValMajor, m_ValMinor, 1, 1) < 0)
  458. m_PSVInitInfo.PSVVersion = 0;
  459. else if (PSVVersion > 1 && DXIL::CompareVersions(m_ValMajor, m_ValMinor, 1, 6) < 0)
  460. m_PSVInitInfo.PSVVersion = 1;
  461. else if (PSVVersion > MAX_PSV_VERSION)
  462. m_PSVInitInfo.PSVVersion = MAX_PSV_VERSION;
  463. const ShaderModel *SM = m_Module.GetShaderModel();
  464. UINT uCBuffers = m_Module.GetCBuffers().size();
  465. UINT uSamplers = m_Module.GetSamplers().size();
  466. UINT uSRVs = m_Module.GetSRVs().size();
  467. UINT uUAVs = m_Module.GetUAVs().size();
  468. m_PSVInitInfo.ResourceCount = uCBuffers + uSamplers + uSRVs + uUAVs;
  469. // TODO: for >= 6.2 version, create more efficient structure
  470. if (m_PSVInitInfo.PSVVersion > 0) {
  471. m_PSVInitInfo.ShaderStage = (PSVShaderKind)SM->GetKind();
  472. // Copy Dxil Signatures
  473. m_StringBuffer.push_back('\0'); // For empty semantic name (system value)
  474. m_PSVInitInfo.SigInputElements = m_Module.GetInputSignature().GetElements().size();
  475. m_SigInputElements.resize(m_PSVInitInfo.SigInputElements);
  476. m_PSVInitInfo.SigOutputElements = m_Module.GetOutputSignature().GetElements().size();
  477. m_SigOutputElements.resize(m_PSVInitInfo.SigOutputElements);
  478. m_PSVInitInfo.SigPatchConstOrPrimElements = m_Module.GetPatchConstOrPrimSignature().GetElements().size();
  479. m_SigPatchConstOrPrimElements.resize(m_PSVInitInfo.SigPatchConstOrPrimElements);
  480. uint32_t i = 0;
  481. for (auto &SE : m_Module.GetInputSignature().GetElements()) {
  482. SetPSVSigElement(m_SigInputElements[i++], *(SE.get()));
  483. }
  484. i = 0;
  485. for (auto &SE : m_Module.GetOutputSignature().GetElements()) {
  486. SetPSVSigElement(m_SigOutputElements[i++], *(SE.get()));
  487. }
  488. i = 0;
  489. for (auto &SE : m_Module.GetPatchConstOrPrimSignature().GetElements()) {
  490. SetPSVSigElement(m_SigPatchConstOrPrimElements[i++], *(SE.get()));
  491. }
  492. // Set String and SemanticInput Tables
  493. m_PSVInitInfo.StringTable.Table = m_StringBuffer.data();
  494. m_PSVInitInfo.StringTable.Size = m_StringBuffer.size();
  495. m_PSVInitInfo.SemanticIndexTable.Table = m_SemanticIndexBuffer.data();
  496. m_PSVInitInfo.SemanticIndexTable.Entries = m_SemanticIndexBuffer.size();
  497. // Set up ViewID and signature dependency info
  498. m_PSVInitInfo.UsesViewID = m_Module.m_ShaderFlags.GetViewID() ? true : false;
  499. m_PSVInitInfo.SigInputVectors = m_Module.GetInputSignature().NumVectorsUsed(0);
  500. for (unsigned streamIndex = 0; streamIndex < 4; streamIndex++) {
  501. m_PSVInitInfo.SigOutputVectors[streamIndex] = m_Module.GetOutputSignature().NumVectorsUsed(streamIndex);
  502. }
  503. m_PSVInitInfo.SigPatchConstOrPrimVectors = 0;
  504. if (SM->IsHS() || SM->IsDS() || SM->IsMS()) {
  505. m_PSVInitInfo.SigPatchConstOrPrimVectors = m_Module.GetPatchConstOrPrimSignature().NumVectorsUsed(0);
  506. }
  507. }
  508. if (!m_PSV.InitNew(m_PSVInitInfo, nullptr, &m_PSVBufferSize)) {
  509. DXASSERT(false, "PSV InitNew failed computing size!");
  510. }
  511. }
  512. uint32_t size() const override {
  513. return m_PSVBufferSize;
  514. }
  515. void write(AbstractMemoryStream *pStream) override {
  516. m_PSVBuffer.resize(m_PSVBufferSize);
  517. if (!m_PSV.InitNew(m_PSVInitInfo, m_PSVBuffer.data(), &m_PSVBufferSize)) {
  518. DXASSERT(false, "PSV InitNew failed!");
  519. }
  520. DXASSERT_NOMSG(m_PSVBuffer.size() == m_PSVBufferSize);
  521. // Set DxilRuntimeInfo
  522. PSVRuntimeInfo0* pInfo = m_PSV.GetPSVRuntimeInfo0();
  523. PSVRuntimeInfo1* pInfo1 = m_PSV.GetPSVRuntimeInfo1();
  524. PSVRuntimeInfo2* pInfo2 = m_PSV.GetPSVRuntimeInfo2();
  525. const ShaderModel* SM = m_Module.GetShaderModel();
  526. pInfo->MinimumExpectedWaveLaneCount = 0;
  527. pInfo->MaximumExpectedWaveLaneCount = (UINT)-1;
  528. switch (SM->GetKind()) {
  529. case ShaderModel::Kind::Vertex: {
  530. pInfo->VS.OutputPositionPresent = 0;
  531. const DxilSignature &S = m_Module.GetOutputSignature();
  532. for (auto &&E : S.GetElements()) {
  533. if (E->GetKind() == Semantic::Kind::Position) {
  534. // Ideally, we might check never writes mask here,
  535. // but this is not yet part of the signature element in Dxil
  536. pInfo->VS.OutputPositionPresent = 1;
  537. break;
  538. }
  539. }
  540. break;
  541. }
  542. case ShaderModel::Kind::Hull: {
  543. pInfo->HS.InputControlPointCount = (UINT)m_Module.GetInputControlPointCount();
  544. pInfo->HS.OutputControlPointCount = (UINT)m_Module.GetOutputControlPointCount();
  545. pInfo->HS.TessellatorDomain = (UINT)m_Module.GetTessellatorDomain();
  546. pInfo->HS.TessellatorOutputPrimitive = (UINT)m_Module.GetTessellatorOutputPrimitive();
  547. break;
  548. }
  549. case ShaderModel::Kind::Domain: {
  550. pInfo->DS.InputControlPointCount = (UINT)m_Module.GetInputControlPointCount();
  551. pInfo->DS.OutputPositionPresent = 0;
  552. const DxilSignature &S = m_Module.GetOutputSignature();
  553. for (auto &&E : S.GetElements()) {
  554. if (E->GetKind() == Semantic::Kind::Position) {
  555. // Ideally, we might check never writes mask here,
  556. // but this is not yet part of the signature element in Dxil
  557. pInfo->DS.OutputPositionPresent = 1;
  558. break;
  559. }
  560. }
  561. pInfo->DS.TessellatorDomain = (UINT)m_Module.GetTessellatorDomain();
  562. break;
  563. }
  564. case ShaderModel::Kind::Geometry: {
  565. pInfo->GS.InputPrimitive = (UINT)m_Module.GetInputPrimitive();
  566. // NOTE: For OutputTopology, pick one from a used stream, or if none
  567. // are used, use stream 0, and set OutputStreamMask to 1.
  568. pInfo->GS.OutputTopology = (UINT)m_Module.GetStreamPrimitiveTopology();
  569. pInfo->GS.OutputStreamMask = m_Module.GetActiveStreamMask();
  570. if (pInfo->GS.OutputStreamMask == 0) {
  571. pInfo->GS.OutputStreamMask = 1; // This is what runtime expects.
  572. }
  573. pInfo->GS.OutputPositionPresent = 0;
  574. const DxilSignature &S = m_Module.GetOutputSignature();
  575. for (auto &&E : S.GetElements()) {
  576. if (E->GetKind() == Semantic::Kind::Position) {
  577. // Ideally, we might check never writes mask here,
  578. // but this is not yet part of the signature element in Dxil
  579. pInfo->GS.OutputPositionPresent = 1;
  580. break;
  581. }
  582. }
  583. break;
  584. }
  585. case ShaderModel::Kind::Pixel: {
  586. pInfo->PS.DepthOutput = 0;
  587. pInfo->PS.SampleFrequency = 0;
  588. {
  589. const DxilSignature &S = m_Module.GetInputSignature();
  590. for (auto &&E : S.GetElements()) {
  591. if (E->GetInterpolationMode()->IsAnySample() ||
  592. E->GetKind() == Semantic::Kind::SampleIndex) {
  593. pInfo->PS.SampleFrequency = 1;
  594. }
  595. }
  596. }
  597. {
  598. const DxilSignature &S = m_Module.GetOutputSignature();
  599. for (auto &&E : S.GetElements()) {
  600. if (E->IsAnyDepth()) {
  601. pInfo->PS.DepthOutput = 1;
  602. break;
  603. }
  604. }
  605. }
  606. break;
  607. }
  608. case ShaderModel::Kind::Compute: {
  609. UINT waveSize = (UINT)m_Module.GetWaveSize();
  610. if (waveSize != 0) {
  611. pInfo->MinimumExpectedWaveLaneCount = waveSize;
  612. pInfo->MaximumExpectedWaveLaneCount = waveSize;
  613. }
  614. break;
  615. }
  616. case ShaderModel::Kind::Library:
  617. case ShaderModel::Kind::Invalid:
  618. // Library and Invalid not relevant to PSVRuntimeInfo0
  619. break;
  620. case ShaderModel::Kind::Mesh: {
  621. pInfo->MS.MaxOutputVertices = (UINT)m_Module.GetMaxOutputVertices();
  622. pInfo->MS.MaxOutputPrimitives = (UINT)m_Module.GetMaxOutputPrimitives();
  623. pInfo1->MS1.MeshOutputTopology = (UINT)m_Module.GetMeshOutputTopology();
  624. Module *mod = m_Module.GetModule();
  625. const DataLayout &DL = mod->getDataLayout();
  626. unsigned totalByteSize = 0;
  627. for (GlobalVariable &GV : mod->globals()) {
  628. PointerType *gvPtrType = cast<PointerType>(GV.getType());
  629. if (gvPtrType->getAddressSpace() == hlsl::DXIL::kTGSMAddrSpace) {
  630. Type *gvType = gvPtrType->getPointerElementType();
  631. unsigned byteSize = DL.getTypeAllocSize(gvType);
  632. totalByteSize += byteSize;
  633. }
  634. }
  635. pInfo->MS.GroupSharedBytesUsed = totalByteSize;
  636. pInfo->MS.PayloadSizeInBytes = m_Module.GetPayloadSizeInBytes();
  637. break;
  638. }
  639. case ShaderModel::Kind::Amplification: {
  640. pInfo->AS.PayloadSizeInBytes = m_Module.GetPayloadSizeInBytes();
  641. break;
  642. }
  643. }
  644. if (pInfo2) {
  645. switch (SM->GetKind()) {
  646. case ShaderModel::Kind::Compute:
  647. case ShaderModel::Kind::Mesh:
  648. case ShaderModel::Kind::Amplification:
  649. pInfo2->NumThreadsX = m_Module.GetNumThreads(0);
  650. pInfo2->NumThreadsY = m_Module.GetNumThreads(1);
  651. pInfo2->NumThreadsZ = m_Module.GetNumThreads(2);
  652. break;
  653. }
  654. }
  655. // Set resource binding information
  656. UINT uResIndex = 0;
  657. for (auto &&R : m_Module.GetCBuffers()) {
  658. DXASSERT_NOMSG(uResIndex < m_PSVInitInfo.ResourceCount);
  659. PSVResourceBindInfo0* pBindInfo = m_PSV.GetPSVResourceBindInfo0(uResIndex);
  660. PSVResourceBindInfo1* pBindInfo1 = m_PSV.GetPSVResourceBindInfo1(uResIndex);
  661. DXASSERT_NOMSG(pBindInfo);
  662. pBindInfo->ResType = (UINT)PSVResourceType::CBV;
  663. pBindInfo->Space = R->GetSpaceID();
  664. pBindInfo->LowerBound = R->GetLowerBound();
  665. pBindInfo->UpperBound = R->GetUpperBound();
  666. if (pBindInfo1) {
  667. pBindInfo1->ResKind = (UINT)R->GetKind();
  668. }
  669. uResIndex++;
  670. }
  671. for (auto &&R : m_Module.GetSamplers()) {
  672. DXASSERT_NOMSG(uResIndex < m_PSVInitInfo.ResourceCount);
  673. PSVResourceBindInfo0* pBindInfo = m_PSV.GetPSVResourceBindInfo0(uResIndex);
  674. PSVResourceBindInfo1* pBindInfo1 = m_PSV.GetPSVResourceBindInfo1(uResIndex);
  675. DXASSERT_NOMSG(pBindInfo);
  676. pBindInfo->ResType = (UINT)PSVResourceType::Sampler;
  677. pBindInfo->Space = R->GetSpaceID();
  678. pBindInfo->LowerBound = R->GetLowerBound();
  679. pBindInfo->UpperBound = R->GetUpperBound();
  680. if (pBindInfo1) {
  681. pBindInfo1->ResKind = (UINT)R->GetKind();
  682. }
  683. uResIndex++;
  684. }
  685. for (auto &&R : m_Module.GetSRVs()) {
  686. DXASSERT_NOMSG(uResIndex < m_PSVInitInfo.ResourceCount);
  687. PSVResourceBindInfo0* pBindInfo = m_PSV.GetPSVResourceBindInfo0(uResIndex);
  688. PSVResourceBindInfo1* pBindInfo1 = m_PSV.GetPSVResourceBindInfo1(uResIndex);
  689. DXASSERT_NOMSG(pBindInfo);
  690. if (R->IsStructuredBuffer()) {
  691. pBindInfo->ResType = (UINT)PSVResourceType::SRVStructured;
  692. } else if (R->IsRawBuffer() || (R->GetKind() == DxilResourceBase::Kind::RTAccelerationStructure)) {
  693. pBindInfo->ResType = (UINT)PSVResourceType::SRVRaw;
  694. } else {
  695. pBindInfo->ResType = (UINT)PSVResourceType::SRVTyped;
  696. }
  697. pBindInfo->Space = R->GetSpaceID();
  698. pBindInfo->LowerBound = R->GetLowerBound();
  699. pBindInfo->UpperBound = R->GetUpperBound();
  700. if (pBindInfo1) {
  701. pBindInfo1->ResKind = (UINT)R->GetKind();
  702. }
  703. uResIndex++;
  704. }
  705. for (auto &&R : m_Module.GetUAVs()) {
  706. DXASSERT_NOMSG(uResIndex < m_PSVInitInfo.ResourceCount);
  707. PSVResourceBindInfo0* pBindInfo = m_PSV.GetPSVResourceBindInfo0(uResIndex);
  708. PSVResourceBindInfo1* pBindInfo1 = m_PSV.GetPSVResourceBindInfo1(uResIndex);
  709. DXASSERT_NOMSG(pBindInfo);
  710. if (R->IsStructuredBuffer()) {
  711. if (R->HasCounter())
  712. pBindInfo->ResType = (UINT)PSVResourceType::UAVStructuredWithCounter;
  713. else
  714. pBindInfo->ResType = (UINT)PSVResourceType::UAVStructured;
  715. } else if (R->IsRawBuffer()) {
  716. pBindInfo->ResType = (UINT)PSVResourceType::UAVRaw;
  717. } else {
  718. pBindInfo->ResType = (UINT)PSVResourceType::UAVTyped;
  719. }
  720. pBindInfo->Space = R->GetSpaceID();
  721. pBindInfo->LowerBound = R->GetLowerBound();
  722. pBindInfo->UpperBound = R->GetUpperBound();
  723. if (pBindInfo1) {
  724. pBindInfo1->ResKind = (UINT)R->GetKind();
  725. }
  726. uResIndex++;
  727. }
  728. DXASSERT_NOMSG(uResIndex == m_PSVInitInfo.ResourceCount);
  729. if (m_PSVInitInfo.PSVVersion > 0) {
  730. DXASSERT_NOMSG(pInfo1);
  731. // Write MaxVertexCount
  732. if (SM->IsGS()) {
  733. DXASSERT_NOMSG(m_Module.GetMaxVertexCount() <= 1024);
  734. pInfo1->MaxVertexCount = (uint16_t)m_Module.GetMaxVertexCount();
  735. }
  736. // Write Dxil Signature Elements
  737. for (unsigned i = 0; i < m_PSV.GetSigInputElements(); i++) {
  738. PSVSignatureElement0 *pInputElement = m_PSV.GetInputElement0(i);
  739. DXASSERT_NOMSG(pInputElement);
  740. memcpy(pInputElement, &m_SigInputElements[i], sizeof(PSVSignatureElement0));
  741. }
  742. for (unsigned i = 0; i < m_PSV.GetSigOutputElements(); i++) {
  743. PSVSignatureElement0 *pOutputElement = m_PSV.GetOutputElement0(i);
  744. DXASSERT_NOMSG(pOutputElement);
  745. memcpy(pOutputElement, &m_SigOutputElements[i], sizeof(PSVSignatureElement0));
  746. }
  747. for (unsigned i = 0; i < m_PSV.GetSigPatchConstOrPrimElements(); i++) {
  748. PSVSignatureElement0 *pPatchConstOrPrimElement = m_PSV.GetPatchConstOrPrimElement0(i);
  749. DXASSERT_NOMSG(pPatchConstOrPrimElement);
  750. memcpy(pPatchConstOrPrimElement, &m_SigPatchConstOrPrimElements[i], sizeof(PSVSignatureElement0));
  751. }
  752. // Gather ViewID dependency information
  753. auto &viewState = m_Module.GetSerializedViewIdState();
  754. if (!viewState.empty()) {
  755. const uint32_t *pSrc = viewState.data();
  756. const uint32_t InputScalars = *(pSrc++);
  757. uint32_t OutputScalars[4];
  758. for (unsigned streamIndex = 0; streamIndex < 4; streamIndex++) {
  759. OutputScalars[streamIndex] = *(pSrc++);
  760. pSrc = CopyViewIDState(pSrc, InputScalars, OutputScalars[streamIndex], m_PSV.GetViewIDOutputMask(streamIndex), m_PSV.GetInputToOutputTable(streamIndex));
  761. if (!SM->IsGS())
  762. break;
  763. }
  764. if (SM->IsHS() || SM->IsMS()) {
  765. const uint32_t PCScalars = *(pSrc++);
  766. pSrc = CopyViewIDState(pSrc, InputScalars, PCScalars, m_PSV.GetViewIDPCOutputMask(), m_PSV.GetInputToPCOutputTable());
  767. } else if (SM->IsDS()) {
  768. const uint32_t PCScalars = *(pSrc++);
  769. pSrc = CopyViewIDState(pSrc, PCScalars, OutputScalars[0], PSVComponentMask(), m_PSV.GetPCInputToOutputTable());
  770. }
  771. DXASSERT_NOMSG(viewState.data() + viewState.size() == pSrc);
  772. }
  773. }
  774. ULONG cbWritten;
  775. IFT(pStream->Write(m_PSVBuffer.data(), m_PSVBufferSize, &cbWritten));
  776. DXASSERT_NOMSG(cbWritten == m_PSVBufferSize);
  777. }
  778. };
  779. // Size-checked writer
  780. // on overrun: throw buffer_overrun{};
  781. // on overlap: throw buffer_overlap{};
  782. class CheckedWriter {
  783. char *Ptr;
  784. size_t Size;
  785. size_t Offset;
  786. public:
  787. class exception : public std::exception {};
  788. class buffer_overrun : public exception {
  789. public:
  790. buffer_overrun() noexcept {}
  791. virtual const char * what() const noexcept override {
  792. return ("buffer_overrun");
  793. }
  794. };
  795. class buffer_overlap : public exception {
  796. public:
  797. buffer_overlap() noexcept {}
  798. virtual const char * what() const noexcept override {
  799. return ("buffer_overlap");
  800. }
  801. };
  802. CheckedWriter(void *ptr, size_t size) :
  803. Ptr(reinterpret_cast<char*>(ptr)), Size(size), Offset(0) {}
  804. size_t GetOffset() const { return Offset; }
  805. void Reset(size_t offset = 0) {
  806. if (offset >= Size) throw buffer_overrun{};
  807. Offset = offset;
  808. }
  809. // offset is absolute, ensure offset is >= current offset
  810. void Advance(size_t offset = 0) {
  811. if (offset < Offset) throw buffer_overlap{};
  812. if (offset >= Size) throw buffer_overrun{};
  813. Offset = offset;
  814. }
  815. void CheckBounds(size_t size) const {
  816. assert(Offset <= Size && "otherwise, offset larger than size");
  817. if (size > Size - Offset)
  818. throw buffer_overrun{};
  819. }
  820. template <typename T>
  821. T *Cast(size_t size = 0) {
  822. if (0 == size) size = sizeof(T);
  823. CheckBounds(size);
  824. return reinterpret_cast<T*>(Ptr + Offset);
  825. }
  826. // Map and Write advance Offset:
  827. template <typename T>
  828. T &Map() {
  829. const size_t size = sizeof(T);
  830. T * p = Cast<T>(size);
  831. Offset += size;
  832. return *p;
  833. }
  834. template <typename T>
  835. T *MapArray(size_t count = 1) {
  836. const size_t size = sizeof(T) * count;
  837. T *p = Cast<T>(size);
  838. Offset += size;
  839. return p;
  840. }
  841. template <typename T>
  842. void Write(const T &obj) {
  843. const size_t size = sizeof(T);
  844. *Cast<T>(size) = obj;
  845. Offset += size;
  846. }
  847. template <typename T>
  848. void WriteArray(const T *pArray, size_t count = 1) {
  849. const size_t size = sizeof(T) * count;
  850. memcpy(Cast<T>(size), pArray, size);
  851. Offset += size;
  852. }
  853. };
  854. // Like DXIL container, RDAT itself is a mini container that contains multiple RDAT parts
  855. class RDATPart {
  856. public:
  857. virtual uint32_t GetPartSize() const { return 0; }
  858. virtual void Write(void *ptr) {}
  859. virtual RuntimeDataPartType GetType() const { return RuntimeDataPartType::Invalid; }
  860. virtual ~RDATPart() {}
  861. };
  862. // Most RDAT parts are tables each containing a list of structures of same type.
  863. // Exceptions are string table and index table because each string or list of
  864. // indicies can be of different sizes.
  865. template <class T>
  866. class RDATTable : public RDATPart {
  867. protected:
  868. std::vector<T> m_rows;
  869. public:
  870. virtual void Insert(T *data) {}
  871. virtual ~RDATTable() {}
  872. void Insert(const T &data) {
  873. m_rows.push_back(data);
  874. }
  875. void Write(void *ptr) {
  876. char *pCur = (char*)ptr;
  877. RuntimeDataTableHeader &header = *reinterpret_cast<RuntimeDataTableHeader*>(pCur);
  878. header.RecordCount = m_rows.size();
  879. header.RecordStride = sizeof(T);
  880. pCur += sizeof(RuntimeDataTableHeader);
  881. memcpy(pCur, m_rows.data(), header.RecordCount * header.RecordStride);
  882. };
  883. uint32_t GetPartSize() const {
  884. if (m_rows.empty())
  885. return 0;
  886. return sizeof(RuntimeDataTableHeader) + m_rows.size() * sizeof(T);
  887. }
  888. };
  889. // Resource table will contain a list of RuntimeDataResourceInfo in order of
  890. // CBuffer, Sampler, SRV, and UAV resource classes.
  891. class ResourceTable : public RDATTable<RuntimeDataResourceInfo> {
  892. public:
  893. RuntimeDataPartType GetType() const { return RuntimeDataPartType::ResourceTable; }
  894. };
  895. class FunctionTable : public RDATTable<RuntimeDataFunctionInfo> {
  896. public:
  897. RuntimeDataPartType GetType() const { return RuntimeDataPartType::FunctionTable; }
  898. };
  899. class StringBufferPart : public RDATPart {
  900. private:
  901. StringMap<uint32_t> m_StringMap;
  902. SmallVector<char, 256> m_StringBuffer;
  903. public:
  904. StringBufferPart() : m_StringMap(), m_StringBuffer() {
  905. // Always start string table with null so empty/null strings have offset of zero
  906. m_StringBuffer.push_back('\0');
  907. }
  908. // returns the offset of the name inserted
  909. uint32_t Insert(StringRef name) {
  910. if (name.empty())
  911. return 0;
  912. // Don't add duplicate strings
  913. auto found = m_StringMap.find(name);
  914. if (found != m_StringMap.end())
  915. return found->second;
  916. uint32_t prevIndex = (uint32_t)m_StringBuffer.size();
  917. m_StringMap[name] = prevIndex;
  918. m_StringBuffer.reserve(m_StringBuffer.size() + name.size() + 1);
  919. m_StringBuffer.append(name.begin(), name.end());
  920. m_StringBuffer.push_back('\0');
  921. return prevIndex;
  922. }
  923. RuntimeDataPartType GetType() const { return RuntimeDataPartType::StringBuffer; }
  924. uint32_t GetPartSize() const { return m_StringBuffer.size(); }
  925. void Write(void *ptr) { memcpy(ptr, m_StringBuffer.data(), m_StringBuffer.size()); }
  926. };
  927. struct IndexArraysPart : public RDATPart {
  928. private:
  929. std::vector<uint32_t> m_IndexBuffer;
  930. // Use m_IndexSet with CmpIndices to avoid duplicate index arrays
  931. struct CmpIndices {
  932. const IndexArraysPart &Table;
  933. CmpIndices(const IndexArraysPart &table) : Table(table) {}
  934. bool operator()(uint32_t left, uint32_t right) const {
  935. const uint32_t *pLeft = Table.m_IndexBuffer.data() + left;
  936. const uint32_t *pRight = Table.m_IndexBuffer.data() + right;
  937. if (*pLeft != *pRight)
  938. return (*pLeft < *pRight);
  939. uint32_t count = *pLeft;
  940. for (unsigned i = 0; i < count; i++) {
  941. ++pLeft; ++pRight;
  942. if (*pLeft != *pRight)
  943. return (*pLeft < *pRight);
  944. }
  945. return false;
  946. }
  947. };
  948. std::set<uint32_t, CmpIndices> m_IndexSet;
  949. public:
  950. IndexArraysPart() : m_IndexBuffer(), m_IndexSet(*this) {}
  951. template <class iterator>
  952. uint32_t AddIndex(iterator begin, iterator end) {
  953. uint32_t newOffset = m_IndexBuffer.size();
  954. m_IndexBuffer.push_back(0); // Size: update after insertion
  955. m_IndexBuffer.insert(m_IndexBuffer.end(), begin, end);
  956. m_IndexBuffer[newOffset] = (m_IndexBuffer.size() - newOffset) - 1;
  957. // Check for duplicate, return new offset if not duplicate
  958. auto insertResult = m_IndexSet.insert(newOffset);
  959. if (insertResult.second)
  960. return newOffset;
  961. // Otherwise it was a duplicate, so chop off the size and return the original
  962. m_IndexBuffer.resize(newOffset);
  963. return *insertResult.first;
  964. }
  965. RuntimeDataPartType GetType() const { return RuntimeDataPartType::IndexArrays; }
  966. uint32_t GetPartSize() const {
  967. return sizeof(uint32_t) * m_IndexBuffer.size();
  968. }
  969. void Write(void *ptr) {
  970. memcpy(ptr, m_IndexBuffer.data(), m_IndexBuffer.size() * sizeof(uint32_t));
  971. }
  972. };
  973. class RawBytesPart : public RDATPart {
  974. private:
  975. std::unordered_map<const void *, uint32_t> m_PtrMap;
  976. std::vector<char> m_DataBuffer;
  977. public:
  978. RawBytesPart() : m_DataBuffer() {}
  979. uint32_t Insert(const void *pData, size_t dataSize) {
  980. auto it = m_PtrMap.find(pData);
  981. if (it != m_PtrMap.end())
  982. return it->second;
  983. if (dataSize + m_DataBuffer.size() > UINT_MAX)
  984. return UINT_MAX;
  985. uint32_t offset = (uint32_t)m_DataBuffer.size();
  986. m_DataBuffer.reserve(m_DataBuffer.size() + dataSize);
  987. m_DataBuffer.insert(m_DataBuffer.end(),
  988. (const char*)pData, (const char*)pData + dataSize);
  989. return offset;
  990. }
  991. RuntimeDataPartType GetType() const { return RuntimeDataPartType::RawBytes; }
  992. uint32_t GetPartSize() const { return m_DataBuffer.size(); }
  993. void Write(void *ptr) { memcpy(ptr, m_DataBuffer.data(), m_DataBuffer.size()); }
  994. };
  995. class SubobjectTable : public RDATTable<RuntimeDataSubobjectInfo> {
  996. public:
  997. RuntimeDataPartType GetType() const { return RuntimeDataPartType::SubobjectTable; }
  998. };
  999. using namespace DXIL;
  1000. class DxilRDATWriter : public DxilPartWriter {
  1001. private:
  1002. SmallVector<char, 1024> m_RDATBuffer;
  1003. std::vector<std::unique_ptr<RDATPart>> m_Parts;
  1004. typedef llvm::SmallSetVector<uint32_t, 8> Indices;
  1005. typedef std::unordered_map<const llvm::Function *, Indices> FunctionIndexMap;
  1006. FunctionIndexMap m_FuncToResNameOffset; // list of resources used
  1007. FunctionIndexMap m_FuncToDependencies; // list of unresolved functions used
  1008. unsigned m_ValMajor, m_ValMinor;
  1009. struct ShaderCompatInfo {
  1010. ShaderCompatInfo()
  1011. : minMajor(6), minMinor(0),
  1012. mask(((unsigned)1 << (unsigned)DXIL::ShaderKind::Invalid) - 1)
  1013. {}
  1014. unsigned minMajor, minMinor, mask;
  1015. };
  1016. typedef std::unordered_map<const llvm::Function*, ShaderCompatInfo> FunctionShaderCompatMap;
  1017. FunctionShaderCompatMap m_FuncToShaderCompat;
  1018. void UpdateFunctionToShaderCompat(const llvm::Function* dxilFunc) {
  1019. for (const auto &user : dxilFunc->users()) {
  1020. if (const llvm::CallInst *CI = dyn_cast<const llvm::CallInst>(user)) {
  1021. // Find calling function
  1022. const llvm::Function *F = cast<const llvm::Function>(CI->getParent()->getParent());
  1023. // Insert or lookup info
  1024. ShaderCompatInfo &info = m_FuncToShaderCompat[F];
  1025. unsigned major, minor, mask;
  1026. // bWithTranslation = true for library modules
  1027. OP::GetMinShaderModelAndMask(CI, /*bWithTranslation*/true,
  1028. m_ValMajor, m_ValMinor,
  1029. major, minor, mask);
  1030. if (major > info.minMajor) {
  1031. info.minMajor = major;
  1032. info.minMinor = minor;
  1033. } else if (major == info.minMajor && minor > info.minMinor) {
  1034. info.minMinor = minor;
  1035. }
  1036. info.mask &= mask;
  1037. }
  1038. }
  1039. }
  1040. const llvm::Function *FindUsingFunction(const llvm::Value *User) {
  1041. if (const llvm::Instruction *I = dyn_cast<const llvm::Instruction>(User)) {
  1042. // Instruction should be inside a basic block, which is in a function
  1043. return cast<const llvm::Function>(I->getParent()->getParent());
  1044. }
  1045. // User can be either instruction, constant, or operator. But User is an
  1046. // operator only if constant is a scalar value, not resource pointer.
  1047. const llvm::Constant *CU = cast<const llvm::Constant>(User);
  1048. if (!CU->user_empty())
  1049. return FindUsingFunction(*CU->user_begin());
  1050. else
  1051. return nullptr;
  1052. }
  1053. void UpdateFunctionToResourceInfo(const DxilResourceBase *resource,
  1054. uint32_t offset) {
  1055. Constant *var = resource->GetGlobalSymbol();
  1056. if (var) {
  1057. for (auto user : var->users()) {
  1058. // Find the function.
  1059. const llvm::Function *F = FindUsingFunction(user);
  1060. if (!F)
  1061. continue;
  1062. if (m_FuncToResNameOffset.find(F) == m_FuncToResNameOffset.end()) {
  1063. m_FuncToResNameOffset[F] = Indices();
  1064. }
  1065. m_FuncToResNameOffset[F].insert(offset);
  1066. }
  1067. }
  1068. }
  1069. void InsertToResourceTable(DxilResourceBase &resource,
  1070. ResourceClass resourceClass,
  1071. uint32_t &resourceIndex) {
  1072. uint32_t stringIndex = m_pStringBufferPart->Insert(resource.GetGlobalName());
  1073. UpdateFunctionToResourceInfo(&resource, resourceIndex++);
  1074. RuntimeDataResourceInfo info = {};
  1075. info.ID = resource.GetID();
  1076. info.Class = static_cast<uint32_t>(resourceClass);
  1077. info.Kind = static_cast<uint32_t>(resource.GetKind());
  1078. info.Space = resource.GetSpaceID();
  1079. info.LowerBound = resource.GetLowerBound();
  1080. info.UpperBound = resource.GetUpperBound();
  1081. info.Name = stringIndex;
  1082. info.Flags = 0;
  1083. if (ResourceClass::UAV == resourceClass) {
  1084. DxilResource *pRes = static_cast<DxilResource*>(&resource);
  1085. if (pRes->HasCounter())
  1086. info.Flags |= static_cast<uint32_t>(DxilResourceFlag::UAVCounter);
  1087. if (pRes->IsGloballyCoherent())
  1088. info.Flags |= static_cast<uint32_t>(DxilResourceFlag::UAVGloballyCoherent);
  1089. if (pRes->IsROV())
  1090. info.Flags |= static_cast<uint32_t>(DxilResourceFlag::UAVRasterizerOrderedView);
  1091. // TODO: add dynamic index flag
  1092. }
  1093. m_pResourceTable->Insert(info);
  1094. }
  1095. void UpdateResourceInfo(const DxilModule &DM) {
  1096. // Try to allocate string table for resources. String table is a sequence
  1097. // of strings delimited by \0
  1098. uint32_t resourceIndex = 0;
  1099. for (auto &resource : DM.GetCBuffers()) {
  1100. InsertToResourceTable(*resource.get(), ResourceClass::CBuffer, resourceIndex);
  1101. }
  1102. for (auto &resource : DM.GetSamplers()) {
  1103. InsertToResourceTable(*resource.get(), ResourceClass::Sampler, resourceIndex);
  1104. }
  1105. for (auto &resource : DM.GetSRVs()) {
  1106. InsertToResourceTable(*resource.get(), ResourceClass::SRV, resourceIndex);
  1107. }
  1108. for (auto &resource : DM.GetUAVs()) {
  1109. InsertToResourceTable(*resource.get(), ResourceClass::UAV, resourceIndex);
  1110. }
  1111. }
  1112. void UpdateFunctionDependency(llvm::Function *F) {
  1113. for (const auto &user : F->users()) {
  1114. const llvm::Function *userFunction = FindUsingFunction(user);
  1115. uint32_t index = m_pStringBufferPart->Insert(F->getName());
  1116. if (m_FuncToDependencies.find(userFunction) ==
  1117. m_FuncToDependencies.end()) {
  1118. m_FuncToDependencies[userFunction] =
  1119. Indices();
  1120. }
  1121. m_FuncToDependencies[userFunction].insert(index);
  1122. }
  1123. }
  1124. void UpdateFunctionInfo(const DxilModule &DM) {
  1125. // We must select the appropriate shader mask for the validator version,
  1126. // so we don't set any bits the validator doesn't recognize.
  1127. unsigned ValidShaderMask = (1 << ((unsigned)DXIL::ShaderKind::Amplification + 1)) - 1;
  1128. if (DXIL::CompareVersions(m_ValMajor, m_ValMinor, 1, 5) < 0) {
  1129. ValidShaderMask = (1 << ((unsigned)DXIL::ShaderKind::Callable + 1)) - 1;
  1130. }
  1131. for (auto &function : DM.GetModule()->getFunctionList()) {
  1132. if (function.isDeclaration() && !function.isIntrinsic()) {
  1133. if (OP::IsDxilOpFunc(&function)) {
  1134. // update min shader model and shader stage mask per function
  1135. UpdateFunctionToShaderCompat(&function);
  1136. } else {
  1137. // collect unresolved dependencies per function
  1138. UpdateFunctionDependency(&function);
  1139. }
  1140. }
  1141. }
  1142. for (auto &function : DM.GetModule()->getFunctionList()) {
  1143. if (!function.isDeclaration()) {
  1144. StringRef mangled = function.getName();
  1145. StringRef unmangled = hlsl::dxilutil::DemangleFunctionName(function.getName());
  1146. uint32_t mangledIndex = m_pStringBufferPart->Insert(mangled);
  1147. uint32_t unmangledIndex = m_pStringBufferPart->Insert(unmangled);
  1148. // Update resource Index
  1149. uint32_t resourceIndex = UINT_MAX;
  1150. uint32_t functionDependencies = UINT_MAX;
  1151. uint32_t payloadSizeInBytes = 0;
  1152. uint32_t attrSizeInBytes = 0;
  1153. uint32_t shaderKind = static_cast<uint32_t>(DXIL::ShaderKind::Library);
  1154. if (m_FuncToResNameOffset.find(&function) != m_FuncToResNameOffset.end())
  1155. resourceIndex =
  1156. m_pIndexArraysPart->AddIndex(m_FuncToResNameOffset[&function].begin(),
  1157. m_FuncToResNameOffset[&function].end());
  1158. if (m_FuncToDependencies.find(&function) != m_FuncToDependencies.end())
  1159. functionDependencies =
  1160. m_pIndexArraysPart->AddIndex(m_FuncToDependencies[&function].begin(),
  1161. m_FuncToDependencies[&function].end());
  1162. if (DM.HasDxilFunctionProps(&function)) {
  1163. auto props = DM.GetDxilFunctionProps(&function);
  1164. if (props.IsClosestHit() || props.IsAnyHit()) {
  1165. payloadSizeInBytes = props.ShaderProps.Ray.payloadSizeInBytes;
  1166. attrSizeInBytes = props.ShaderProps.Ray.attributeSizeInBytes;
  1167. }
  1168. else if (props.IsMiss()) {
  1169. payloadSizeInBytes = props.ShaderProps.Ray.payloadSizeInBytes;
  1170. }
  1171. else if (props.IsCallable()) {
  1172. payloadSizeInBytes = props.ShaderProps.Ray.paramSizeInBytes;
  1173. }
  1174. shaderKind = (uint32_t)props.shaderKind;
  1175. }
  1176. ShaderFlags flags = ShaderFlags::CollectShaderFlags(&function, &DM);
  1177. RuntimeDataFunctionInfo info = {};
  1178. info.Name = mangledIndex;
  1179. info.UnmangledName = unmangledIndex;
  1180. info.ShaderKind = shaderKind;
  1181. info.Resources = resourceIndex;
  1182. info.FunctionDependencies = functionDependencies;
  1183. info.PayloadSizeInBytes = payloadSizeInBytes;
  1184. info.AttributeSizeInBytes = attrSizeInBytes;
  1185. uint64_t featureFlags = flags.GetFeatureInfo();
  1186. info.FeatureInfo1 = featureFlags & 0xffffffff;
  1187. info.FeatureInfo2 = (featureFlags >> 32) & 0xffffffff;
  1188. // Init min target 6.0
  1189. unsigned minMajor = 6, minMinor = 0;
  1190. // Increase min target based on feature flags:
  1191. if (flags.GetUseNativeLowPrecision() && flags.GetLowPrecisionPresent()) {
  1192. minMinor = 2;
  1193. } else if (flags.GetBarycentrics() || flags.GetViewID()) {
  1194. minMinor = 1;
  1195. }
  1196. if ((DXIL::ShaderKind)shaderKind == DXIL::ShaderKind::Library) {
  1197. // Init mask to all kinds for library functions
  1198. info.ShaderStageFlag = ValidShaderMask;
  1199. } else {
  1200. // Init mask to current kind for shader functions
  1201. info.ShaderStageFlag = (unsigned)1 << shaderKind;
  1202. }
  1203. auto it = m_FuncToShaderCompat.find(&function);
  1204. if (it != m_FuncToShaderCompat.end()) {
  1205. auto &compatInfo = it->second;
  1206. if (compatInfo.minMajor > minMajor) {
  1207. minMajor = compatInfo.minMajor;
  1208. minMinor = compatInfo.minMinor;
  1209. } else if (compatInfo.minMinor > minMinor) {
  1210. minMinor = compatInfo.minMinor;
  1211. }
  1212. info.ShaderStageFlag &= compatInfo.mask;
  1213. }
  1214. info.MinShaderTarget = EncodeVersion((DXIL::ShaderKind)shaderKind, minMajor, minMinor);
  1215. m_pFunctionTable->Insert(info);
  1216. }
  1217. }
  1218. }
  1219. void UpdateSubobjectInfo(const DxilModule &DM) {
  1220. if (!DM.GetSubobjects())
  1221. return;
  1222. for (auto &it : DM.GetSubobjects()->GetSubobjects()) {
  1223. auto &obj = *it.second;
  1224. RuntimeDataSubobjectInfo info = {};
  1225. info.Name = m_pStringBufferPart->Insert(obj.GetName());
  1226. info.Kind = (uint32_t)obj.GetKind();
  1227. bool bLocalRS = false;
  1228. switch (obj.GetKind()) {
  1229. case DXIL::SubobjectKind::StateObjectConfig:
  1230. obj.GetStateObjectConfig(info.StateObjectConfig.Flags);
  1231. break;
  1232. case DXIL::SubobjectKind::LocalRootSignature:
  1233. bLocalRS = true;
  1234. __fallthrough;
  1235. case DXIL::SubobjectKind::GlobalRootSignature: {
  1236. const void *Data;
  1237. obj.GetRootSignature(bLocalRS, Data, info.RootSignature.SizeInBytes);
  1238. info.RootSignature.RawBytesOffset =
  1239. m_pRawBytesPart->Insert(Data, info.RootSignature.SizeInBytes);
  1240. break;
  1241. }
  1242. case DXIL::SubobjectKind::SubobjectToExportsAssociation: {
  1243. llvm::StringRef Subobject;
  1244. const char * const * Exports;
  1245. uint32_t NumExports;
  1246. std::vector<uint32_t> ExportIndices;
  1247. obj.GetSubobjectToExportsAssociation(Subobject, Exports, NumExports);
  1248. info.SubobjectToExportsAssociation.Subobject =
  1249. m_pStringBufferPart->Insert(Subobject);
  1250. ExportIndices.resize(NumExports);
  1251. for (unsigned i = 0; i < NumExports; ++i) {
  1252. ExportIndices[i] = m_pStringBufferPart->Insert(Exports[i]);
  1253. }
  1254. info.SubobjectToExportsAssociation.Exports =
  1255. m_pIndexArraysPart->AddIndex(
  1256. ExportIndices.begin(), ExportIndices.end());
  1257. break;
  1258. }
  1259. case DXIL::SubobjectKind::RaytracingShaderConfig:
  1260. obj.GetRaytracingShaderConfig(
  1261. info.RaytracingShaderConfig.MaxPayloadSizeInBytes,
  1262. info.RaytracingShaderConfig.MaxAttributeSizeInBytes);
  1263. break;
  1264. case DXIL::SubobjectKind::RaytracingPipelineConfig:
  1265. obj.GetRaytracingPipelineConfig(
  1266. info.RaytracingPipelineConfig.MaxTraceRecursionDepth);
  1267. break;
  1268. case DXIL::SubobjectKind::HitGroup:
  1269. {
  1270. HitGroupType hgType;
  1271. StringRef AnyHit;
  1272. StringRef ClosestHit;
  1273. StringRef Intersection;
  1274. obj.GetHitGroup(hgType, AnyHit, ClosestHit, Intersection);
  1275. info.HitGroup.Type = (uint32_t)hgType;
  1276. info.HitGroup.AnyHit = m_pStringBufferPart->Insert(AnyHit);
  1277. info.HitGroup.ClosestHit = m_pStringBufferPart->Insert(ClosestHit);
  1278. info.HitGroup.Intersection = m_pStringBufferPart->Insert(Intersection);
  1279. break;
  1280. }
  1281. case DXIL::SubobjectKind::RaytracingPipelineConfig1:
  1282. obj.GetRaytracingPipelineConfig1(
  1283. info.RaytracingPipelineConfig1.MaxTraceRecursionDepth,
  1284. info.RaytracingPipelineConfig1.Flags);
  1285. break;
  1286. }
  1287. m_pSubobjectTable->Insert(info);
  1288. }
  1289. }
  1290. void CreateParts() {
  1291. #define ADD_PART(type) \
  1292. m_Parts.emplace_back(llvm::make_unique<type>()); \
  1293. m_p##type = reinterpret_cast<type*>(m_Parts.back().get());
  1294. ADD_PART(StringBufferPart);
  1295. ADD_PART(ResourceTable);
  1296. ADD_PART(FunctionTable);
  1297. ADD_PART(IndexArraysPart);
  1298. ADD_PART(RawBytesPart);
  1299. ADD_PART(SubobjectTable);
  1300. #undef ADD_PART
  1301. }
  1302. StringBufferPart *m_pStringBufferPart;
  1303. IndexArraysPart *m_pIndexArraysPart;
  1304. RawBytesPart *m_pRawBytesPart;
  1305. FunctionTable *m_pFunctionTable;
  1306. ResourceTable *m_pResourceTable;
  1307. SubobjectTable *m_pSubobjectTable;
  1308. public:
  1309. DxilRDATWriter(const DxilModule &mod)
  1310. : m_RDATBuffer(), m_Parts(), m_FuncToResNameOffset() {
  1311. // Keep track of validator version so we can make a compatible RDAT
  1312. mod.GetValidatorVersion(m_ValMajor, m_ValMinor);
  1313. CreateParts();
  1314. UpdateResourceInfo(mod);
  1315. UpdateFunctionInfo(mod);
  1316. UpdateSubobjectInfo(mod);
  1317. // Delete any empty parts:
  1318. std::vector<std::unique_ptr<RDATPart>>::iterator it = m_Parts.begin();
  1319. while (it != m_Parts.end()) {
  1320. if (it->get()->GetPartSize() == 0) {
  1321. it = m_Parts.erase(it);
  1322. }
  1323. else
  1324. it++;
  1325. }
  1326. }
  1327. uint32_t size() const override {
  1328. // header + offset array
  1329. uint32_t total = sizeof(RuntimeDataHeader) + m_Parts.size() * sizeof(uint32_t);
  1330. // For each part: part header + part size
  1331. for (auto &part : m_Parts)
  1332. total += sizeof(RuntimeDataPartHeader) + PSVALIGN4(part->GetPartSize());
  1333. return total;
  1334. }
  1335. void write(AbstractMemoryStream *pStream) override {
  1336. try {
  1337. m_RDATBuffer.resize(size(), 0);
  1338. CheckedWriter W(m_RDATBuffer.data(), m_RDATBuffer.size());
  1339. // write RDAT header
  1340. RuntimeDataHeader &header = W.Map<RuntimeDataHeader>();
  1341. header.Version = RDAT_Version_10;
  1342. header.PartCount = m_Parts.size();
  1343. // map offsets
  1344. uint32_t *offsets = W.MapArray<uint32_t>(header.PartCount);
  1345. // write parts
  1346. unsigned i = 0;
  1347. for (auto &part : m_Parts) {
  1348. offsets[i++] = W.GetOffset();
  1349. RuntimeDataPartHeader &partHeader = W.Map<RuntimeDataPartHeader>();
  1350. partHeader.Type = part->GetType();
  1351. partHeader.Size = PSVALIGN4(part->GetPartSize());
  1352. DXASSERT(partHeader.Size, "otherwise, failed to remove empty part");
  1353. char *bytes = W.MapArray<char>(partHeader.Size);
  1354. part->Write(bytes);
  1355. }
  1356. }
  1357. catch (CheckedWriter::exception e) {
  1358. throw hlsl::Exception(DXC_E_GENERAL_INTERNAL_ERROR, e.what());
  1359. }
  1360. ULONG cbWritten;
  1361. IFT(pStream->Write(m_RDATBuffer.data(), m_RDATBuffer.size(), &cbWritten));
  1362. DXASSERT_NOMSG(cbWritten == m_RDATBuffer.size());
  1363. }
  1364. };
  1365. DxilPartWriter *hlsl::NewPSVWriter(const DxilModule &M, uint32_t PSVVersion) {
  1366. return new DxilPSVWriter(M, PSVVersion);
  1367. }
  1368. DxilPartWriter *hlsl::NewRDATWriter(const DxilModule &M) {
  1369. return new DxilRDATWriter(M);
  1370. }
  1371. class DxilContainerWriter_impl : public DxilContainerWriter {
  1372. private:
  1373. class DxilPart {
  1374. public:
  1375. DxilPartHeader Header;
  1376. WriteFn Write;
  1377. DxilPart(uint32_t fourCC, uint32_t size, WriteFn write) : Write(write) {
  1378. Header.PartFourCC = fourCC;
  1379. Header.PartSize = size;
  1380. }
  1381. };
  1382. llvm::SmallVector<DxilPart, 8> m_Parts;
  1383. public:
  1384. void AddPart(uint32_t FourCC, uint32_t Size, WriteFn Write) override {
  1385. m_Parts.emplace_back(FourCC, Size, Write);
  1386. }
  1387. uint32_t size() const override {
  1388. uint32_t partSize = 0;
  1389. for (auto &part : m_Parts) {
  1390. partSize += part.Header.PartSize;
  1391. }
  1392. return (uint32_t)GetDxilContainerSizeFromParts((uint32_t)m_Parts.size(), partSize);
  1393. }
  1394. void write(AbstractMemoryStream *pStream) override {
  1395. DxilContainerHeader header;
  1396. const uint32_t PartCount = (uint32_t)m_Parts.size();
  1397. uint32_t containerSizeInBytes = size();
  1398. InitDxilContainer(&header, PartCount, containerSizeInBytes);
  1399. IFT(pStream->Reserve(header.ContainerSizeInBytes));
  1400. IFT(WriteStreamValue(pStream, header));
  1401. uint32_t offset = sizeof(header) + (uint32_t)GetOffsetTableSize(PartCount);
  1402. for (auto &&part : m_Parts) {
  1403. IFT(WriteStreamValue(pStream, offset));
  1404. offset += sizeof(DxilPartHeader) + part.Header.PartSize;
  1405. }
  1406. for (auto &&part : m_Parts) {
  1407. IFT(WriteStreamValue(pStream, part.Header));
  1408. size_t start = pStream->GetPosition();
  1409. part.Write(pStream);
  1410. DXASSERT_LOCALVAR(start, pStream->GetPosition() - start == (size_t)part.Header.PartSize, "out of bound");
  1411. }
  1412. DXASSERT(containerSizeInBytes == (uint32_t)pStream->GetPosition(), "else stream size is incorrect");
  1413. }
  1414. };
  1415. DxilContainerWriter *hlsl::NewDxilContainerWriter() {
  1416. return new DxilContainerWriter_impl();
  1417. }
  1418. static bool HasDebugInfo(const Module &M) {
  1419. for (Module::const_named_metadata_iterator NMI = M.named_metadata_begin(),
  1420. NME = M.named_metadata_end();
  1421. NMI != NME; ++NMI) {
  1422. if (NMI->getName().startswith("llvm.dbg.")) {
  1423. return true;
  1424. }
  1425. }
  1426. return false;
  1427. }
  1428. static void GetPaddedProgramPartSize(AbstractMemoryStream *pStream,
  1429. uint32_t &bitcodeInUInt32,
  1430. uint32_t &bitcodePaddingBytes) {
  1431. bitcodeInUInt32 = pStream->GetPtrSize();
  1432. bitcodePaddingBytes = (bitcodeInUInt32 % 4);
  1433. bitcodeInUInt32 = (bitcodeInUInt32 / 4) + (bitcodePaddingBytes ? 1 : 0);
  1434. }
  1435. static void WriteProgramPart(const ShaderModel *pModel,
  1436. AbstractMemoryStream *pModuleBitcode,
  1437. AbstractMemoryStream *pStream) {
  1438. DXASSERT(pModel != nullptr, "else generation should have failed");
  1439. DxilProgramHeader programHeader;
  1440. uint32_t shaderVersion =
  1441. EncodeVersion(pModel->GetKind(), pModel->GetMajor(), pModel->GetMinor());
  1442. unsigned dxilMajor, dxilMinor;
  1443. pModel->GetDxilVersion(dxilMajor, dxilMinor);
  1444. uint32_t dxilVersion = DXIL::MakeDxilVersion(dxilMajor, dxilMinor);
  1445. InitProgramHeader(programHeader, shaderVersion, dxilVersion, pModuleBitcode->GetPtrSize());
  1446. uint32_t programInUInt32, programPaddingBytes;
  1447. GetPaddedProgramPartSize(pModuleBitcode, programInUInt32,
  1448. programPaddingBytes);
  1449. ULONG cbWritten;
  1450. IFT(WriteStreamValue(pStream, programHeader));
  1451. IFT(pStream->Write(pModuleBitcode->GetPtr(), pModuleBitcode->GetPtrSize(),
  1452. &cbWritten));
  1453. if (programPaddingBytes) {
  1454. uint32_t paddingValue = 0;
  1455. IFT(pStream->Write(&paddingValue, programPaddingBytes, &cbWritten));
  1456. }
  1457. }
  1458. namespace {
  1459. class RootSignatureWriter : public DxilPartWriter {
  1460. private:
  1461. std::vector<uint8_t> m_Sig;
  1462. public:
  1463. RootSignatureWriter(std::vector<uint8_t> &&S) : m_Sig(std::move(S)) {}
  1464. uint32_t size() const { return m_Sig.size(); }
  1465. void write(AbstractMemoryStream *pStream) {
  1466. ULONG cbWritten;
  1467. IFT(pStream->Write(m_Sig.data(), size(), &cbWritten));
  1468. }
  1469. };
  1470. } // namespace
  1471. void hlsl::SerializeDxilContainerForModule(DxilModule *pModule,
  1472. AbstractMemoryStream *pModuleBitcode,
  1473. AbstractMemoryStream *pFinalStream,
  1474. llvm::StringRef DebugName,
  1475. SerializeDxilFlags Flags,
  1476. DxilShaderHash *pShaderHashOut,
  1477. AbstractMemoryStream *pReflectionStreamOut,
  1478. AbstractMemoryStream *pRootSigStreamOut) {
  1479. // TODO: add a flag to update the module and remove information that is not part
  1480. // of DXIL proper and is used only to assemble the container.
  1481. DXASSERT_NOMSG(pModule != nullptr);
  1482. DXASSERT_NOMSG(pModuleBitcode != nullptr);
  1483. DXASSERT_NOMSG(pFinalStream != nullptr);
  1484. unsigned ValMajor, ValMinor;
  1485. pModule->GetValidatorVersion(ValMajor, ValMinor);
  1486. if (DXIL::CompareVersions(ValMajor, ValMinor, 1, 1) < 0)
  1487. Flags &= ~SerializeDxilFlags::IncludeDebugNamePart;
  1488. bool bSupportsShaderHash = DXIL::CompareVersions(ValMajor, ValMinor, 1, 5) >= 0;
  1489. bool bCompat_1_4 = DXIL::CompareVersions(ValMajor, ValMinor, 1, 5) < 0;
  1490. bool bEmitReflection = Flags & SerializeDxilFlags::IncludeReflectionPart ||
  1491. pReflectionStreamOut;
  1492. DxilContainerWriter_impl writer;
  1493. // Write the feature part.
  1494. DxilFeatureInfoWriter featureInfoWriter(*pModule);
  1495. writer.AddPart(DFCC_FeatureInfo, featureInfoWriter.size(), [&](AbstractMemoryStream *pStream) {
  1496. featureInfoWriter.write(pStream);
  1497. });
  1498. std::unique_ptr<DxilProgramSignatureWriter> pInputSigWriter = nullptr;
  1499. std::unique_ptr<DxilProgramSignatureWriter> pOutputSigWriter = nullptr;
  1500. std::unique_ptr<DxilProgramSignatureWriter> pPatchConstOrPrimSigWriter = nullptr;
  1501. if (!pModule->GetShaderModel()->IsLib()) {
  1502. DXIL::TessellatorDomain domain = DXIL::TessellatorDomain::Undefined;
  1503. if (pModule->GetShaderModel()->IsHS() || pModule->GetShaderModel()->IsDS())
  1504. domain = pModule->GetTessellatorDomain();
  1505. pInputSigWriter = llvm::make_unique<DxilProgramSignatureWriter>(
  1506. pModule->GetInputSignature(), domain,
  1507. /*IsInput*/ true,
  1508. /*UseMinPrecision*/ pModule->GetUseMinPrecision(),
  1509. bCompat_1_4);
  1510. pOutputSigWriter = llvm::make_unique<DxilProgramSignatureWriter>(
  1511. pModule->GetOutputSignature(), domain,
  1512. /*IsInput*/ false,
  1513. /*UseMinPrecision*/ pModule->GetUseMinPrecision(),
  1514. bCompat_1_4);
  1515. // Write the input and output signature parts.
  1516. writer.AddPart(DFCC_InputSignature, pInputSigWriter->size(),
  1517. [&](AbstractMemoryStream *pStream) {
  1518. pInputSigWriter->write(pStream);
  1519. });
  1520. writer.AddPart(DFCC_OutputSignature, pOutputSigWriter->size(),
  1521. [&](AbstractMemoryStream *pStream) {
  1522. pOutputSigWriter->write(pStream);
  1523. });
  1524. pPatchConstOrPrimSigWriter = llvm::make_unique<DxilProgramSignatureWriter>(
  1525. pModule->GetPatchConstOrPrimSignature(), domain,
  1526. /*IsInput*/ pModule->GetShaderModel()->IsDS(),
  1527. /*UseMinPrecision*/ pModule->GetUseMinPrecision(),
  1528. bCompat_1_4);
  1529. if (pModule->GetPatchConstOrPrimSignature().GetElements().size()) {
  1530. writer.AddPart(DFCC_PatchConstantSignature,
  1531. pPatchConstOrPrimSigWriter->size(),
  1532. [&](AbstractMemoryStream *pStream) {
  1533. pPatchConstOrPrimSigWriter->write(pStream);
  1534. });
  1535. }
  1536. }
  1537. std::unique_ptr<DxilRDATWriter> pRDATWriter = nullptr;
  1538. std::unique_ptr<DxilPSVWriter> pPSVWriter = nullptr;
  1539. unsigned int major, minor;
  1540. pModule->GetDxilVersion(major, minor);
  1541. RootSignatureWriter rootSigWriter(std::move(pModule->GetSerializedRootSignature())); // Grab RS here
  1542. DXASSERT_NOMSG(pModule->GetSerializedRootSignature().empty());
  1543. bool bMetadataStripped = false;
  1544. if (pModule->GetShaderModel()->IsLib()) {
  1545. DXASSERT(pModule->GetSerializedRootSignature().empty(),
  1546. "otherwise, library has root signature outside subobject definitions");
  1547. // Write the DxilRuntimeData (RDAT) part.
  1548. pRDATWriter = llvm::make_unique<DxilRDATWriter>(*pModule);
  1549. writer.AddPart(
  1550. DFCC_RuntimeData, pRDATWriter->size(),
  1551. [&](AbstractMemoryStream *pStream) { pRDATWriter->write(pStream); });
  1552. bMetadataStripped |= pModule->StripSubobjectsFromMetadata();
  1553. pModule->ResetSubobjects(nullptr);
  1554. } else {
  1555. // Write the DxilPipelineStateValidation (PSV0) part.
  1556. pPSVWriter = llvm::make_unique<DxilPSVWriter>(*pModule);
  1557. writer.AddPart(
  1558. DFCC_PipelineStateValidation, pPSVWriter->size(),
  1559. [&](AbstractMemoryStream *pStream) { pPSVWriter->write(pStream); });
  1560. // Write the root signature (RTS0) part.
  1561. if (rootSigWriter.size()) {
  1562. if (pRootSigStreamOut) {
  1563. // Write root signature wrapped in container for separate output
  1564. DxilContainerWriter_impl rootSigContainerWriter;
  1565. rootSigContainerWriter.AddPart(
  1566. DFCC_RootSignature, rootSigWriter.size(),
  1567. [&](AbstractMemoryStream *pStream) { rootSigWriter.write(pStream); });
  1568. rootSigContainerWriter.write(pRootSigStreamOut);
  1569. }
  1570. if ((Flags & SerializeDxilFlags::StripRootSignature) == 0) {
  1571. // Write embedded root signature
  1572. writer.AddPart(
  1573. DFCC_RootSignature, rootSigWriter.size(),
  1574. [&](AbstractMemoryStream *pStream) { rootSigWriter.write(pStream); });
  1575. }
  1576. bMetadataStripped |= pModule->StripRootSignatureFromMetadata();
  1577. }
  1578. }
  1579. // If metadata was stripped, re-serialize the input module.
  1580. CComPtr<AbstractMemoryStream> pInputProgramStream = pModuleBitcode;
  1581. if (bMetadataStripped) {
  1582. pInputProgramStream.Release();
  1583. IFT(CreateMemoryStream(DxcGetThreadMallocNoRef(), &pInputProgramStream));
  1584. raw_stream_ostream outStream(pInputProgramStream.p);
  1585. WriteBitcodeToFile(pModule->GetModule(), outStream, true);
  1586. }
  1587. // If we have debug information present, serialize it to a debug part, then use the stripped version as the canonical program version.
  1588. CComPtr<AbstractMemoryStream> pProgramStream = pInputProgramStream;
  1589. bool bModuleStripped = false;
  1590. bool bHasDebugInfo = HasDebugInfo(*pModule->GetModule());
  1591. if (bHasDebugInfo) {
  1592. uint32_t debugInUInt32, debugPaddingBytes;
  1593. GetPaddedProgramPartSize(pInputProgramStream, debugInUInt32, debugPaddingBytes);
  1594. if (Flags & SerializeDxilFlags::IncludeDebugInfoPart) {
  1595. writer.AddPart(DFCC_ShaderDebugInfoDXIL, debugInUInt32 * sizeof(uint32_t) + sizeof(DxilProgramHeader), [&](AbstractMemoryStream *pStream) {
  1596. WriteProgramPart(pModule->GetShaderModel(), pInputProgramStream, pStream);
  1597. });
  1598. }
  1599. llvm::StripDebugInfo(*pModule->GetModule());
  1600. pModule->StripDebugRelatedCode();
  1601. bModuleStripped = true;
  1602. } else {
  1603. // If no debug info, clear DebugNameDependOnSource
  1604. // (it's default, and this scenario can happen)
  1605. Flags &= ~SerializeDxilFlags::DebugNameDependOnSource;
  1606. }
  1607. // Clone module for reflection, strip function defs
  1608. std::unique_ptr<Module> reflectionModule;
  1609. if (bEmitReflection) {
  1610. // Retain usage information in metadata for reflection by:
  1611. // Upgrade validator version, re-emit metadata, then clone module for reflection.
  1612. // 0,0 = Not meant to be validated, support latest
  1613. pModule->SetValidatorVersion(0, 0);
  1614. pModule->ReEmitDxilResources();
  1615. pModule->EmitDxilCounters();
  1616. reflectionModule.reset(llvm::CloneModule(pModule->GetModule()));
  1617. // Now restore validator version on main module and re-emit metadata.
  1618. pModule->SetValidatorVersion(ValMajor, ValMinor);
  1619. pModule->ReEmitDxilResources();
  1620. for (Function &F : reflectionModule->functions()) {
  1621. if (!F.isDeclaration()) {
  1622. F.deleteBody();
  1623. }
  1624. }
  1625. // Just make sure this doesn't crash/assert on debug build:
  1626. DXASSERT_NOMSG(&reflectionModule->GetOrCreateDxilModule());
  1627. }
  1628. CComPtr<AbstractMemoryStream> pReflectionBitcodeStream;
  1629. uint32_t reflectPartSizeInBytes = 0;
  1630. if (bEmitReflection)
  1631. {
  1632. IFT(CreateMemoryStream(DxcGetThreadMallocNoRef(), &pReflectionBitcodeStream));
  1633. raw_stream_ostream outStream(pReflectionBitcodeStream.p);
  1634. WriteBitcodeToFile(reflectionModule.get(), outStream, false);
  1635. outStream.flush();
  1636. uint32_t reflectInUInt32 = 0, reflectPaddingBytes = 0;
  1637. GetPaddedProgramPartSize(pReflectionBitcodeStream, reflectInUInt32, reflectPaddingBytes);
  1638. reflectPartSizeInBytes = reflectInUInt32 * sizeof(uint32_t) + sizeof(DxilProgramHeader);
  1639. }
  1640. if (pReflectionStreamOut) {
  1641. DxilPartHeader partSTAT;
  1642. partSTAT.PartFourCC = DFCC_ShaderStatistics;
  1643. partSTAT.PartSize = reflectPartSizeInBytes;
  1644. IFT(WriteStreamValue(pReflectionStreamOut, partSTAT));
  1645. WriteProgramPart(pModule->GetShaderModel(), pReflectionBitcodeStream, pReflectionStreamOut);
  1646. // If library, we need RDAT part as well. For now, we just append it
  1647. if (pModule->GetShaderModel()->IsLib()) {
  1648. DxilPartHeader partRDAT;
  1649. partRDAT.PartFourCC = DFCC_RuntimeData;
  1650. partRDAT.PartSize = pRDATWriter->size();
  1651. IFT(WriteStreamValue(pReflectionStreamOut, partRDAT));
  1652. pRDATWriter->write(pReflectionStreamOut);
  1653. }
  1654. }
  1655. if (Flags & SerializeDxilFlags::IncludeReflectionPart) {
  1656. writer.AddPart(DFCC_ShaderStatistics, reflectPartSizeInBytes,
  1657. [pModule, pReflectionBitcodeStream](AbstractMemoryStream *pStream) {
  1658. WriteProgramPart(pModule->GetShaderModel(), pReflectionBitcodeStream, pStream);
  1659. });
  1660. }
  1661. if (Flags & SerializeDxilFlags::StripReflectionFromDxilPart) {
  1662. bModuleStripped |= pModule->StripReflection();
  1663. }
  1664. // If debug info or reflection was stripped, re-serialize the module.
  1665. if (bModuleStripped) {
  1666. pProgramStream.Release();
  1667. IFT(CreateMemoryStream(DxcGetThreadMallocNoRef(), &pProgramStream));
  1668. raw_stream_ostream outStream(pProgramStream.p);
  1669. WriteBitcodeToFile(pModule->GetModule(), outStream, false);
  1670. }
  1671. // Compute hash if needed.
  1672. DxilShaderHash HashContent;
  1673. SmallString<32> HashStr;
  1674. if (bSupportsShaderHash || pShaderHashOut ||
  1675. (Flags & SerializeDxilFlags::IncludeDebugNamePart &&
  1676. DebugName.empty()))
  1677. {
  1678. // If the debug name should be specific to the sources, base the name on the debug
  1679. // bitcode, which will include the source references, line numbers, etc. Otherwise,
  1680. // do it exclusively on the target shader bitcode.
  1681. llvm::MD5 md5;
  1682. if (Flags & SerializeDxilFlags::DebugNameDependOnSource) {
  1683. md5.update(ArrayRef<uint8_t>(pModuleBitcode->GetPtr(), pModuleBitcode->GetPtrSize()));
  1684. HashContent.Flags = (uint32_t)DxilShaderHashFlags::IncludesSource;
  1685. } else {
  1686. md5.update(ArrayRef<uint8_t>(pProgramStream->GetPtr(), pProgramStream->GetPtrSize()));
  1687. HashContent.Flags = (uint32_t)DxilShaderHashFlags::None;
  1688. }
  1689. md5.final(HashContent.Digest);
  1690. md5.stringifyResult(HashContent.Digest, HashStr);
  1691. }
  1692. // Serialize debug name if requested.
  1693. std::string DebugNameStr; // Used if constructing name based on hash
  1694. if (Flags & SerializeDxilFlags::IncludeDebugNamePart) {
  1695. if (DebugName.empty()) {
  1696. DebugNameStr += HashStr;
  1697. DebugNameStr += ".pdb";
  1698. DebugName = DebugNameStr;
  1699. }
  1700. // Calculate the size of the blob part.
  1701. const uint32_t DebugInfoContentLen = PSVALIGN4(
  1702. sizeof(DxilShaderDebugName) + DebugName.size() + 1); // 1 for null
  1703. writer.AddPart(DFCC_ShaderDebugName, DebugInfoContentLen,
  1704. [DebugName]
  1705. (AbstractMemoryStream *pStream)
  1706. {
  1707. DxilShaderDebugName NameContent;
  1708. NameContent.Flags = 0;
  1709. NameContent.NameLength = DebugName.size();
  1710. IFT(WriteStreamValue(pStream, NameContent));
  1711. ULONG cbWritten;
  1712. IFT(pStream->Write(DebugName.begin(), DebugName.size(), &cbWritten));
  1713. const char Pad[] = { '\0','\0','\0','\0' };
  1714. // Always writes at least one null to align size
  1715. unsigned padLen = (4 - ((sizeof(DxilShaderDebugName) + cbWritten) & 0x3));
  1716. IFT(pStream->Write(Pad, padLen, &cbWritten));
  1717. });
  1718. }
  1719. // Add hash to container if supported by validator version.
  1720. if (bSupportsShaderHash) {
  1721. writer.AddPart(DFCC_ShaderHash, sizeof(HashContent),
  1722. [HashContent]
  1723. (AbstractMemoryStream *pStream)
  1724. {
  1725. IFT(WriteStreamValue(pStream, HashContent));
  1726. });
  1727. }
  1728. // Write hash to separate output if requested.
  1729. if (pShaderHashOut) {
  1730. memcpy(pShaderHashOut, &HashContent, sizeof(DxilShaderHash));
  1731. }
  1732. // Compute padded bitcode size.
  1733. uint32_t programInUInt32, programPaddingBytes;
  1734. GetPaddedProgramPartSize(pProgramStream, programInUInt32, programPaddingBytes);
  1735. // Write the program part.
  1736. writer.AddPart(DFCC_DXIL, programInUInt32 * sizeof(uint32_t) + sizeof(DxilProgramHeader), [&](AbstractMemoryStream *pStream) {
  1737. WriteProgramPart(pModule->GetShaderModel(), pProgramStream, pStream);
  1738. });
  1739. writer.write(pFinalStream);
  1740. }
  1741. void hlsl::SerializeDxilContainerForRootSignature(hlsl::RootSignatureHandle *pRootSigHandle,
  1742. AbstractMemoryStream *pFinalStream) {
  1743. DXASSERT_NOMSG(pRootSigHandle != nullptr);
  1744. DXASSERT_NOMSG(pFinalStream != nullptr);
  1745. DxilContainerWriter_impl writer;
  1746. // Write the root signature (RTS0) part.
  1747. DxilProgramRootSignatureWriter rootSigWriter(*pRootSigHandle);
  1748. if (!pRootSigHandle->IsEmpty()) {
  1749. writer.AddPart(
  1750. DFCC_RootSignature, rootSigWriter.size(),
  1751. [&](AbstractMemoryStream *pStream) { rootSigWriter.write(pStream); });
  1752. }
  1753. writer.write(pFinalStream);
  1754. }