DxilDebugInstrumentation.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // DxilDebugInstrumentation.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. // Adds instrumentation that enables shader debugging in PIX //
  9. // //
  10. ///////////////////////////////////////////////////////////////////////////////
  11. #include "dxc/HLSL/DxilGenerationPass.h"
  12. #include "dxc/HLSL/DxilOperations.h"
  13. #include "dxc/HLSL/DxilModule.h"
  14. #include "llvm/IR/Module.h"
  15. #include "llvm/IR/Constants.h"
  16. #include "llvm/IR/InstIterator.h"
  17. #include "llvm/IR/IRBuilder.h"
  18. using namespace llvm;
  19. using namespace hlsl;
  20. // Overview of instrumentation:
  21. //
  22. // In summary, instructions are added that cause a "trace" of the execution of the shader to be written
  23. // out to a UAV. This trace is then used by a debugger application to provide a post-mortem debugging
  24. // experience that reconstructs the execution history of the shader.
  25. //
  26. // The trace is only required for a particular shader instance of interest, and a branchless mechanism
  27. // is used to write the trace either to an incrementing location within the UAV, or to a "dumping ground"
  28. // area at the top of the UAV if the instance is not of interest.
  29. //
  30. // The following modifications are made:
  31. //
  32. // First, instructions are added to the top of the entry point function that implement the following:
  33. // - Examine the input variables that define the instance of the shader that is running. This will
  34. // be SV_Position for pixel shaders, SV_Vertex+SV_Instance for vertex shaders, thread id for compute
  35. // shaders etc. If these system values need to be added to the shader, then they are also added to the
  36. // input signature, if appropriate.
  37. // - Compare the above variables with the instance of interest defined by the invoker of this pass.
  38. // Deduce two values: a multiplicand and an addend that together allow a branchless calculation of
  39. // the offset into the UAV at which to write via "offset = offset * multiplicand + addend."
  40. // If the instance is NOT of interest, the multiplicand is zero and the addend is
  41. // sizeof(UAV)-(a little bit), causing writes for uninteresting invocations to end up at the top of
  42. // the UAV. Otherwise the multiplicand is 1 and the addend is 0.
  43. // - Calculate an "instance identifier". Even with the above instance identification, several invocations may
  44. // end up matching the selection criteria. Specifically, this happens during a draw call in which many
  45. // triangles overlap the pixel of interest. More on this below.
  46. //
  47. // During execution, the instrumentation for most instructions cause data to be emitted to the UAV.
  48. // The index at which data is written is identified by treating the first uint32 of the UAV as an index
  49. // which is atomically incremented by the instrumentation. The very first value of this counter that is
  50. // encountered by each invocation is used as the "instance identifier" mentioned above. That instance
  51. // identifier is written out with each packet, since many pixel shaders executing in parallel will emit
  52. // interleaved packets, and the debugger application uses the identifiers to group packets from each separate
  53. // invocation together.
  54. //
  55. // If an instruction has a non-void and primitive return type, i.e. isn't a struct, then the instrumentation
  56. // will write that value out to the UAV as well as part of the "step" data packet.
  57. //
  58. // The limiting size of the UAV is enforced in a branchless way by ANDing the offset with a precomputed
  59. // value that is sizeof(UAV)-64. The actual size of the UAV allocated by the caller is required to be
  60. // a power of two plus 64 for this reason. The caller detects UAV overrun by examining a canary value
  61. // close to the end of the power-of-two size of the UAV. If this value has been overwritten, the debug session
  62. // is deemed to have overflowed the UAV. The caller will than allocate a UAV that is twice the size and
  63. // try again, up to a predefined maximum.
  64. // Keep this in sync with the same-named value in the debugger application's WinPixShaderUtils.h
  65. constexpr uint64_t DebugBufferDumpingGroundSize = 64 * 1024;
  66. // These definitions echo those in the debugger application's debugshaderrecord.h file
  67. enum DebugShaderModifierRecordType {
  68. DebugShaderModifierRecordTypeInvocationStartMarker,
  69. DebugShaderModifierRecordTypeStep,
  70. DebugShaderModifierRecordTypeEvent,
  71. DebugShaderModifierRecordTypeInputRegister,
  72. DebugShaderModifierRecordTypeReadRegister,
  73. DebugShaderModifierRecordTypeWrittenRegister,
  74. DebugShaderModifierRecordTypeRegisterRelativeIndex0,
  75. DebugShaderModifierRecordTypeRegisterRelativeIndex1,
  76. DebugShaderModifierRecordTypeRegisterRelativeIndex2,
  77. DebugShaderModifierRecordTypeDXILStepVoid = 251,
  78. DebugShaderModifierRecordTypeDXILStepFloat = 252,
  79. DebugShaderModifierRecordTypeDXILStepUint32 = 253,
  80. DebugShaderModifierRecordTypeDXILStepUint64 = 254,
  81. DebugShaderModifierRecordTypeDXILStepDouble = 255,
  82. };
  83. // These structs echo those in the debugger application's debugshaderrecord.h file, but are recapitulated here
  84. // because the originals use unnamed unions which are disallowed by DXCompiler's build.
  85. //
  86. #pragma pack(push,4)
  87. struct DebugShaderModifierRecordHeader {
  88. union {
  89. struct {
  90. uint32_t SizeDwords : 4;
  91. uint32_t Flags : 4;
  92. uint32_t Type : 8;
  93. uint32_t HeaderPayload : 16;
  94. } Details;
  95. uint32_t u32Header;
  96. } Header;
  97. uint32_t UID;
  98. };
  99. struct DebugShaderModifierRecordDXILStepBase {
  100. union {
  101. struct {
  102. uint32_t SizeDwords : 4;
  103. uint32_t Flags : 4;
  104. uint32_t Type : 8;
  105. uint32_t Opcode : 16;
  106. } Details;
  107. uint32_t u32Header;
  108. } Header;
  109. uint32_t UID;
  110. uint32_t InstructionOffset;
  111. };
  112. template< typename ReturnType >
  113. struct DebugShaderModifierRecordDXILStep : public DebugShaderModifierRecordDXILStepBase {
  114. ReturnType ReturnValue;
  115. };
  116. template< >
  117. struct DebugShaderModifierRecordDXILStep<void> : public DebugShaderModifierRecordDXILStepBase {
  118. };
  119. #pragma pack(pop)
  120. uint32_t DebugShaderModifierRecordPayloadSizeDwords(size_t recordTotalSizeBytes) {
  121. return ((recordTotalSizeBytes - sizeof(DebugShaderModifierRecordHeader)) / sizeof(uint32_t));
  122. }
  123. class DxilDebugInstrumentation : public ModulePass {
  124. private:
  125. union ParametersAllTogether {
  126. unsigned Parameters[3];
  127. struct PixelShaderParameters {
  128. unsigned X;
  129. unsigned Y;
  130. } PixelShader;
  131. struct VertexShaderParameters {
  132. unsigned VertexId;
  133. unsigned InstanceId;
  134. } VertexShader;
  135. struct ComputeShaderParameters {
  136. unsigned ThreadIdX;
  137. unsigned ThreadIdY;
  138. unsigned ThreadIdZ;
  139. } ComputeShader;
  140. struct GeometryShaderParameters {
  141. unsigned PrimitiveId;
  142. unsigned InstanceId;
  143. } GeometryShader;
  144. } m_Parameters = { 0,0,0 };
  145. union SystemValueIndices {
  146. struct PixelShaderParameters {
  147. unsigned Position;
  148. } PixelShader;
  149. struct VertexShaderParameters {
  150. unsigned VertexId;
  151. unsigned InstanceId;
  152. } VertexShader;
  153. struct GeometryShaderParameters {
  154. unsigned PrimitiveId;
  155. unsigned InstanceId;
  156. } GeometryShader;
  157. };
  158. uint64_t m_UAVSize = 1024*1024;
  159. Value * m_SelectionCriterion = nullptr;
  160. CallInst * m_HandleForUAV = nullptr;
  161. Value * m_InvocationId = nullptr;
  162. // Together these two values allow branchless writing to the UAV. An invocation of the shader
  163. // is either of interest or not (e.g. it writes to the pixel the user selected for debugging
  164. // or it doesn't). If not of interest, debugging output will still occur, but it will be
  165. // relegated to the very top few bytes of the UAV. Invocations of interest, by contrast, will
  166. // be written to the UAV at sequentially increasing offsets.
  167. // This value will either be one or zero (one if the invocation is of interest, zero otherwise)
  168. Value * m_OffsetMultiplicand = nullptr;
  169. // This will either be zero (if the invocation is of interest) or (UAVSize)-(SmallValue) if not.
  170. Value * m_OffsetAddend = nullptr;
  171. Constant * m_OffsetMask = nullptr;
  172. std::map<uint32_t, Value *> m_IncrementInstructionBySize;
  173. unsigned int m_InstructionIndex = 0;
  174. struct BuilderContext {
  175. Module &M;
  176. DxilModule &DM;
  177. LLVMContext & Ctx;
  178. OP * HlslOP;
  179. IRBuilder<> & Builder;
  180. };
  181. uint32_t m_RemainingReservedSpaceInBytes = 0;
  182. Value * m_CurrentIndex = nullptr;
  183. public:
  184. static char ID; // Pass identification, replacement for typeid
  185. explicit DxilDebugInstrumentation() : ModulePass(ID) {}
  186. const char *getPassName() const override { return "Add PIX debug instrumentation"; }
  187. void applyOptions(PassOptions O) override;
  188. bool runOnModule(Module &M) override;
  189. private:
  190. SystemValueIndices addRequiredSystemValues(BuilderContext &BC);
  191. void addUAV(BuilderContext &BC);
  192. void addInvocationSelectionProlog(BuilderContext &BC, SystemValueIndices SVIndices);
  193. Value * addPixelShaderProlog(BuilderContext &BC, SystemValueIndices SVIndices);
  194. Value * addGeometryShaderProlog(BuilderContext &BC, SystemValueIndices SVIndices);
  195. Value * addComputeShaderProlog(BuilderContext &BC);
  196. Value * addVertexShaderProlog(BuilderContext &BC, SystemValueIndices SVIndices);
  197. void addDebugEntryValue(BuilderContext &BC, Value * TheValue);
  198. void addInvocationStartMarker(BuilderContext &BC);
  199. void reserveDebugEntrySpace(BuilderContext &BC, uint32_t SpaceInDwords);
  200. void addStepDebugEntry(BuilderContext &BC, Instruction *Inst);
  201. uint32_t UAVDumpingGroundOffset();
  202. template<typename ReturnType>
  203. void addStepEntryForType(DebugShaderModifierRecordType RecordType, BuilderContext &BC, Instruction *Inst);
  204. };
  205. void DxilDebugInstrumentation::applyOptions(PassOptions O) {
  206. for (const auto & option : O) {
  207. if (0 == option.first.compare("parameter0")) {
  208. m_Parameters.Parameters[0] = atoi(option.second.data());
  209. }
  210. else if (0 == option.first.compare("parameter1")) {
  211. m_Parameters.Parameters[1] = atoi(option.second.data());
  212. }
  213. else if (0 == option.first.compare("parameter2")) {
  214. m_Parameters.Parameters[2] = atoi(option.second.data());
  215. }
  216. else if (0 == option.first.compare("UAVSize")) {
  217. m_UAVSize = std::stoull(option.second.data());
  218. }
  219. }
  220. }
  221. uint32_t DxilDebugInstrumentation::UAVDumpingGroundOffset() {
  222. return static_cast<uint32_t>(m_UAVSize - DebugBufferDumpingGroundSize);
  223. }
  224. DxilDebugInstrumentation::SystemValueIndices DxilDebugInstrumentation::addRequiredSystemValues(BuilderContext &BC) {
  225. SystemValueIndices SVIndices{};
  226. hlsl::DxilSignature & InputSignature = BC.DM.GetInputSignature();
  227. auto & InputElements = InputSignature.GetElements();
  228. auto ShaderModel = BC.DM.GetShaderModel();
  229. switch (ShaderModel->GetKind()) {
  230. case DXIL::ShaderKind::Pixel: {
  231. auto Existing_SV_Position = std::find_if(
  232. InputElements.begin(), InputElements.end(),
  233. [](const std::unique_ptr<DxilSignatureElement> & Element) {
  234. return Element->GetSemantic()->GetKind() == hlsl::DXIL::SemanticKind::Position; });
  235. // SV_Position, if present, has to have full mask, so we needn't worry
  236. // about the shader having selected components that don't include x or y.
  237. // If not present, we add it.
  238. if (Existing_SV_Position == InputElements.end()) {
  239. auto Added_SV_Position = std::make_unique<DxilSignatureElement>(DXIL::SigPointKind::PSIn);
  240. Added_SV_Position->Initialize("Position", hlsl::CompType::getF32(), hlsl::DXIL::InterpolationMode::Linear, 1, 4);
  241. Added_SV_Position->AppendSemanticIndex(0);
  242. Added_SV_Position->SetSigPointKind(DXIL::SigPointKind::PSIn);
  243. Added_SV_Position->SetKind(hlsl::DXIL::SemanticKind::Position);
  244. auto index = InputSignature.AppendElement(std::move(Added_SV_Position));
  245. SVIndices.PixelShader.Position = InputElements[index]->GetID();
  246. }
  247. else {
  248. SVIndices.PixelShader.Position = Existing_SV_Position->get()->GetID();
  249. }
  250. }
  251. break;
  252. case DXIL::ShaderKind::Vertex: {
  253. {
  254. auto Existing_SV_VertexId = std::find_if(
  255. InputElements.begin(), InputElements.end(),
  256. [](const std::unique_ptr<DxilSignatureElement> & Element) {
  257. return Element->GetSemantic()->GetKind() == hlsl::DXIL::SemanticKind::VertexID; });
  258. if (Existing_SV_VertexId == InputElements.end()) {
  259. auto Added_SV_VertexId = std::make_unique<DxilSignatureElement>(DXIL::SigPointKind::VSIn);
  260. Added_SV_VertexId->Initialize("VertexId", hlsl::CompType::getF32(), hlsl::DXIL::InterpolationMode::Undefined, 1, 1);
  261. Added_SV_VertexId->AppendSemanticIndex(0);
  262. Added_SV_VertexId->SetSigPointKind(DXIL::SigPointKind::VSIn);
  263. Added_SV_VertexId->SetKind(hlsl::DXIL::SemanticKind::VertexID);
  264. auto index = InputSignature.AppendElement(std::move(Added_SV_VertexId));
  265. SVIndices.VertexShader.VertexId = InputElements[index]->GetID();
  266. }
  267. else {
  268. SVIndices.VertexShader.VertexId = Existing_SV_VertexId->get()->GetID();
  269. }
  270. }
  271. {
  272. auto Existing_SV_InstanceId = std::find_if(
  273. InputElements.begin(), InputElements.end(),
  274. [](const std::unique_ptr<DxilSignatureElement> & Element) {
  275. return Element->GetSemantic()->GetKind() == hlsl::DXIL::SemanticKind::InstanceID; });
  276. if (Existing_SV_InstanceId == InputElements.end()) {
  277. auto Added_SV_InstanceId = std::make_unique<DxilSignatureElement>(DXIL::SigPointKind::VSIn);
  278. Added_SV_InstanceId->Initialize("InstanceId", hlsl::CompType::getF32(), hlsl::DXIL::InterpolationMode::Undefined, 1, 1);
  279. Added_SV_InstanceId->AppendSemanticIndex(0);
  280. Added_SV_InstanceId->SetSigPointKind(DXIL::SigPointKind::VSIn);
  281. Added_SV_InstanceId->SetKind(hlsl::DXIL::SemanticKind::InstanceID);
  282. auto index = InputSignature.AppendElement(std::move(Added_SV_InstanceId));
  283. SVIndices.VertexShader.InstanceId = InputElements[index]->GetID();
  284. }
  285. else {
  286. SVIndices.VertexShader.InstanceId = Existing_SV_InstanceId->get()->GetID();
  287. }
  288. }
  289. }
  290. break;
  291. case DXIL::ShaderKind::Geometry:
  292. // GS Instance Id and Primitive Id are not in the input signature
  293. break;
  294. case DXIL::ShaderKind::Compute:
  295. // Compute thread Id is not in the input signature
  296. break;
  297. default:
  298. assert(false); // guaranteed by runOnModule
  299. }
  300. return SVIndices;
  301. }
  302. Value * DxilDebugInstrumentation::addComputeShaderProlog(BuilderContext &BC) {
  303. Constant* Zero32Arg = BC.HlslOP->GetU32Const(0);
  304. Constant* One32Arg = BC.HlslOP->GetU32Const(1);
  305. Constant* Two32Arg = BC.HlslOP->GetU32Const(2);
  306. auto ThreadIdFunc = BC.HlslOP->GetOpFunc(DXIL::OpCode::ThreadId, Type::getInt32Ty(BC.Ctx));
  307. Constant* Opcode = BC.HlslOP->GetU32Const((unsigned)DXIL::OpCode::ThreadId);
  308. auto ThreadIdX = BC.Builder.CreateCall(ThreadIdFunc, { Opcode, Zero32Arg }, "ThreadIdX");
  309. auto ThreadIdY = BC.Builder.CreateCall(ThreadIdFunc, { Opcode, One32Arg }, "ThreadIdY");
  310. auto ThreadIdZ = BC.Builder.CreateCall(ThreadIdFunc, { Opcode, Two32Arg }, "ThreadIdZ");
  311. // Compare to expected thread ID
  312. auto CompareToX = BC.Builder.CreateICmpEQ(ThreadIdX, BC.HlslOP->GetU32Const(m_Parameters.ComputeShader.ThreadIdX), "CompareToThreadIdX");
  313. auto CompareToY = BC.Builder.CreateICmpEQ(ThreadIdY, BC.HlslOP->GetU32Const(m_Parameters.ComputeShader.ThreadIdY), "CompareToThreadIdY");
  314. auto CompareToZ = BC.Builder.CreateICmpEQ(ThreadIdZ, BC.HlslOP->GetU32Const(m_Parameters.ComputeShader.ThreadIdZ), "CompareToThreadIdZ");
  315. auto CompareXAndY = BC.Builder.CreateAnd(CompareToX, CompareToY, "CompareXAndY");
  316. auto CompareAll = BC.Builder.CreateAnd(CompareXAndY, CompareToZ, "CompareAll");
  317. return CompareAll;
  318. }
  319. Value * DxilDebugInstrumentation::addVertexShaderProlog(BuilderContext &BC, SystemValueIndices SVIndices) {
  320. Constant* Zero32Arg = BC.HlslOP->GetU32Const(0);
  321. Constant* Zero8Arg = BC.HlslOP->GetI8Const(0);
  322. UndefValue* UndefArg = UndefValue::get(Type::getInt32Ty(BC.Ctx));
  323. auto LoadInputOpFunc = BC.HlslOP->GetOpFunc(DXIL::OpCode::LoadInput, Type::getInt32Ty(BC.Ctx));
  324. Constant* LoadInputOpcode = BC.HlslOP->GetU32Const((unsigned)DXIL::OpCode::LoadInput);
  325. Constant* SV_Vert_ID = BC.HlslOP->GetU32Const(SVIndices.VertexShader.VertexId);
  326. auto VertId = BC.Builder.CreateCall(LoadInputOpFunc,
  327. { LoadInputOpcode, SV_Vert_ID, Zero32Arg /*row*/, Zero8Arg /*column*/, UndefArg }, "VertId");
  328. Constant* SV_Instance_ID = BC.HlslOP->GetU32Const(SVIndices.VertexShader.InstanceId);
  329. auto InstanceId = BC.Builder.CreateCall(LoadInputOpFunc,
  330. { LoadInputOpcode, SV_Instance_ID, Zero32Arg /*row*/, Zero8Arg /*column*/, UndefArg }, "InstanceId");
  331. // Compare to expected vertex ID and instance ID
  332. auto CompareToVert = BC.Builder.CreateICmpEQ(VertId, BC.HlslOP->GetU32Const(m_Parameters.VertexShader.VertexId), "CompareToVertId");
  333. auto CompareToInstance = BC.Builder.CreateICmpEQ(InstanceId, BC.HlslOP->GetU32Const(m_Parameters.VertexShader.InstanceId), "CompareToInstanceId");
  334. auto CompareBoth = BC.Builder.CreateAnd(CompareToVert, CompareToInstance, "CompareBoth");
  335. return CompareBoth;
  336. }
  337. Value * DxilDebugInstrumentation::addGeometryShaderProlog(BuilderContext &BC, SystemValueIndices SVIndices) {
  338. auto PrimitiveIdOpFunc = BC.HlslOP->GetOpFunc(DXIL::OpCode::PrimitiveID, Type::getInt32Ty(BC.Ctx));
  339. Constant* PrimitiveIdOpcode = BC.HlslOP->GetU32Const((unsigned)DXIL::OpCode::PrimitiveID);
  340. auto PrimId = BC.Builder.CreateCall(PrimitiveIdOpFunc,
  341. { PrimitiveIdOpcode }, "PrimId");
  342. auto CompareToPrim = BC.Builder.CreateICmpEQ(PrimId, BC.HlslOP->GetU32Const(m_Parameters.GeometryShader.PrimitiveId), "CompareToPrimId");
  343. if (BC.DM.GetGSInstanceCount() <= 1) {
  344. return CompareToPrim;
  345. }
  346. auto GSInstanceIdOpFunc = BC.HlslOP->GetOpFunc(DXIL::OpCode::GSInstanceID, Type::getInt32Ty(BC.Ctx));
  347. Constant* GSInstanceIdOpcode = BC.HlslOP->GetU32Const((unsigned)DXIL::OpCode::GSInstanceID);
  348. auto GSInstanceId = BC.Builder.CreateCall(GSInstanceIdOpFunc,
  349. { GSInstanceIdOpcode }, "GSInstanceId");
  350. // Compare to expected vertex ID and instance ID
  351. auto CompareToInstance = BC.Builder.CreateICmpEQ(GSInstanceId, BC.HlslOP->GetU32Const(m_Parameters.GeometryShader.InstanceId), "CompareToInstanceId");
  352. auto CompareBoth = BC.Builder.CreateAnd(CompareToPrim, CompareToInstance, "CompareBoth");
  353. return CompareBoth;
  354. }
  355. Value * DxilDebugInstrumentation::addPixelShaderProlog(BuilderContext &BC, SystemValueIndices SVIndices) {
  356. Constant* Zero32Arg = BC.HlslOP->GetU32Const(0);
  357. Constant* Zero8Arg = BC.HlslOP->GetI8Const(0);
  358. Constant* One8Arg = BC.HlslOP->GetI8Const(1);
  359. UndefValue* UndefArg = UndefValue::get(Type::getInt32Ty(BC.Ctx));
  360. // Convert SV_POSITION to UINT
  361. Value * XAsInt;
  362. Value * YAsInt;
  363. {
  364. auto LoadInputOpFunc = BC.HlslOP->GetOpFunc(DXIL::OpCode::LoadInput, Type::getFloatTy(BC.Ctx));
  365. Constant* LoadInputOpcode = BC.HlslOP->GetU32Const((unsigned)DXIL::OpCode::LoadInput);
  366. Constant* SV_Pos_ID = BC.HlslOP->GetU32Const(SVIndices.PixelShader.Position);
  367. auto XPos = BC.Builder.CreateCall(LoadInputOpFunc,
  368. { LoadInputOpcode, SV_Pos_ID, Zero32Arg /*row*/, Zero8Arg /*column*/, UndefArg }, "XPos");
  369. auto YPos = BC.Builder.CreateCall(LoadInputOpFunc,
  370. { LoadInputOpcode, SV_Pos_ID, Zero32Arg /*row*/, One8Arg /*column*/, UndefArg }, "YPos");
  371. XAsInt = BC.Builder.CreateCast(Instruction::CastOps::FPToUI, XPos, Type::getInt32Ty(BC.Ctx), "XIndex");
  372. YAsInt = BC.Builder.CreateCast(Instruction::CastOps::FPToUI, YPos, Type::getInt32Ty(BC.Ctx), "YIndex");
  373. }
  374. // Compare to expected pixel position and primitive ID
  375. auto CompareToX = BC.Builder.CreateICmpEQ(XAsInt, BC.HlslOP->GetU32Const(m_Parameters.PixelShader.X), "CompareToX");
  376. auto CompareToY = BC.Builder.CreateICmpEQ(YAsInt, BC.HlslOP->GetU32Const(m_Parameters.PixelShader.Y), "CompareToY");
  377. auto ComparePos = BC.Builder.CreateAnd(CompareToX, CompareToY, "ComparePos");
  378. return ComparePos;
  379. }
  380. void DxilDebugInstrumentation::addUAV(BuilderContext &BC)
  381. {
  382. // Set up a UAV with structure of a single int
  383. unsigned int UAVResourceHandle = static_cast<unsigned int>(BC.DM.GetUAVs().size());
  384. SmallVector<llvm::Type*, 1> Elements{ Type::getInt32Ty(BC.Ctx) };
  385. llvm::StructType *UAVStructTy = llvm::StructType::create(Elements, "PIX_DebugUAV_Type");
  386. std::unique_ptr<DxilResource> pUAV = llvm::make_unique<DxilResource>();
  387. pUAV->SetGlobalName("PIX_DebugUAVName");
  388. pUAV->SetGlobalSymbol(UndefValue::get(UAVStructTy->getPointerTo()));
  389. pUAV->SetID(UAVResourceHandle);
  390. pUAV->SetSpaceID((unsigned int)-2); // This is the reserved-for-tools register space
  391. pUAV->SetSampleCount(1);
  392. pUAV->SetGloballyCoherent(false);
  393. pUAV->SetHasCounter(false);
  394. pUAV->SetCompType(CompType::getI32());
  395. pUAV->SetLowerBound(0);
  396. pUAV->SetRangeSize(1);
  397. pUAV->SetKind(DXIL::ResourceKind::RawBuffer);
  398. pUAV->SetRW(true);
  399. auto ID = BC.DM.AddUAV(std::move(pUAV));
  400. assert(ID == UAVResourceHandle);
  401. BC.DM.m_ShaderFlags.SetEnableRawAndStructuredBuffers(true);
  402. // Create handle for the newly-added UAV
  403. Function* CreateHandleOpFunc = BC.HlslOP->GetOpFunc(DXIL::OpCode::CreateHandle, Type::getVoidTy(BC.Ctx));
  404. Constant* CreateHandleOpcodeArg = BC.HlslOP->GetU32Const((unsigned)DXIL::OpCode::CreateHandle);
  405. Constant* UAVVArg = BC.HlslOP->GetI8Const(static_cast<std::underlying_type<DxilResourceBase::Class>::type>(DXIL::ResourceClass::UAV));
  406. Constant* MetaDataArg = BC.HlslOP->GetU32Const(ID); // position of the metadata record in the corresponding metadata list
  407. Constant* IndexArg = BC.HlslOP->GetU32Const(0); //
  408. Constant* FalseArg = BC.HlslOP->GetI1Const(0); // non-uniform resource index: false
  409. m_HandleForUAV = BC.Builder.CreateCall(CreateHandleOpFunc,
  410. { CreateHandleOpcodeArg, UAVVArg, MetaDataArg, IndexArg, FalseArg }, "PIX_DebugUAV_Handle");
  411. }
  412. void DxilDebugInstrumentation::addInvocationSelectionProlog(BuilderContext &BC, SystemValueIndices SVIndices) {
  413. auto ShaderModel = BC.DM.GetShaderModel();
  414. Value * ParameterTestResult;
  415. switch (ShaderModel->GetKind()) {
  416. case DXIL::ShaderKind::Pixel:
  417. ParameterTestResult = addPixelShaderProlog(BC, SVIndices);
  418. break;
  419. case DXIL::ShaderKind::Geometry:
  420. ParameterTestResult = addGeometryShaderProlog(BC, SVIndices);
  421. break;
  422. case DXIL::ShaderKind::Vertex:
  423. ParameterTestResult = addVertexShaderProlog(BC, SVIndices);
  424. break;
  425. case DXIL::ShaderKind::Compute:
  426. ParameterTestResult = addComputeShaderProlog(BC);
  427. break;
  428. default:
  429. assert(false); // guaranteed by runOnModule
  430. }
  431. // This is a convenient place to calculate the values that modify the UAV offset for invocations of interest and for
  432. // UAV size.
  433. m_OffsetMultiplicand = BC.Builder.CreateCast(Instruction::CastOps::ZExt, ParameterTestResult, Type::getInt32Ty(BC.Ctx), "OffsetMultiplicand");
  434. auto InverseOffsetMultiplicand = BC.Builder.CreateSub(BC.HlslOP->GetU32Const(1), m_OffsetMultiplicand, "ComplementOfMultiplicand");
  435. m_OffsetAddend = BC.Builder.CreateMul(BC.HlslOP->GetU32Const(UAVDumpingGroundOffset()), InverseOffsetMultiplicand, "OffsetAddend");
  436. m_OffsetMask = BC.HlslOP->GetU32Const(UAVDumpingGroundOffset() - 1);
  437. m_SelectionCriterion = ParameterTestResult;
  438. }
  439. void DxilDebugInstrumentation::reserveDebugEntrySpace(BuilderContext &BC, uint32_t SpaceInBytes) {
  440. assert(m_CurrentIndex == nullptr);
  441. assert(m_RemainingReservedSpaceInBytes == 0);
  442. m_RemainingReservedSpaceInBytes = SpaceInBytes;
  443. // Insert the UAV increment instruction:
  444. Function* AtomicOpFunc = BC.HlslOP->GetOpFunc(OP::OpCode::AtomicBinOp, Type::getInt32Ty(BC.Ctx));
  445. Constant* AtomicBinOpcode = BC.HlslOP->GetU32Const((unsigned)OP::OpCode::AtomicBinOp);
  446. Constant* AtomicAdd = BC.HlslOP->GetU32Const((unsigned)DXIL::AtomicBinOpCode::Add);
  447. Constant* Zero32Arg = BC.HlslOP->GetU32Const(0);
  448. UndefValue* UndefArg = UndefValue::get(Type::getInt32Ty(BC.Ctx));
  449. // so inc will be zero for uninteresting invocations:
  450. Value * IncrementForThisInvocation;
  451. auto findIncrementInstruction = m_IncrementInstructionBySize.find(SpaceInBytes);
  452. if (findIncrementInstruction == m_IncrementInstructionBySize.end()) {
  453. Constant* Increment = BC.HlslOP->GetU32Const(SpaceInBytes);
  454. auto it = m_IncrementInstructionBySize.emplace(
  455. SpaceInBytes, BC.Builder.CreateMul(Increment, m_OffsetMultiplicand, "IncrementForThisInvocation"));
  456. findIncrementInstruction = it.first;
  457. }
  458. IncrementForThisInvocation = findIncrementInstruction->second;
  459. auto PreviousValue = BC.Builder.CreateCall(AtomicOpFunc, {
  460. AtomicBinOpcode,// i32, ; opcode
  461. m_HandleForUAV, // %dx.types.Handle, ; resource handle
  462. AtomicAdd, // i32, ; binary operation code : EXCHANGE, IADD, AND, OR, XOR, IMIN, IMAX, UMIN, UMAX
  463. Zero32Arg, // i32, ; coordinate c0: index in bytes
  464. UndefArg, // i32, ; coordinate c1 (unused)
  465. UndefArg, // i32, ; coordinate c2 (unused)
  466. IncrementForThisInvocation, // i32); increment value
  467. }, "UAVIncResult");
  468. if (m_InvocationId == nullptr)
  469. {
  470. m_InvocationId = PreviousValue;
  471. }
  472. auto MaskedForLimit = BC.Builder.CreateAnd(PreviousValue, m_OffsetMask, "MaskedForUAVLimit");
  473. // The return value will either end up being itself (multiplied by one and added with zero)
  474. // or the "dump uninteresting things here" value of (UAVSize - a bit).
  475. auto MultipliedForInterest = BC.Builder.CreateMul(MaskedForLimit, m_OffsetMultiplicand, "MultipliedForInterest");
  476. auto AddedForInterest = BC.Builder.CreateAdd(MultipliedForInterest, m_OffsetAddend, "AddedForInterest");
  477. m_CurrentIndex = AddedForInterest;
  478. }
  479. void DxilDebugInstrumentation::addDebugEntryValue(BuilderContext &BC, Value * TheValue) {
  480. assert(m_RemainingReservedSpaceInBytes > 0);
  481. auto TheValueTypeID = TheValue->getType()->getTypeID();
  482. if (TheValueTypeID == Type::TypeID::DoubleTyID) {
  483. Function* SplitDouble = BC.HlslOP->GetOpFunc(OP::OpCode::SplitDouble, TheValue->getType());
  484. Constant* SplitDoubleOpcode = BC.HlslOP->GetU32Const((unsigned)DXIL::OpCode::SplitDouble);
  485. auto SplitDoubleIntruction = BC.Builder.CreateCall(SplitDouble, { SplitDoubleOpcode, TheValue }, "SplitDouble");
  486. auto LowBits = BC.Builder.CreateExtractValue(SplitDoubleIntruction, 0, "LowBits");
  487. auto HighBits = BC.Builder.CreateExtractValue(SplitDoubleIntruction, 1, "HighBits");
  488. //addDebugEntryValue(BC, BC.HlslOP->GetU32Const(0)); // padding
  489. addDebugEntryValue(BC, LowBits);
  490. addDebugEntryValue(BC, HighBits);
  491. }
  492. else if (TheValueTypeID == Type::TypeID::IntegerTyID && TheValue->getType()->getIntegerBitWidth() == 64) {
  493. auto LowBits = BC.Builder.CreateTrunc(TheValue, Type::getInt32Ty(BC.Ctx), "LowBits");
  494. auto ShiftedBits = BC.Builder.CreateLShr(TheValue, 32, "ShiftedBits");
  495. auto HighBits = BC.Builder.CreateTrunc(ShiftedBits, Type::getInt32Ty(BC.Ctx), "HighBits");
  496. //addDebugEntryValue(BC, BC.HlslOP->GetU32Const(0)); // padding
  497. addDebugEntryValue(BC, LowBits);
  498. addDebugEntryValue(BC, HighBits);
  499. }
  500. else if (TheValueTypeID == Type::TypeID::IntegerTyID &&
  501. (TheValue->getType()->getIntegerBitWidth() == 16 || TheValue->getType()->getIntegerBitWidth() == 1)) {
  502. auto As32 = BC.Builder.CreateZExt(TheValue, Type::getInt32Ty(BC.Ctx), "As32");
  503. addDebugEntryValue(BC, As32);
  504. }
  505. else if (TheValueTypeID == Type::TypeID::HalfTyID) {
  506. auto AsFloat = BC.Builder.CreateFPCast(TheValue, Type::getFloatTy(BC.Ctx), "AsFloat");
  507. addDebugEntryValue(BC, AsFloat);
  508. }
  509. else {
  510. Function* StoreValue = BC.HlslOP->GetOpFunc(OP::OpCode::BufferStore, TheValue->getType()); // Type::getInt32Ty(BC.Ctx));
  511. Constant* StoreValueOpcode = BC.HlslOP->GetU32Const((unsigned)DXIL::OpCode::BufferStore);
  512. UndefValue* Undef32Arg = UndefValue::get(Type::getInt32Ty(BC.Ctx));
  513. Constant* ZeroArg;
  514. UndefValue* UndefArg;
  515. if (TheValueTypeID == Type::TypeID::IntegerTyID) {
  516. ZeroArg = BC.HlslOP->GetU32Const(0);
  517. UndefArg = UndefValue::get(Type::getInt32Ty(BC.Ctx));
  518. }
  519. else if (TheValueTypeID == Type::TypeID::FloatTyID) {
  520. ZeroArg = BC.HlslOP->GetFloatConst(0.f);
  521. UndefArg = UndefValue::get(Type::getFloatTy(BC.Ctx));
  522. }
  523. else {
  524. // The above are the only two valid types for a UAV store
  525. assert(false);
  526. }
  527. Constant* WriteMask_X = BC.HlslOP->GetI8Const(1);
  528. (void)BC.Builder.CreateCall(StoreValue, {
  529. StoreValueOpcode, // i32 opcode
  530. m_HandleForUAV, // %dx.types.Handle, ; resource handle
  531. m_CurrentIndex, // i32 c0: index in bytes into UAV
  532. Undef32Arg, // i32 c1: unused
  533. TheValue,
  534. UndefArg, // unused values
  535. UndefArg, // unused values
  536. UndefArg, // unused values
  537. WriteMask_X
  538. });
  539. m_RemainingReservedSpaceInBytes -= 4;
  540. assert(m_RemainingReservedSpaceInBytes < 1024); // check for underflow
  541. if (m_RemainingReservedSpaceInBytes != 0) {
  542. m_CurrentIndex = BC.Builder.CreateAdd(m_CurrentIndex, BC.HlslOP->GetU32Const(4));
  543. }
  544. else {
  545. m_CurrentIndex = nullptr;
  546. }
  547. }
  548. }
  549. void DxilDebugInstrumentation::addInvocationStartMarker(BuilderContext &BC) {
  550. DebugShaderModifierRecordHeader marker{ 0 };
  551. reserveDebugEntrySpace(BC, sizeof(marker));
  552. marker.Header.Details.SizeDwords = DebugShaderModifierRecordPayloadSizeDwords(sizeof(marker));;
  553. marker.Header.Details.Flags = 0;
  554. marker.Header.Details.Type = DebugShaderModifierRecordTypeInvocationStartMarker;
  555. addDebugEntryValue(BC, BC.HlslOP->GetU32Const(marker.Header.u32Header));
  556. addDebugEntryValue(BC, m_InvocationId);
  557. }
  558. template<typename ReturnType>
  559. void DxilDebugInstrumentation::addStepEntryForType(DebugShaderModifierRecordType RecordType, BuilderContext &BC, Instruction *Inst) {
  560. DebugShaderModifierRecordDXILStep<ReturnType> step = {};
  561. reserveDebugEntrySpace(BC, sizeof(step));
  562. step.Header.Details.SizeDwords = DebugShaderModifierRecordPayloadSizeDwords(sizeof(step));
  563. step.Header.Details.Type = static_cast<uint8_t>(RecordType);
  564. addDebugEntryValue(BC, BC.HlslOP->GetU32Const(step.Header.u32Header));
  565. addDebugEntryValue(BC, m_InvocationId);
  566. addDebugEntryValue(BC, BC.HlslOP->GetU32Const(m_InstructionIndex++));
  567. if (RecordType != DebugShaderModifierRecordTypeDXILStepVoid) {
  568. addDebugEntryValue(BC, Inst);
  569. }
  570. }
  571. void DxilDebugInstrumentation::addStepDebugEntry(BuilderContext &BC, Instruction *Inst) {
  572. if (Inst->getOpcode() == Instruction::OtherOps::PHI) {
  573. return;
  574. }
  575. Type::TypeID ID = Inst->getType()->getTypeID();
  576. switch (ID) {
  577. case Type::TypeID::StructTyID:
  578. case Type::TypeID::VoidTyID:
  579. addStepEntryForType<void>(DebugShaderModifierRecordTypeDXILStepVoid, BC, Inst);
  580. break;
  581. case Type::TypeID::FloatTyID:
  582. addStepEntryForType<float>(DebugShaderModifierRecordTypeDXILStepFloat, BC, Inst);
  583. break;
  584. case Type::TypeID::IntegerTyID:
  585. if (Inst->getType()->getIntegerBitWidth() == 64) {
  586. addStepEntryForType<uint64_t>(DebugShaderModifierRecordTypeDXILStepUint64, BC, Inst);
  587. }
  588. else {
  589. addStepEntryForType<uint32_t>(DebugShaderModifierRecordTypeDXILStepUint32, BC, Inst);
  590. }
  591. break;
  592. case Type::TypeID::DoubleTyID:
  593. addStepEntryForType<double>(DebugShaderModifierRecordTypeDXILStepDouble, BC, Inst);
  594. break;
  595. case Type::TypeID::HalfTyID:
  596. addStepEntryForType<float>(DebugShaderModifierRecordTypeDXILStepFloat, BC, Inst);
  597. break;
  598. case Type::TypeID::PointerTyID:
  599. // Skip pointer calculation instructions. They aren't particularly meaningful to the user (being a mere
  600. // implementation detail for lookup tables, etc.), and their type is problematic from a UI point of view.
  601. // The subsequent instructions that dereference the pointer will be properly instrumented and show the
  602. // (meaningful) retrieved value.
  603. break;
  604. case Type::TypeID::FP128TyID:
  605. case Type::TypeID::LabelTyID:
  606. case Type::TypeID::MetadataTyID:
  607. case Type::TypeID::FunctionTyID:
  608. case Type::TypeID::ArrayTyID:
  609. case Type::TypeID::VectorTyID:
  610. assert(false);
  611. }
  612. }
  613. bool DxilDebugInstrumentation::runOnModule(Module &M) {
  614. DxilModule &DM = M.GetOrCreateDxilModule();
  615. LLVMContext & Ctx = M.getContext();
  616. OP *HlslOP = DM.GetOP();
  617. auto ShaderModel = DM.GetShaderModel();
  618. switch (ShaderModel->GetKind()) {
  619. case DXIL::ShaderKind::Pixel:
  620. case DXIL::ShaderKind::Vertex:
  621. case DXIL::ShaderKind::Compute:
  622. case DXIL::ShaderKind::Geometry:
  623. break;
  624. default:
  625. return false;
  626. }
  627. // First record pointers to all instructions in the function:
  628. std::vector<Instruction*> AllInstructions;
  629. for (inst_iterator I = inst_begin(DM.GetEntryFunction()), E = inst_end(DM.GetEntryFunction()); I != E; ++I) {
  630. AllInstructions.push_back(&*I);
  631. }
  632. // Branchless instrumentation requires taking care of a few things:
  633. // -Each invocation of the shader will be either of interest or not of interest
  634. // -If of interest, the offset into the output UAV will be as expected
  635. // -If not, the offset is forced to (UAVsize) - (Small Amount), and that output is ignored by the CPU-side code.
  636. // -The invocation of interest may overflow the UAV. This is handled by taking the modulus of the
  637. // output index. Overflow is then detected on the CPU side by checking for the presence of a canary
  638. // value at (UAVSize) - (Small Amount) * 2 (which is actually a conservative definition of overflow).
  639. //
  640. Instruction* firstInsertionPt = DM.GetEntryFunction()->getEntryBlock().getFirstInsertionPt();
  641. IRBuilder<> Builder(firstInsertionPt);
  642. BuilderContext BC{ M, DM, Ctx, HlslOP, Builder };
  643. addUAV(BC);
  644. auto SystemValues = addRequiredSystemValues(BC);
  645. addInvocationSelectionProlog(BC, SystemValues);
  646. addInvocationStartMarker(BC);
  647. // Instrument original instructions:
  648. for (auto & Inst : AllInstructions) {
  649. // Instrumentation goes after the instruction if it has a return value.
  650. // Otherwise, the instruction might be a terminator so we HAVE to put the instrumentation before
  651. if (Inst->getType()->getTypeID() != Type::TypeID::VoidTyID) {
  652. // Has a return type, so can't be a terminator, so start inserting before the next instruction
  653. IRBuilder<> Builder(Inst->getNextNode());
  654. BuilderContext BC2{ BC.M, BC.DM, BC.Ctx, BC.HlslOP, Builder };
  655. addStepDebugEntry(BC2, Inst);
  656. }
  657. else {
  658. // Insert before this instruction
  659. IRBuilder<> Builder(Inst);
  660. BuilderContext BC2{ BC.M, BC.DM, BC.Ctx, BC.HlslOP, Builder };
  661. addStepDebugEntry(BC2, Inst);
  662. }
  663. }
  664. DM.ReEmitDxilResources();
  665. return true;
  666. }
  667. char DxilDebugInstrumentation::ID = 0;
  668. ModulePass *llvm::createDxilDebugInstrumentationPass() {
  669. return new DxilDebugInstrumentation();
  670. }
  671. INITIALIZE_PASS(DxilDebugInstrumentation, "hlsl-dxil-debug-instrumentation", "HLSL DXIL debug instrumentation for PIX", false, false)