DxilDebugInstrumentation.cpp 34 KB

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