DxilDebugInstrumentation.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  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. } m_Parameters = { 0,0,0 };
  141. union SystemValueIndices {
  142. struct PixelShaderParameters {
  143. unsigned Position;
  144. } PixelShader;
  145. struct VertexShaderParameters {
  146. unsigned VertexId;
  147. unsigned InstanceId;
  148. } VertexShader;
  149. };
  150. uint64_t m_UAVSize = 1024*1024;
  151. Value * m_SelectionCriterion = nullptr;
  152. CallInst * m_HandleForUAV = nullptr;
  153. Value * m_InvocationId = nullptr;
  154. // Together these two values allow branchless writing to the UAV. An invocation of the shader
  155. // is either of interest or not (e.g. it writes to the pixel the user selected for debugging
  156. // or it doesn't). If not of interest, debugging output will still occur, but it will be
  157. // relegated to the very top few bytes of the UAV. Invocations of interest, by contrast, will
  158. // be written to the UAV at sequentially increasing offsets.
  159. // This value will either be one or zero (one if the invocation is of interest, zero otherwise)
  160. Value * m_OffsetMultiplicand = nullptr;
  161. // This will either be zero (if the invocation is of interest) or (UAVSize)-(SmallValue) if not.
  162. Value * m_OffsetAddend = nullptr;
  163. Constant * m_OffsetMask = nullptr;
  164. std::map<uint32_t, Value *> m_IncrementInstructionBySize;
  165. unsigned int m_InstructionIndex = 0;
  166. struct BuilderContext {
  167. Module &M;
  168. DxilModule &DM;
  169. LLVMContext & Ctx;
  170. OP * HlslOP;
  171. IRBuilder<> & Builder;
  172. };
  173. uint32_t m_RemainingReservedSpaceInBytes = 0;
  174. Value * m_CurrentIndex = nullptr;
  175. public:
  176. static char ID; // Pass identification, replacement for typeid
  177. explicit DxilDebugInstrumentation() : ModulePass(ID) {}
  178. const char *getPassName() const override { return "Add PIX debug instrumentation"; }
  179. void applyOptions(PassOptions O) override;
  180. bool runOnModule(Module &M) override;
  181. private:
  182. SystemValueIndices addRequiredSystemValues(BuilderContext &BC);
  183. void addUAV(BuilderContext &BC);
  184. void addInvocationSelectionProlog(BuilderContext &BC, SystemValueIndices SVIndices);
  185. Value * addPixelShaderProlog(BuilderContext &BC, SystemValueIndices SVIndices);
  186. Value * addComputeShaderProlog(BuilderContext &BC);
  187. Value * addVertexShaderProlog(BuilderContext &BC, SystemValueIndices SVIndices);
  188. void addDebugEntryValue(BuilderContext &BC, Value * TheValue);
  189. void addInvocationStartMarker(BuilderContext &BC);
  190. void reserveDebugEntrySpace(BuilderContext &BC, uint32_t SpaceInDwords);
  191. void addStepDebugEntry(BuilderContext &BC, Instruction *Inst);
  192. uint32_t UAVDumpingGroundOffset();
  193. template<typename ReturnType>
  194. void addStepEntryForType(DebugShaderModifierRecordType RecordType, BuilderContext &BC, Instruction *Inst);
  195. };
  196. void DxilDebugInstrumentation::applyOptions(PassOptions O) {
  197. for (const auto & option : O) {
  198. if (0 == option.first.compare("parameter0")) {
  199. m_Parameters.Parameters[0] = atoi(option.second.data());
  200. }
  201. else if (0 == option.first.compare("parameter1")) {
  202. m_Parameters.Parameters[1] = atoi(option.second.data());
  203. }
  204. else if (0 == option.first.compare("parameter2")) {
  205. m_Parameters.Parameters[2] = atoi(option.second.data());
  206. }
  207. else if (0 == option.first.compare("UAVSize")) {
  208. m_UAVSize = std::stoull(option.second.data());
  209. }
  210. }
  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 = std::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 = std::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 = std::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::Compute:
  283. // Compute thread Id is not in the input signature
  284. break;
  285. default:
  286. assert(false); // guaranteed by runOnModule
  287. }
  288. return SVIndices;
  289. }
  290. Value * DxilDebugInstrumentation::addComputeShaderProlog(BuilderContext &BC) {
  291. Constant* Zero32Arg = BC.HlslOP->GetU32Const(0);
  292. Constant* One32Arg = BC.HlslOP->GetU32Const(1);
  293. Constant* Two32Arg = BC.HlslOP->GetU32Const(2);
  294. auto ThreadIdFunc = BC.HlslOP->GetOpFunc(DXIL::OpCode::ThreadId, Type::getInt32Ty(BC.Ctx));
  295. Constant* Opcode = BC.HlslOP->GetU32Const((unsigned)DXIL::OpCode::ThreadId);
  296. auto ThreadIdX = BC.Builder.CreateCall(ThreadIdFunc, { Opcode, Zero32Arg }, "ThreadIdX");
  297. auto ThreadIdY = BC.Builder.CreateCall(ThreadIdFunc, { Opcode, One32Arg }, "ThreadIdY");
  298. auto ThreadIdZ = BC.Builder.CreateCall(ThreadIdFunc, { Opcode, Two32Arg }, "ThreadIdZ");
  299. // Compare to expected thread ID
  300. auto CompareToX = BC.Builder.CreateICmpEQ(ThreadIdX, BC.HlslOP->GetU32Const(m_Parameters.ComputeShader.ThreadIdX), "CompareToThreadIdX");
  301. auto CompareToY = BC.Builder.CreateICmpEQ(ThreadIdY, BC.HlslOP->GetU32Const(m_Parameters.ComputeShader.ThreadIdY), "CompareToThreadIdY");
  302. auto CompareToZ = BC.Builder.CreateICmpEQ(ThreadIdZ, BC.HlslOP->GetU32Const(m_Parameters.ComputeShader.ThreadIdZ), "CompareToThreadIdZ");
  303. auto CompareXAndY = BC.Builder.CreateAnd(CompareToX, CompareToY, "CompareXAndY");
  304. auto CompareAll = BC.Builder.CreateAnd(CompareXAndY, CompareToZ, "CompareAll");
  305. return CompareAll;
  306. }
  307. Value * DxilDebugInstrumentation::addVertexShaderProlog(BuilderContext &BC, SystemValueIndices SVIndices) {
  308. Constant* Zero32Arg = BC.HlslOP->GetU32Const(0);
  309. Constant* Zero8Arg = BC.HlslOP->GetI8Const(0);
  310. UndefValue* UndefArg = UndefValue::get(Type::getInt32Ty(BC.Ctx));
  311. auto LoadInputOpFunc = BC.HlslOP->GetOpFunc(DXIL::OpCode::LoadInput, Type::getInt32Ty(BC.Ctx));
  312. Constant* LoadInputOpcode = BC.HlslOP->GetU32Const((unsigned)DXIL::OpCode::LoadInput);
  313. Constant* SV_Vert_ID = BC.HlslOP->GetU32Const(SVIndices.VertexShader.VertexId);
  314. auto VertId = BC.Builder.CreateCall(LoadInputOpFunc,
  315. { LoadInputOpcode, SV_Vert_ID, Zero32Arg /*row*/, Zero8Arg /*column*/, UndefArg }, "VertId");
  316. Constant* SV_Instance_ID = BC.HlslOP->GetU32Const(SVIndices.VertexShader.InstanceId);
  317. auto InstanceId = BC.Builder.CreateCall(LoadInputOpFunc,
  318. { LoadInputOpcode, SV_Instance_ID, Zero32Arg /*row*/, Zero8Arg /*column*/, UndefArg }, "InstanceId");
  319. // Compare to expected vertex ID and instance ID
  320. auto CompareToVert = BC.Builder.CreateICmpEQ(VertId, BC.HlslOP->GetU32Const(m_Parameters.VertexShader.VertexId), "CompareToVertId");
  321. auto CompareToInstance = BC.Builder.CreateICmpEQ(InstanceId, BC.HlslOP->GetU32Const(m_Parameters.VertexShader.InstanceId), "CompareToInstanceId");
  322. auto CompareBoth = BC.Builder.CreateAnd(CompareToVert, CompareToInstance, "CompareBoth");
  323. return CompareBoth;
  324. }
  325. Value * DxilDebugInstrumentation::addPixelShaderProlog(BuilderContext &BC, SystemValueIndices SVIndices) {
  326. Constant* Zero32Arg = BC.HlslOP->GetU32Const(0);
  327. Constant* Zero8Arg = BC.HlslOP->GetI8Const(0);
  328. Constant* One8Arg = BC.HlslOP->GetI8Const(1);
  329. UndefValue* UndefArg = UndefValue::get(Type::getInt32Ty(BC.Ctx));
  330. // Convert SV_POSITION to UINT
  331. Value * XAsInt;
  332. Value * YAsInt;
  333. {
  334. auto LoadInputOpFunc = BC.HlslOP->GetOpFunc(DXIL::OpCode::LoadInput, Type::getFloatTy(BC.Ctx));
  335. Constant* LoadInputOpcode = BC.HlslOP->GetU32Const((unsigned)DXIL::OpCode::LoadInput);
  336. Constant* SV_Pos_ID = BC.HlslOP->GetU32Const(SVIndices.PixelShader.Position);
  337. auto XPos = BC.Builder.CreateCall(LoadInputOpFunc,
  338. { LoadInputOpcode, SV_Pos_ID, Zero32Arg /*row*/, Zero8Arg /*column*/, UndefArg }, "XPos");
  339. auto YPos = BC.Builder.CreateCall(LoadInputOpFunc,
  340. { LoadInputOpcode, SV_Pos_ID, Zero32Arg /*row*/, One8Arg /*column*/, UndefArg }, "YPos");
  341. XAsInt = BC.Builder.CreateCast(Instruction::CastOps::FPToUI, XPos, Type::getInt32Ty(BC.Ctx), "XIndex");
  342. YAsInt = BC.Builder.CreateCast(Instruction::CastOps::FPToUI, YPos, Type::getInt32Ty(BC.Ctx), "YIndex");
  343. }
  344. // Compare to expected pixel position and primitive ID
  345. auto CompareToX = BC.Builder.CreateICmpEQ(XAsInt, BC.HlslOP->GetU32Const(m_Parameters.PixelShader.X), "CompareToX");
  346. auto CompareToY = BC.Builder.CreateICmpEQ(YAsInt, BC.HlslOP->GetU32Const(m_Parameters.PixelShader.Y), "CompareToY");
  347. auto ComparePos = BC.Builder.CreateAnd(CompareToX, CompareToY, "ComparePos");
  348. return ComparePos;
  349. }
  350. void DxilDebugInstrumentation::addUAV(BuilderContext &BC)
  351. {
  352. // Set up a UAV with structure of a single int
  353. unsigned int UAVResourceHandle = static_cast<unsigned int>(BC.DM.GetUAVs().size());
  354. SmallVector<llvm::Type*, 1> Elements{ Type::getInt32Ty(BC.Ctx) };
  355. llvm::StructType *UAVStructTy = llvm::StructType::create(Elements, "PIX_DebugUAV_Type");
  356. std::unique_ptr<DxilResource> pUAV = llvm::make_unique<DxilResource>();
  357. pUAV->SetGlobalName("PIX_DebugUAVName");
  358. pUAV->SetGlobalSymbol(UndefValue::get(UAVStructTy->getPointerTo()));
  359. pUAV->SetID(UAVResourceHandle);
  360. pUAV->SetSpaceID((unsigned int)-2); // This is the reserved-for-tools register space
  361. pUAV->SetSampleCount(1);
  362. pUAV->SetGloballyCoherent(false);
  363. pUAV->SetHasCounter(false);
  364. pUAV->SetCompType(CompType::getI32());
  365. pUAV->SetLowerBound(0);
  366. pUAV->SetRangeSize(1);
  367. pUAV->SetKind(DXIL::ResourceKind::RawBuffer);
  368. pUAV->SetRW(true);
  369. auto ID = BC.DM.AddUAV(std::move(pUAV));
  370. assert(ID == UAVResourceHandle);
  371. BC.DM.m_ShaderFlags.SetEnableRawAndStructuredBuffers(true);
  372. // Create handle for the newly-added UAV
  373. Function* CreateHandleOpFunc = BC.HlslOP->GetOpFunc(DXIL::OpCode::CreateHandle, Type::getVoidTy(BC.Ctx));
  374. Constant* CreateHandleOpcodeArg = BC.HlslOP->GetU32Const((unsigned)DXIL::OpCode::CreateHandle);
  375. Constant* UAVVArg = BC.HlslOP->GetI8Const(static_cast<std::underlying_type<DxilResourceBase::Class>::type>(DXIL::ResourceClass::UAV));
  376. Constant* MetaDataArg = BC.HlslOP->GetU32Const(ID); // position of the metadata record in the corresponding metadata list
  377. Constant* IndexArg = BC.HlslOP->GetU32Const(0); //
  378. Constant* FalseArg = BC.HlslOP->GetI1Const(0); // non-uniform resource index: false
  379. m_HandleForUAV = BC.Builder.CreateCall(CreateHandleOpFunc,
  380. { CreateHandleOpcodeArg, UAVVArg, MetaDataArg, IndexArg, FalseArg }, "PIX_DebugUAV_Handle");
  381. }
  382. void DxilDebugInstrumentation::addInvocationSelectionProlog(BuilderContext &BC, SystemValueIndices SVIndices) {
  383. auto ShaderModel = BC.DM.GetShaderModel();
  384. Value * ParameterTestResult;
  385. switch (ShaderModel->GetKind()) {
  386. case DXIL::ShaderKind::Pixel:
  387. ParameterTestResult = addPixelShaderProlog(BC, SVIndices);
  388. break;
  389. case DXIL::ShaderKind::Vertex:
  390. ParameterTestResult = addVertexShaderProlog(BC, SVIndices);
  391. break;
  392. case DXIL::ShaderKind::Compute:
  393. ParameterTestResult = addComputeShaderProlog(BC);
  394. break;
  395. default:
  396. assert(false); // guaranteed by runOnModule
  397. }
  398. // This is a convenient place to calculate the values that modify the UAV offset for invocations of interest and for
  399. // UAV size.
  400. m_OffsetMultiplicand = BC.Builder.CreateCast(Instruction::CastOps::ZExt, ParameterTestResult, Type::getInt32Ty(BC.Ctx), "OffsetMultiplicand");
  401. auto InverseOffsetMultiplicand = BC.Builder.CreateSub(BC.HlslOP->GetU32Const(1), m_OffsetMultiplicand, "ComplementOfMultiplicand");
  402. m_OffsetAddend = BC.Builder.CreateMul(BC.HlslOP->GetU32Const(UAVDumpingGroundOffset()), InverseOffsetMultiplicand, "OffsetAddend");
  403. m_OffsetMask = BC.HlslOP->GetU32Const(UAVDumpingGroundOffset() - 1);
  404. m_SelectionCriterion = ParameterTestResult;
  405. }
  406. void DxilDebugInstrumentation::reserveDebugEntrySpace(BuilderContext &BC, uint32_t SpaceInBytes) {
  407. assert(m_CurrentIndex == nullptr);
  408. assert(m_RemainingReservedSpaceInBytes == 0);
  409. m_RemainingReservedSpaceInBytes = SpaceInBytes;
  410. // Insert the UAV increment instruction:
  411. Function* AtomicOpFunc = BC.HlslOP->GetOpFunc(OP::OpCode::AtomicBinOp, Type::getInt32Ty(BC.Ctx));
  412. Constant* AtomicBinOpcode = BC.HlslOP->GetU32Const((unsigned)OP::OpCode::AtomicBinOp);
  413. Constant* AtomicAdd = BC.HlslOP->GetU32Const((unsigned)DXIL::AtomicBinOpCode::Add);
  414. Constant* Zero32Arg = BC.HlslOP->GetU32Const(0);
  415. UndefValue* UndefArg = UndefValue::get(Type::getInt32Ty(BC.Ctx));
  416. // so inc will be zero for uninteresting invocations:
  417. Value * IncrementForThisInvocation;
  418. auto findIncrementInstruction = m_IncrementInstructionBySize.find(SpaceInBytes);
  419. if (findIncrementInstruction == m_IncrementInstructionBySize.end()) {
  420. Constant* Increment = BC.HlslOP->GetU32Const(SpaceInBytes);
  421. auto it = m_IncrementInstructionBySize.emplace(
  422. SpaceInBytes, BC.Builder.CreateMul(Increment, m_OffsetMultiplicand, "IncrementForThisInvocation"));
  423. findIncrementInstruction = it.first;
  424. }
  425. IncrementForThisInvocation = findIncrementInstruction->second;
  426. auto PreviousValue = BC.Builder.CreateCall(AtomicOpFunc, {
  427. AtomicBinOpcode,// i32, ; opcode
  428. m_HandleForUAV, // %dx.types.Handle, ; resource handle
  429. AtomicAdd, // i32, ; binary operation code : EXCHANGE, IADD, AND, OR, XOR, IMIN, IMAX, UMIN, UMAX
  430. Zero32Arg, // i32, ; coordinate c0: index in bytes
  431. UndefArg, // i32, ; coordinate c1 (unused)
  432. UndefArg, // i32, ; coordinate c2 (unused)
  433. IncrementForThisInvocation, // i32); increment value
  434. }, "UAVIncResult");
  435. if (m_InvocationId == nullptr)
  436. {
  437. m_InvocationId = PreviousValue;
  438. }
  439. auto MaskedForLimit = BC.Builder.CreateAnd(PreviousValue, m_OffsetMask, "MaskedForUAVLimit");
  440. // The return value will either end up being itself (multiplied by one and added with zero)
  441. // or the "dump uninteresting things here" value of (UAVSize - a bit).
  442. auto MultipliedForInterest = BC.Builder.CreateMul(MaskedForLimit, m_OffsetMultiplicand, "MultipliedForInterest");
  443. auto AddedForInterest = BC.Builder.CreateAdd(MultipliedForInterest, m_OffsetAddend, "AddedForInterest");
  444. m_CurrentIndex = AddedForInterest;
  445. }
  446. void DxilDebugInstrumentation::addDebugEntryValue(BuilderContext &BC, Value * TheValue) {
  447. assert(m_RemainingReservedSpaceInBytes > 0);
  448. auto TheValueTypeID = TheValue->getType()->getTypeID();
  449. if (TheValueTypeID == Type::TypeID::DoubleTyID) {
  450. Function* SplitDouble = BC.HlslOP->GetOpFunc(OP::OpCode::SplitDouble, TheValue->getType());
  451. Constant* SplitDoubleOpcode = BC.HlslOP->GetU32Const((unsigned)DXIL::OpCode::SplitDouble);
  452. auto SplitDoubleIntruction = BC.Builder.CreateCall(SplitDouble, { SplitDoubleOpcode, TheValue }, "SplitDouble");
  453. auto LowBits = BC.Builder.CreateExtractValue(SplitDoubleIntruction, 0, "LowBits");
  454. auto HighBits = BC.Builder.CreateExtractValue(SplitDoubleIntruction, 1, "HighBits");
  455. //addDebugEntryValue(BC, BC.HlslOP->GetU32Const(0)); // padding
  456. addDebugEntryValue(BC, LowBits);
  457. addDebugEntryValue(BC, HighBits);
  458. }
  459. else if (TheValueTypeID == Type::TypeID::IntegerTyID && TheValue->getType()->getIntegerBitWidth() == 64) {
  460. auto LowBits = BC.Builder.CreateTrunc(TheValue, Type::getInt32Ty(BC.Ctx), "LowBits");
  461. auto ShiftedBits = BC.Builder.CreateLShr(TheValue, 32, "ShiftedBits");
  462. auto HighBits = BC.Builder.CreateTrunc(ShiftedBits, Type::getInt32Ty(BC.Ctx), "HighBits");
  463. //addDebugEntryValue(BC, BC.HlslOP->GetU32Const(0)); // padding
  464. addDebugEntryValue(BC, LowBits);
  465. addDebugEntryValue(BC, HighBits);
  466. }
  467. else if (TheValueTypeID == Type::TypeID::IntegerTyID &&
  468. (TheValue->getType()->getIntegerBitWidth() == 16 || TheValue->getType()->getIntegerBitWidth() == 1)) {
  469. auto As32 = BC.Builder.CreateZExt(TheValue, Type::getInt32Ty(BC.Ctx), "As32");
  470. addDebugEntryValue(BC, As32);
  471. }
  472. else if (TheValueTypeID == Type::TypeID::HalfTyID) {
  473. auto AsFloat = BC.Builder.CreateFPCast(TheValue, Type::getFloatTy(BC.Ctx), "AsFloat");
  474. addDebugEntryValue(BC, AsFloat);
  475. }
  476. else {
  477. Function* StoreValue = BC.HlslOP->GetOpFunc(OP::OpCode::BufferStore, TheValue->getType()); // Type::getInt32Ty(BC.Ctx));
  478. Constant* StoreValueOpcode = BC.HlslOP->GetU32Const((unsigned)DXIL::OpCode::BufferStore);
  479. UndefValue* Undef32Arg = UndefValue::get(Type::getInt32Ty(BC.Ctx));
  480. Constant* ZeroArg;
  481. UndefValue* UndefArg;
  482. if (TheValueTypeID == Type::TypeID::IntegerTyID) {
  483. ZeroArg = BC.HlslOP->GetU32Const(0);
  484. UndefArg = UndefValue::get(Type::getInt32Ty(BC.Ctx));
  485. }
  486. else if (TheValueTypeID == Type::TypeID::FloatTyID) {
  487. ZeroArg = BC.HlslOP->GetFloatConst(0.f);
  488. UndefArg = UndefValue::get(Type::getFloatTy(BC.Ctx));
  489. }
  490. else {
  491. // The above are the only two valid types for a UAV store
  492. assert(false);
  493. }
  494. Constant* WriteMask_X = BC.HlslOP->GetI8Const(1);
  495. (void)BC.Builder.CreateCall(StoreValue, {
  496. StoreValueOpcode, // i32 opcode
  497. m_HandleForUAV, // %dx.types.Handle, ; resource handle
  498. m_CurrentIndex, // i32 c0: index in bytes into UAV
  499. Undef32Arg, // i32 c1: unused
  500. TheValue,
  501. UndefArg, // unused values
  502. UndefArg, // unused values
  503. UndefArg, // unused values
  504. WriteMask_X
  505. });
  506. m_RemainingReservedSpaceInBytes -= 4;
  507. assert(m_RemainingReservedSpaceInBytes < 1024); // check for underflow
  508. if (m_RemainingReservedSpaceInBytes != 0) {
  509. m_CurrentIndex = BC.Builder.CreateAdd(m_CurrentIndex, BC.HlslOP->GetU32Const(4));
  510. }
  511. else {
  512. m_CurrentIndex = nullptr;
  513. }
  514. }
  515. }
  516. void DxilDebugInstrumentation::addInvocationStartMarker(BuilderContext &BC) {
  517. DebugShaderModifierRecordHeader marker{ 0 };
  518. reserveDebugEntrySpace(BC, sizeof(marker));
  519. marker.Header.Details.SizeDwords = DebugShaderModifierRecordPayloadSizeDwords(sizeof(marker));;
  520. marker.Header.Details.Flags = 0;
  521. marker.Header.Details.Type = DebugShaderModifierRecordTypeInvocationStartMarker;
  522. addDebugEntryValue(BC, BC.HlslOP->GetU32Const(marker.Header.u32Header));
  523. addDebugEntryValue(BC, m_InvocationId);
  524. }
  525. template<typename ReturnType>
  526. void DxilDebugInstrumentation::addStepEntryForType(DebugShaderModifierRecordType RecordType, BuilderContext &BC, Instruction *Inst) {
  527. DebugShaderModifierRecordDXILStep<ReturnType> step = {};
  528. reserveDebugEntrySpace(BC, sizeof(step));
  529. step.Header.Details.SizeDwords = DebugShaderModifierRecordPayloadSizeDwords(sizeof(step));
  530. step.Header.Details.Type = static_cast<uint8_t>(RecordType);
  531. addDebugEntryValue(BC, BC.HlslOP->GetU32Const(step.Header.u32Header));
  532. addDebugEntryValue(BC, m_InvocationId);
  533. addDebugEntryValue(BC, BC.HlslOP->GetU32Const(m_InstructionIndex++));
  534. if (RecordType != DebugShaderModifierRecordTypeDXILStepVoid) {
  535. addDebugEntryValue(BC, Inst);
  536. }
  537. }
  538. void DxilDebugInstrumentation::addStepDebugEntry(BuilderContext &BC, Instruction *Inst) {
  539. if (Inst->getOpcode() == Instruction::OtherOps::PHI) {
  540. return;
  541. }
  542. Type::TypeID ID = Inst->getType()->getTypeID();
  543. switch (ID) {
  544. case Type::TypeID::StructTyID:
  545. case Type::TypeID::VoidTyID:
  546. addStepEntryForType<void>(DebugShaderModifierRecordTypeDXILStepVoid, BC, Inst);
  547. break;
  548. case Type::TypeID::FloatTyID:
  549. addStepEntryForType<float>(DebugShaderModifierRecordTypeDXILStepFloat, BC, Inst);
  550. break;
  551. case Type::TypeID::IntegerTyID:
  552. if (Inst->getType()->getIntegerBitWidth() == 64) {
  553. addStepEntryForType<uint64_t>(DebugShaderModifierRecordTypeDXILStepUint64, BC, Inst);
  554. }
  555. else {
  556. addStepEntryForType<uint32_t>(DebugShaderModifierRecordTypeDXILStepUint32, BC, Inst);
  557. }
  558. break;
  559. case Type::TypeID::DoubleTyID:
  560. addStepEntryForType<double>(DebugShaderModifierRecordTypeDXILStepDouble, BC, Inst);
  561. break;
  562. case Type::TypeID::HalfTyID:
  563. addStepEntryForType<float>(DebugShaderModifierRecordTypeDXILStepFloat, BC, Inst);
  564. break;
  565. case Type::TypeID::FP128TyID:
  566. case Type::TypeID::LabelTyID:
  567. case Type::TypeID::MetadataTyID:
  568. case Type::TypeID::FunctionTyID:
  569. case Type::TypeID::ArrayTyID:
  570. case Type::TypeID::PointerTyID:
  571. case Type::TypeID::VectorTyID:
  572. assert(false);
  573. }
  574. }
  575. bool DxilDebugInstrumentation::runOnModule(Module &M) {
  576. DxilModule &DM = M.GetOrCreateDxilModule();
  577. LLVMContext & Ctx = M.getContext();
  578. OP *HlslOP = DM.GetOP();
  579. auto ShaderModel = DM.GetShaderModel();
  580. switch (ShaderModel->GetKind()) {
  581. case DXIL::ShaderKind::Pixel:
  582. case DXIL::ShaderKind::Vertex:
  583. case DXIL::ShaderKind::Compute:
  584. break;
  585. default:
  586. return false;
  587. }
  588. // First record pointers to all instructions in the function:
  589. std::vector<Instruction*> AllInstructions;
  590. for (inst_iterator I = inst_begin(DM.GetEntryFunction()), E = inst_end(DM.GetEntryFunction()); I != E; ++I) {
  591. AllInstructions.push_back(&*I);
  592. }
  593. // Branchless instrumentation requires taking care of a few things:
  594. // -Each invocation of the shader will be either of interest or not of interest
  595. // -If of interest, the offset into the output UAV will be as expected
  596. // -If not, the offset is forced to (UAVsize) - (Small Amount), and that output is ignored by the CPU-side code.
  597. // -The invocation of interest may overflow the UAV. This is handled by taking the modulus of the
  598. // output index. Overflow is then detected on the CPU side by checking for the presence of a canary
  599. // value at (UAVSize) - (Small Amount) * 2 (which is actually a conservative definition of overflow).
  600. //
  601. Instruction* firstInsertionPt = DM.GetEntryFunction()->getEntryBlock().getFirstInsertionPt();
  602. IRBuilder<> Builder(firstInsertionPt);
  603. BuilderContext BC{ M, DM, Ctx, HlslOP, Builder };
  604. addUAV(BC);
  605. auto SystemValues = addRequiredSystemValues(BC);
  606. addInvocationSelectionProlog(BC, SystemValues);
  607. addInvocationStartMarker(BC);
  608. // Instrument original instructions:
  609. for (auto & Inst : AllInstructions) {
  610. // Instrumentation goes after the instruction if it has a return value.
  611. // Otherwise, the instruction might be a terminator so we HAVE to put the instrumentation before
  612. if (Inst->getType()->getTypeID() != Type::TypeID::VoidTyID) {
  613. // Has a return type, so can't be a terminator, so start inserting before the next instruction
  614. IRBuilder<> Builder(Inst->getNextNode());
  615. BuilderContext BC2{ BC.M, BC.DM, BC.Ctx, BC.HlslOP, Builder };
  616. addStepDebugEntry(BC2, Inst);
  617. }
  618. else {
  619. // Insert before this instruction
  620. IRBuilder<> Builder(Inst);
  621. BuilderContext BC2{ BC.M, BC.DM, BC.Ctx, BC.HlslOP, Builder };
  622. addStepDebugEntry(BC2, Inst);
  623. }
  624. }
  625. DM.ReEmitDxilResources();
  626. return true;
  627. }
  628. char DxilDebugInstrumentation::ID = 0;
  629. ModulePass *llvm::createDxilDebugInstrumentationPass() {
  630. return new DxilDebugInstrumentation();
  631. }
  632. INITIALIZE_PASS(DxilDebugInstrumentation, "hlsl-dxil-debug-instrumentation", "HLSL DXIL debug instrumentation for PIX", false, false)