DxilDebugInstrumentation.cpp 34 KB

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