forked from microsoft/DirectXShaderCompiler
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdxc.cpp
More file actions
1597 lines (1433 loc) · 56.9 KB
/
Copy pathdxc.cpp
File metadata and controls
1597 lines (1433 loc) · 56.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
///////////////////////////////////////////////////////////////////////////////
// //
// dxc.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Provides the entry point for the dxc console program. //
// //
///////////////////////////////////////////////////////////////////////////////
//
// Some unimplemented flags as compared to fxc:
//
// /compress - Compress DX10 shader bytecode from files.
// /decompress - Decompress DX10 shader bytecode from first file.
// /Fx <file> - Output assembly code and hex listing file.
// /Fl <file> - Output a library.
// /Gch - Compile as a child effect for fx_4_x profiles.
// /Gdp - Disable effect performance mode.
// /Gec - Enable backwards compatibility mode.
// /Ges - Enable strict mode.
// /Gpp - Force partial precision.
// /Lx - Output hexadecimal literals
// /Op - Disable preshaders
//
// Unimplemented but on roadmap:
//
// /matchUAVs - Match template shader UAV slot allocations in the current
// shader /mergeUAVs - Merge UAV slot allocations of template shader and the
// current shader /Ni - Output instruction numbers in assembly listings
// /No - Output instruction byte offset in assembly listings
// /Qstrip_reflect
// /res_may_alias
// /shtemplate
// /verifyrootsignature
//
#include "dxc.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/Unicode.h"
#include "dxc/Support/WinFunctions.h"
#include "dxc/Support/WinIncludes.h"
#include "dxc/dxcerrors.h"
#include <sstream>
#include <string>
#include <vector>
#include "dxc/DXIL/DxilShaderModel.h"
#include "dxc/DxilContainer/DxilContainer.h"
#include "dxc/DxilRootSignature/DxilRootSignature.h"
#include "dxc/Support/FileIOHelper.h"
#include "dxc/Support/HLSLOptions.h"
#include "dxc/Support/dxcapi.use.h"
#include "dxc/Support/microcom.h"
#include "dxc/dxcapi.h"
#include "dxc/dxcapi.internal.h"
#include "dxc/dxctools.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#ifdef _WIN32
// Mach change start
// #include <comdef.h>
#ifdef _MSC_VER
#include <comdef.h>
#endif // _MSC_VER
// Mach change end
#include <dia2.h>
#endif
#include <algorithm>
#include <unordered_map>
#ifdef _WIN32
#pragma comment(lib, "version.lib")
#endif
// SPIRV Change Starts
#ifdef ENABLE_SPIRV_CODEGEN
#include "spirv-tools/libspirv.hpp"
#include "clang/SPIRV/FeatureManager.h"
static bool DisassembleSpirv(IDxcBlob *binaryBlob, IDxcLibrary *library,
IDxcBlobEncoding **assemblyBlob, bool withColor,
bool withByteOffset, spv_target_env target_env) {
if (!binaryBlob)
return true;
size_t num32BitWords = (binaryBlob->GetBufferSize() + 3) / 4;
std::string binaryStr((char *)binaryBlob->GetBufferPointer(),
binaryBlob->GetBufferSize());
binaryStr.resize(num32BitWords * 4, 0);
std::vector<uint32_t> words;
words.resize(num32BitWords, 0);
memcpy(words.data(), binaryStr.data(), binaryStr.size());
std::string assembly;
spvtools::SpirvTools spirvTools(target_env);
uint32_t options = (SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES |
SPV_BINARY_TO_TEXT_OPTION_INDENT);
if (withColor)
options |= SPV_BINARY_TO_TEXT_OPTION_COLOR;
if (withByteOffset)
options |= SPV_BINARY_TO_TEXT_OPTION_SHOW_BYTE_OFFSET;
if (!spirvTools.Disassemble(words, &assembly, options))
return false;
IFT(library->CreateBlobWithEncodingOnHeapCopy(
assembly.data(), assembly.size(), CP_UTF8, assemblyBlob));
return true;
}
#endif
// SPIRV Change Ends
inline bool wcseq(LPCWSTR a, LPCWSTR b) {
return (a == nullptr && b == nullptr) ||
(a != nullptr && b != nullptr && wcscmp(a, b) == 0);
}
using namespace dxc;
using namespace llvm::opt;
using namespace hlsl::options;
class DxcContext {
private:
DxcOpts &m_Opts;
DxcDllSupport &m_dxcSupport;
int ActOnBlob(IDxcBlob *pBlob);
int ActOnBlob(IDxcBlob *pBlob, IDxcBlob *pDebugBlob, LPCWSTR pDebugBlobName);
void UpdatePart(IDxcBlob *pBlob, IDxcBlob **ppResult);
bool UpdatePartRequired();
void WriteHeader(IDxcBlobEncoding *pDisassembly, IDxcBlob *pCode,
llvm::Twine &pVariableName, LPCWSTR pPath);
HRESULT ReadFileIntoPartContent(hlsl::DxilFourCC fourCC, LPCWSTR fileName,
IDxcBlob **ppResult);
// Dia is only supported on Windows.
#ifdef _WIN32
// TODO : Refactor two functions below. There are duplicate functions in
// DxcContext in dxa.cpp
HRESULT GetDxcDiaTable(IDxcLibrary *pLibrary, IDxcBlob *pTargetBlob,
IDiaTable **ppTable, LPCWSTR tableName);
#endif // _WIN32
HRESULT FindModuleBlob(hlsl::DxilFourCC fourCC, IDxcBlob *pSource,
IDxcLibrary *pLibrary, IDxcBlob **ppTargetBlob);
void ExtractRootSignature(IDxcBlob *pBlob, IDxcBlob **ppResult);
int VerifyRootSignature();
template <typename TInterface>
HRESULT CreateInstance(REFCLSID clsid, TInterface **pResult) {
return m_dxcSupport.CreateInstance(clsid, pResult);
}
public:
DxcContext(DxcOpts &Opts, DxcDllSupport &dxcSupport)
: m_Opts(Opts), m_dxcSupport(dxcSupport) {}
int Compile();
void Recompile(IDxcBlob *pSource, IDxcLibrary *pLibrary,
IDxcCompiler *pCompiler, std::vector<LPCWSTR> &args,
std::wstring &outputPDBPath, CComPtr<IDxcBlob> &pDebugBlob,
IDxcOperationResult **pCompileResult);
int DumpBinary();
int Link();
void Preprocess();
void GetCompilerVersionInfo(llvm::raw_string_ostream &OS);
};
static void WriteBlobToFile(IDxcBlob *pBlob, llvm::StringRef FName,
UINT32 defaultTextCodePage) {
::dxc::WriteBlobToFile(pBlob, StringRefWide(FName), defaultTextCodePage);
}
static void WritePartToFile(IDxcBlob *pBlob, hlsl::DxilFourCC CC,
llvm::StringRef FName) {
const hlsl::DxilContainerHeader *pContainer = hlsl::IsDxilContainerLike(
pBlob->GetBufferPointer(), pBlob->GetBufferSize());
if (!pContainer) {
throw hlsl::Exception(E_FAIL, "Unable to find required part in blob");
}
hlsl::DxilPartIsType pred(CC);
hlsl::DxilPartIterator it =
std::find_if(hlsl::begin(pContainer), hlsl::end(pContainer), pred);
if (it == hlsl::end(pContainer)) {
throw hlsl::Exception(E_FAIL, "Unable to find required part in blob");
}
const char *pData = hlsl::GetDxilPartData(*it);
DWORD dataLen = (*it)->PartSize;
StringRefWide WideName(FName);
CHandle file(CreateFileW(WideName, GENERIC_WRITE, FILE_SHARE_READ, nullptr,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr));
if (file == INVALID_HANDLE_VALUE) {
IFT_Data(HRESULT_FROM_WIN32(GetLastError()), WideName);
}
DWORD written;
if (FALSE == WriteFile(file, pData, dataLen, &written, nullptr)) {
IFT_Data(HRESULT_FROM_WIN32(GetLastError()), WideName);
}
}
static void WriteDxcOutputToFile(DXC_OUT_KIND kind, IDxcResult *pResult,
UINT32 textCodePage) {
if (pResult->HasOutput(kind)) {
CComPtr<IDxcBlob> pData;
CComPtr<IDxcBlobWide> pName;
IFT(pResult->GetOutput(kind, IID_PPV_ARGS(&pData), &pName));
if (pName && pName->GetStringLength() > 0)
WriteBlobToFile(pData, pName->GetStringPointer(), textCodePage);
}
}
static bool StringBlobEqualWide(IDxcBlobWide *pBlob, const WCHAR *pStr) {
size_t uSize = wcslen(pStr);
if (pBlob && pBlob->GetStringLength() == uSize) {
return 0 == memcmp(pBlob->GetBufferPointer(), pStr, pBlob->GetBufferSize());
}
return false;
}
static void WriteDxcExtraOuputs(IDxcResult *pResult) {
DXC_OUT_KIND kind = DXC_OUT_EXTRA_OUTPUTS;
if (!pResult->HasOutput(kind)) {
return;
}
CComPtr<IDxcExtraOutputs> pOutputs;
CComPtr<IDxcBlobWide> pName;
IFT(pResult->GetOutput(kind, IID_PPV_ARGS(&pOutputs), &pName));
UINT32 uOutputCount = pOutputs->GetOutputCount();
for (UINT32 i = 0; i < uOutputCount; i++) {
CComPtr<IDxcBlobWide> pFileName;
CComPtr<IDxcBlobWide> pType;
CComPtr<IDxcBlob> pBlob;
HRESULT hr =
pOutputs->GetOutput(i, IID_PPV_ARGS(&pBlob), &pType, &pFileName);
// Not a blob
if (FAILED(hr))
continue;
UINT32 uCodePage = CP_ACP;
CComPtr<IDxcBlobEncoding> pBlobEncoding;
if (SUCCEEDED(pBlob.QueryInterface(&pBlobEncoding))) {
BOOL bKnown = FALSE;
UINT32 uKnownCodePage = CP_ACP;
IFT(pBlobEncoding->GetEncoding(&bKnown, &uKnownCodePage));
if (bKnown) {
uCodePage = uKnownCodePage;
}
}
if (pFileName && pFileName->GetStringLength() > 0) {
if (StringBlobEqualWide(pFileName, DXC_EXTRA_OUTPUT_NAME_STDOUT)) {
if (uCodePage != CP_ACP) {
WriteBlobToConsole(pBlob, STD_OUTPUT_HANDLE);
}
} else if (StringBlobEqualWide(pFileName, DXC_EXTRA_OUTPUT_NAME_STDERR)) {
if (uCodePage != CP_ACP) {
WriteBlobToConsole(pBlob, STD_ERROR_HANDLE);
}
} else {
WriteBlobToFile(pBlob, pFileName->GetStringPointer(), uCodePage);
}
}
}
}
static void WriteDxcOutputToConsole(IDxcResult *pResult, DXC_OUT_KIND kind) {
if (!pResult->HasOutput(kind))
return;
CComPtr<IDxcBlob> pBlob;
IFT(pResult->GetOutput(kind, IID_PPV_ARGS(&pBlob), nullptr));
llvm::StringRef outputString((LPSTR)pBlob->GetBufferPointer(),
pBlob->GetBufferSize());
llvm::SmallVector<llvm::StringRef, 20> lines;
outputString.split(lines, "\n");
std::string outputStr;
llvm::raw_string_ostream SS(outputStr);
for (auto line : lines) {
SS << "; " << line << "\n";
}
WriteUtf8ToConsole(outputStr.data(), outputStr.size());
}
std::string getDependencyOutputFileName(llvm::StringRef inputFileName) {
return inputFileName.substr(0, inputFileName.rfind('.')).str() + ".d";
}
// This function is called either after the compilation is done or /dumpbin
// option is provided Performing options that are used to process dxil
// container.
int DxcContext::ActOnBlob(IDxcBlob *pBlob) {
return ActOnBlob(pBlob, nullptr, nullptr);
}
int DxcContext::ActOnBlob(IDxcBlob *pBlob, IDxcBlob *pDebugBlob,
LPCWSTR pDebugBlobName) {
int retVal = 0;
if (m_Opts.DumpDependencies) {
if (!m_Opts.OutputFileForDependencies.empty()) {
CComPtr<IDxcBlob> pResult;
UpdatePart(pBlob, &pResult);
WriteBlobToFile(pResult, m_Opts.OutputFileForDependencies,
m_Opts.DefaultTextCodePage);
} else if (m_Opts.WriteDependencies) {
CComPtr<IDxcBlob> pResult;
UpdatePart(pBlob, &pResult);
WriteBlobToFile(pResult, getDependencyOutputFileName(m_Opts.InputFile),
m_Opts.DefaultTextCodePage);
} else {
WriteBlobToConsole(pBlob);
}
return retVal;
}
// Text output.
if (m_Opts.AstDump || m_Opts.OptDump || m_Opts.VerifyDiagnostics) {
WriteBlobToConsole(pBlob);
return retVal;
}
// Write the output blob.
if (!m_Opts.OutputObject.empty()) {
// For backward compatability: fxc requires /Fo for /extractrootsignature
if (!m_Opts.ExtractRootSignature) {
CComPtr<IDxcBlob> pResult;
UpdatePart(pBlob, &pResult);
WriteBlobToFile(pResult, m_Opts.OutputObject, m_Opts.DefaultTextCodePage);
}
}
// Verify Root Signature
if (!m_Opts.VerifyRootSignatureSource.empty()) {
return VerifyRootSignature();
}
// Extract and write the PDB/debug information.
if (!m_Opts.DebugFile.empty()) {
IFTBOOLMSG(m_Opts.GeneratePDB(), E_INVALIDARG,
"/Fd specified, but no Debug Info was "
"found in the shader, please use the "
"/Zi or /Zs switch to generate debug "
"information compiling this shader.");
if (pDebugBlob != nullptr) {
IFTBOOLMSG(pDebugBlobName && *pDebugBlobName, E_INVALIDARG,
"/Fd was specified but no debug name was produced");
WriteBlobToFile(pDebugBlob, pDebugBlobName, m_Opts.DefaultTextCodePage);
} else {
// Note: This is for load from binary case
WritePartToFile(pBlob, hlsl::DFCC_ShaderDebugInfoDXIL, m_Opts.DebugFile);
}
}
// Extract and write root signature information.
if (m_Opts.ExtractRootSignature) {
CComPtr<IDxcBlob> pRootSignatureContainer;
ExtractRootSignature(pBlob, &pRootSignatureContainer);
WriteBlobToFile(pRootSignatureContainer, m_Opts.OutputObject,
m_Opts.DefaultTextCodePage);
}
// Extract and write private data.
if (!m_Opts.ExtractPrivateFile.empty()) {
WritePartToFile(pBlob, hlsl::DFCC_PrivateData, m_Opts.ExtractPrivateFile);
}
// OutputObject suppresses console dump.
bool needDisassembly =
!m_Opts.OutputHeader.empty() || !m_Opts.AssemblyCode.empty() ||
(m_Opts.OutputObject.empty() && m_Opts.DebugFile.empty() &&
m_Opts.ExtractPrivateFile.empty() &&
m_Opts.VerifyRootSignatureSource.empty() &&
!m_Opts.ExtractRootSignature);
if (!needDisassembly)
return retVal;
CComPtr<IDxcBlobEncoding> pDisassembleResult;
// SPIRV Change Starts
#ifdef ENABLE_SPIRV_CODEGEN
if (m_Opts.GenSPIRV) {
CComPtr<IDxcLibrary> pLibrary;
IFT(m_dxcSupport.CreateInstance(CLSID_DxcLibrary, &pLibrary));
llvm::Optional<spv_target_env> target_env =
clang::spirv::FeatureManager::stringToSpvEnvironment(
m_Opts.SpirvOptions.targetEnv);
IFTBOOLMSG(target_env, E_INVALIDARG, "Cannot parse SPIR-V target env.");
if (!DisassembleSpirv(pBlob, pLibrary, &pDisassembleResult,
m_Opts.ColorCodeAssembly,
m_Opts.DisassembleByteOffset, *target_env))
return 1;
} else {
#endif // ENABLE_SPIRV_CODEGEN
// SPIRV Change Ends
if (m_Opts.IsRootSignatureProfile()) {
// keep the same behavior as fxc, people may want to embed the root
// signatures in their code bases.
CComPtr<IDxcLibrary> pLibrary;
IFT(m_dxcSupport.CreateInstance(CLSID_DxcLibrary, &pLibrary));
std::string Message = "Disassembly failed";
IFT(pLibrary->CreateBlobWithEncodingOnHeapCopy(
(LPBYTE)&Message[0], Message.size(), CP_ACP, &pDisassembleResult));
} else {
CComPtr<IDxcCompiler> pCompiler;
IFT(CreateInstance(CLSID_DxcCompiler, &pCompiler));
IFT(pCompiler->Disassemble(pBlob, &pDisassembleResult));
}
// SPIRV Change Starts
#ifdef ENABLE_SPIRV_CODEGEN
}
#endif // ENABLE_SPIRV_CODEGEN
// SPIRV Change Ends
bool disassemblyWritten = false;
if (!m_Opts.OutputHeader.empty()) {
llvm::Twine varName = m_Opts.VariableName.empty()
? llvm::Twine("g_", m_Opts.EntryPoint)
: m_Opts.VariableName;
WriteHeader(pDisassembleResult, pBlob, varName,
StringRefWide(m_Opts.OutputHeader));
disassemblyWritten = true;
}
if (!m_Opts.AssemblyCode.empty()) {
WriteBlobToFile(pDisassembleResult, m_Opts.AssemblyCode,
m_Opts.DefaultTextCodePage);
disassemblyWritten = true;
}
if (!disassemblyWritten) {
WriteBlobToConsole(pDisassembleResult);
}
return retVal;
}
// Given a dxil container, update the dxil container by processing container
// specific options.
void DxcContext::UpdatePart(IDxcBlob *pSource, IDxcBlob **ppResult) {
DXASSERT(pSource && ppResult, "otherwise blob cannot be updated");
if (!UpdatePartRequired()) {
*ppResult = pSource;
pSource->AddRef();
return;
}
CComPtr<IDxcContainerBuilder> pContainerBuilder;
CComPtr<IDxcBlob> pResult;
IFT(CreateInstance(CLSID_DxcContainerBuilder, &pContainerBuilder));
// Load original container and update blob for each given option
IFT(pContainerBuilder->Load(pSource));
// Update parts based on dxc options
if (m_Opts.StripDebug) {
IFT(pContainerBuilder->RemovePart(
hlsl::DxilFourCC::DFCC_ShaderDebugInfoDXIL));
}
if (m_Opts.StripPrivate) {
IFT(pContainerBuilder->RemovePart(hlsl::DxilFourCC::DFCC_PrivateData));
}
if (m_Opts.StripRootSignature) {
IFT(pContainerBuilder->RemovePart(hlsl::DxilFourCC::DFCC_RootSignature));
}
if (!m_Opts.PrivateSource.empty()) {
CComPtr<IDxcBlob> privateBlob;
IFT(ReadFileIntoPartContent(hlsl::DxilFourCC::DFCC_PrivateData,
StringRefWide(m_Opts.PrivateSource),
&privateBlob));
// setprivate option can replace existing private part.
// Try removing the private data if exists
pContainerBuilder->RemovePart(hlsl::DxilFourCC::DFCC_PrivateData);
IFT(pContainerBuilder->AddPart(hlsl::DxilFourCC::DFCC_PrivateData,
privateBlob));
}
if (!m_Opts.RootSignatureSource.empty()) {
// set rootsignature assumes that the given input is a dxil container.
// We only want to add RTS0 part to the container builder.
CComPtr<IDxcBlob> RootSignatureBlob;
IFT(ReadFileIntoPartContent(hlsl::DxilFourCC::DFCC_RootSignature,
StringRefWide(m_Opts.RootSignatureSource),
&RootSignatureBlob));
// setrootsignature option can replace existing rootsignature part
// Try removing rootsignature if exists
pContainerBuilder->RemovePart(hlsl::DxilFourCC::DFCC_RootSignature);
IFT(pContainerBuilder->AddPart(hlsl::DxilFourCC::DFCC_RootSignature,
RootSignatureBlob));
}
// Get the final blob from container builder
CComPtr<IDxcOperationResult> pBuilderResult;
IFT(pContainerBuilder->SerializeContainer(&pBuilderResult));
if (!m_Opts.OutputWarningsFile.empty()) {
CComPtr<IDxcBlobEncoding> pErrors;
IFT(pBuilderResult->GetErrorBuffer(&pErrors));
if (pErrors != nullptr) {
WriteBlobToFile(pErrors, m_Opts.OutputWarningsFile,
m_Opts.DefaultTextCodePage);
}
} else {
WriteOperationErrorsToConsole(pBuilderResult, m_Opts.OutputWarnings);
}
HRESULT status;
IFT(pBuilderResult->GetStatus(&status));
IFT(status);
IFT(pBuilderResult->GetResult(ppResult));
}
bool DxcContext::UpdatePartRequired() {
return (m_Opts.StripDebug || m_Opts.StripPrivate ||
m_Opts.StripRootSignature || !m_Opts.PrivateSource.empty() ||
!m_Opts.RootSignatureSource.empty()) &&
(m_Opts.Link || m_Opts.DumpBin || !m_Opts.Preprocess.empty());
}
// This function reads the file from input file and constructs a blob with
// fourCC parts Used for setprivate and setrootsignature option
HRESULT DxcContext::ReadFileIntoPartContent(hlsl::DxilFourCC fourCC,
LPCWSTR fileName,
IDxcBlob **ppResult) {
DXASSERT(fourCC == hlsl::DxilFourCC::DFCC_PrivateData ||
fourCC == hlsl::DxilFourCC::DFCC_RootSignature,
"Otherwise we provided wrong part to read for updating part.");
// Read result, if it's private data, then return the blob
if (fourCC == hlsl::DxilFourCC::DFCC_PrivateData) {
CComPtr<IDxcBlobEncoding> pResult;
ReadFileIntoBlob(m_dxcSupport, fileName, &pResult);
*ppResult = pResult.Detach();
}
// If root signature, check if it's a dxil container that contains
// rootsignature part, then construct a blob of root signature part
if (fourCC == hlsl::DxilFourCC::DFCC_RootSignature) {
CComPtr<IDxcBlob> pResult;
CComHeapPtr<BYTE> pData;
DWORD dataSize;
IFT(hlsl::ReadBinaryFile(fileName, (void **)&pData, &dataSize));
DXASSERT(pData != nullptr,
"otherwise ReadBinaryFile should throw an exception");
hlsl::DxilContainerHeader *pHeader =
hlsl::IsDxilContainerLike(pData.m_pData, dataSize);
IFRBOOL(hlsl::IsValidDxilContainer(pHeader, dataSize), E_INVALIDARG);
hlsl::DxilPartHeader *pPartHeader =
hlsl::GetDxilPartByType(pHeader, hlsl::DxilFourCC::DFCC_RootSignature);
IFRBOOL(pPartHeader != nullptr, E_INVALIDARG);
hlsl::DxcCreateBlobOnHeapCopy(hlsl::GetDxilPartData(pPartHeader),
pPartHeader->PartSize, &pResult);
*ppResult = pResult.Detach();
}
return S_OK;
}
// Constructs a dxil container builder with only root signature part.
// Right now IDxcContainerBuilder assumes that we are building a full dxil
// container, but we are building a container with only rootsignature part
void DxcContext::ExtractRootSignature(IDxcBlob *pBlob, IDxcBlob **ppResult) {
DXASSERT_NOMSG(pBlob != nullptr && ppResult != nullptr);
const hlsl::DxilContainerHeader *pHeader =
(hlsl::DxilContainerHeader *)(pBlob->GetBufferPointer());
IFTBOOL(hlsl::IsValidDxilContainer(pHeader, pHeader->ContainerSizeInBytes),
DXC_E_CONTAINER_INVALID);
const hlsl::DxilPartHeader *pPartHeader =
hlsl::GetDxilPartByType(pHeader, hlsl::DxilFourCC::DFCC_RootSignature);
IFTBOOL(pPartHeader != nullptr, DXC_E_MISSING_PART);
// Get new header and allocate memory for new container
hlsl::DxilContainerHeader newHeader;
uint32_t containerSize =
hlsl::GetDxilContainerSizeFromParts(1, pPartHeader->PartSize);
hlsl::InitDxilContainer(&newHeader, 1, containerSize);
CComPtr<hlsl::AbstractMemoryStream> pMemoryStream;
IFT(hlsl::CreateMemoryStream(DxcGetThreadMallocNoRef(), &pMemoryStream));
ULONG cbWritten;
// Write Container Header
IFT(pMemoryStream->Write(&newHeader, sizeof(hlsl::DxilContainerHeader),
&cbWritten));
IFTBOOL(cbWritten == sizeof(hlsl::DxilContainerHeader), E_OUTOFMEMORY);
// Write Part Offset
uint32_t offset =
sizeof(hlsl::DxilContainerHeader) + hlsl::GetOffsetTableSize(1);
IFT(pMemoryStream->Write(&offset, sizeof(uint32_t), &cbWritten));
IFTBOOL(cbWritten == sizeof(uint32_t), E_OUTOFMEMORY);
// Write Root Signature Header
IFT(pMemoryStream->Write(pPartHeader, sizeof(hlsl::DxilPartHeader),
&cbWritten));
IFTBOOL(cbWritten == sizeof(hlsl::DxilPartHeader), E_OUTOFMEMORY);
const char *partContent = hlsl::GetDxilPartData(pPartHeader);
// Write Root Signature Content
IFT(pMemoryStream->Write(partContent, pPartHeader->PartSize, &cbWritten));
IFTBOOL(cbWritten == pPartHeader->PartSize, E_OUTOFMEMORY);
// Return Result
CComPtr<IDxcBlob> pResult;
IFT(pMemoryStream->QueryInterface(&pResult));
*ppResult = pResult.Detach();
}
int DxcContext::VerifyRootSignature() {
// Get dxil container from file
CComPtr<IDxcBlobEncoding> pSource;
ReadFileIntoBlob(m_dxcSupport, StringRefWide(m_Opts.InputFile), &pSource);
hlsl::DxilContainerHeader *pSourceHeader =
(hlsl::DxilContainerHeader *)pSource->GetBufferPointer();
IFTBOOLMSG(hlsl::IsValidDxilContainer(pSourceHeader,
pSourceHeader->ContainerSizeInBytes),
E_INVALIDARG, "invalid DXIL container to verify.");
// Get rootsignature from file
CComPtr<IDxcBlob> pRootSignature;
IFTMSG(ReadFileIntoPartContent(
hlsl::DxilFourCC::DFCC_RootSignature,
StringRefWide(m_Opts.VerifyRootSignatureSource), &pRootSignature),
"invalid root signature to verify.");
// TODO : Right now we are just going to bild a new blob with updated root
// signature to verify root signature Since dxil container builder will verify
// on its behalf. This does unnecessary memory allocation. We can improve this
// later.
CComPtr<IDxcContainerBuilder> pContainerBuilder;
IFT(CreateInstance(CLSID_DxcContainerBuilder, &pContainerBuilder));
IFT(pContainerBuilder->Load(pSource));
// Try removing root signature if it already exists
pContainerBuilder->RemovePart(hlsl::DxilFourCC::DFCC_RootSignature);
IFT(pContainerBuilder->AddPart(hlsl::DxilFourCC::DFCC_RootSignature,
pRootSignature));
CComPtr<IDxcOperationResult> pOperationResult;
IFT(pContainerBuilder->SerializeContainer(&pOperationResult));
HRESULT status = E_FAIL;
CComPtr<IDxcBlob> pResult;
IFT(pOperationResult->GetStatus(&status));
if (FAILED(status)) {
if (!m_Opts.OutputWarningsFile.empty()) {
CComPtr<IDxcBlobEncoding> pErrors;
IFT(pOperationResult->GetErrorBuffer(&pErrors));
WriteBlobToFile(pErrors, m_Opts.OutputWarningsFile,
m_Opts.DefaultTextCodePage);
} else {
WriteOperationErrorsToConsole(pOperationResult, m_Opts.OutputWarnings);
}
return 1;
} else {
printf("root signature verification succeeded.");
return 0;
}
}
class DxcIncludeHandlerForInjectedSources : public IDxcIncludeHandler {
private:
DXC_MICROCOM_REF_FIELD(m_dwRef)
public:
DXC_MICROCOM_ADDREF_RELEASE_IMPL(m_dwRef)
DxcIncludeHandlerForInjectedSources() : m_dwRef(0){};
std::unordered_map<std::wstring, CComPtr<IDxcBlob>> includeFiles;
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
return DoBasicQueryInterface<IDxcIncludeHandler>(this, iid, ppvObject);
}
HRESULT insertIncludeFile(LPCWSTR pFilename, IDxcBlobEncoding *pBlob,
UINT32 dataLen) {
try {
// Mach change start
// #ifdef _WIN32
// includeFiles.try_emplace(std::wstring(pFilename), pBlob);
// #else
// Mach change end
// Note: try_emplace is only available in C++17 on Linux.
// try_emplace does nothing if the key already exists in the map.
if (includeFiles.find(std::wstring(pFilename)) == includeFiles.end())
includeFiles.emplace(std::wstring(pFilename), pBlob);
// Mach change start
// #endif // _WIN32
// Mach change end
}
CATCH_CPP_RETURN_HRESULT()
return S_OK;
}
HRESULT STDMETHODCALLTYPE LoadSource(LPCWSTR pFilename,
IDxcBlob **ppIncludeSource) override {
try {
// Convert pFilename into native form for indexing as is done when the MD
// is created
std::string FilenameStr8 = Unicode::WideToUTF8StringOrThrow(pFilename);
llvm::SmallString<128> NormalizedPath;
llvm::sys::path::native(FilenameStr8, NormalizedPath);
std::wstring FilenameStr16 =
Unicode::UTF8ToWideStringOrThrow(NormalizedPath.c_str());
*ppIncludeSource = includeFiles.at(FilenameStr16);
(*ppIncludeSource)->AddRef();
}
CATCH_CPP_RETURN_HRESULT()
return S_OK;
}
};
void DxcContext::Recompile(IDxcBlob *pSource, IDxcLibrary *pLibrary,
IDxcCompiler *pCompiler, std::vector<LPCWSTR> &args,
std::wstring &outputPDBPath,
CComPtr<IDxcBlob> &pDebugBlob,
IDxcOperationResult **ppCompileResult) {
CComPtr<IDxcPdbUtils> pPdbUtils;
IFT(CreateInstance(CLSID_DxcPdbUtils, &pPdbUtils));
IFT(pPdbUtils->Load(pSource));
UINT32 uNumFlags = 0;
IFT(pPdbUtils->GetFlagCount(&uNumFlags));
std::vector<const WCHAR *> NewArgs;
std::vector<std::wstring> NewArgsStorage;
for (UINT32 i = 0; i < uNumFlags; i++) {
CComBSTR pFlag;
IFT(pPdbUtils->GetFlag(i, &pFlag));
NewArgsStorage.push_back(std::wstring(pFlag));
}
for (const std::wstring &flag : NewArgsStorage)
NewArgs.push_back(flag.c_str());
UINT32 uNumDefines = 0;
IFT(pPdbUtils->GetDefineCount(&uNumDefines));
std::vector<std::wstring> NewDefinesStorage;
std::vector<DxcDefine> NewDefines;
for (UINT32 i = 0; i < uNumDefines; i++) {
CComBSTR pDefine;
IFT(pPdbUtils->GetDefine(i, &pDefine));
NewDefinesStorage.push_back(std::wstring(pDefine));
}
for (std::wstring &Define : NewDefinesStorage) {
wchar_t *pDefineStart = &Define[0];
wchar_t *pDefineEnd = pDefineStart + Define.size();
DxcDefine D = {};
D.Name = pDefineStart;
D.Value = nullptr;
for (wchar_t *pCursor = pDefineStart; pCursor < pDefineEnd; ++pCursor) {
if (*pCursor == L'=') {
*pCursor = L'\0';
D.Value = (pCursor + 1);
break;
}
}
NewDefines.push_back(D);
}
CComBSTR pMainFileName;
CComBSTR pTargetProfile;
CComBSTR pEntryPoint;
IFT(pPdbUtils->GetMainFileName(&pMainFileName));
IFT(pPdbUtils->GetTargetProfile(&pTargetProfile));
IFT(pPdbUtils->GetEntryPoint(&pEntryPoint));
CComPtr<IDxcBlobEncoding> pCompileSource;
CComPtr<DxcIncludeHandlerForInjectedSources> pIncludeHandler =
new DxcIncludeHandlerForInjectedSources();
UINT32 uSourceCount = 0;
IFT(pPdbUtils->GetSourceCount(&uSourceCount));
for (UINT32 i = 0; i < uSourceCount; i++) {
CComPtr<IDxcBlobEncoding> pSourceFile;
CComBSTR pFileName;
IFT(pPdbUtils->GetSource(i, &pSourceFile));
IFT(pPdbUtils->GetSourceName(i, &pFileName));
IFT(pIncludeHandler->insertIncludeFile(pFileName, pSourceFile, 0));
if (pMainFileName == pFileName) {
// Transfer pSourceFile to avoid extra AddRef+Release.
pCompileSource.Attach(pSourceFile.Detach());
}
}
CComPtr<IDxcOperationResult> pResult;
if (!m_Opts.DebugFile.empty()) {
CComPtr<IDxcCompiler2> pCompiler2;
CComHeapPtr<WCHAR> pDebugName;
Unicode::UTF8ToWideString(m_Opts.DebugFile.str().c_str(), &outputPDBPath);
IFT(pCompiler->QueryInterface(&pCompiler2));
IFT(pCompiler2->CompileWithDebug(
pCompileSource, pMainFileName, pEntryPoint, pTargetProfile,
NewArgs.data(), NewArgs.size(), NewDefines.data(), NewDefines.size(),
pIncludeHandler, &pResult, &pDebugName, &pDebugBlob));
if (pDebugName.m_pData && m_Opts.DebugFileIsDirectory()) {
outputPDBPath += pDebugName.m_pData;
}
} else {
IFT(pCompiler->Compile(pCompileSource, pMainFileName, pEntryPoint,
pTargetProfile, NewArgs.data(), NewArgs.size(),
NewDefines.data(), NewDefines.size(),
pIncludeHandler, &pResult));
}
*ppCompileResult = pResult.Detach();
}
int DxcContext::Compile() {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pCompileResult;
CComPtr<IDxcBlob> pDebugBlob;
std::wstring outputPDBPath;
{
CComPtr<IDxcBlobEncoding> pSource;
std::vector<std::wstring> argStrings;
CopyArgsToWStrings(m_Opts.Args, CoreOption, argStrings);
std::vector<LPCWSTR> args;
args.reserve(argStrings.size());
for (const std::wstring &a : argStrings)
args.push_back(a.data());
if (m_Opts.AstDump)
args.push_back(L"-ast-dump");
CComPtr<IDxcLibrary> pLibrary;
IFT(CreateInstance(CLSID_DxcLibrary, &pLibrary));
IFT(CreateInstance(CLSID_DxcCompiler, &pCompiler));
ReadFileIntoBlob(m_dxcSupport, StringRefWide(m_Opts.InputFile), &pSource);
IFTARG(pSource->GetBufferSize() >= 4);
if (m_Opts.RecompileFromBinary) {
Recompile(pSource, pLibrary, pCompiler, args, outputPDBPath, pDebugBlob,
&pCompileResult);
} else {
CComPtr<IDxcIncludeHandler> pIncludeHandler;
IFT(pLibrary->CreateIncludeHandler(&pIncludeHandler));
// Upgrade profile to 6.0 version from minimum recognized shader model
llvm::StringRef TargetProfile = m_Opts.TargetProfile;
const hlsl::ShaderModel *SM =
hlsl::ShaderModel::GetByName(m_Opts.TargetProfile.str().c_str());
if (SM->IsValid() && SM->GetMajor() < 6) {
TargetProfile = hlsl::ShaderModel::Get(SM->GetKind(), 6, 0)->GetName();
std::string versionWarningString =
"warning: Promoting older shader model profile to 6.0 version.";
fprintf(stderr, "%s\n", versionWarningString.data());
if (!SM->IsSM51Plus()) {
// Add flag for backcompat with SM 5.0 resource reservation
args.push_back(L"-flegacy-resource-reservation");
}
}
if (!m_Opts.DebugFile.empty()) {
CComPtr<IDxcCompiler2> pCompiler2;
CComHeapPtr<WCHAR> pDebugName;
Unicode::UTF8ToWideString(m_Opts.DebugFile.str().c_str(),
&outputPDBPath);
IFT(pCompiler.QueryInterface(&pCompiler2));
IFT(pCompiler2->CompileWithDebug(
pSource, StringRefWide(m_Opts.InputFile),
StringRefWide(m_Opts.EntryPoint), StringRefWide(TargetProfile),
args.data(), args.size(), m_Opts.Defines.data(),
m_Opts.Defines.size(), pIncludeHandler, &pCompileResult,
&pDebugName, &pDebugBlob));
if (pDebugName.m_pData && m_Opts.DebugFileIsDirectory()) {
outputPDBPath += pDebugName.m_pData;
}
} else {
IFT(pCompiler->Compile(
pSource, StringRefWide(m_Opts.InputFile),
StringRefWide(m_Opts.EntryPoint), StringRefWide(TargetProfile),
args.data(), args.size(), m_Opts.Defines.data(),
m_Opts.Defines.size(), pIncludeHandler, &pCompileResult));
}
}
// When compiling we don't embed debug info if options don't ask for it.
// If user specified /Qstrip_debug, remove from m_Opts now so we don't
// try to modify the container to strip debug info that isn't there.
if (!m_Opts.EmbedDebugInfo()) {
m_Opts.StripDebug = false;
}
}
if (!m_Opts.OutputWarningsFile.empty()) {
CComPtr<IDxcBlobEncoding> pErrors;
IFT(pCompileResult->GetErrorBuffer(&pErrors));
WriteBlobToFile(pErrors, m_Opts.OutputWarningsFile,
m_Opts.DefaultTextCodePage);
} else {
WriteOperationErrorsToConsole(pCompileResult, m_Opts.OutputWarnings);
}
HRESULT status;
IFT(pCompileResult->GetStatus(&status));
if (SUCCEEDED(status) || m_Opts.AstDump || m_Opts.OptDump ||
m_Opts.DumpDependencies || m_Opts.VerifyDiagnostics) {
CComPtr<IDxcBlob> pProgram;
IFT(pCompileResult->GetResult(&pProgram));
if (pProgram.p != nullptr) {
ActOnBlob(pProgram.p, pDebugBlob, outputPDBPath.c_str());
// Now write out extra parts
CComPtr<IDxcResult> pResult;
if (SUCCEEDED(pCompileResult->QueryInterface(&pResult))) {
WriteDxcOutputToConsole(pResult, DXC_OUT_REMARKS);
WriteDxcOutputToConsole(pResult, DXC_OUT_TIME_REPORT);
if (m_Opts.TimeTrace == "-")
WriteDxcOutputToConsole(pResult, DXC_OUT_TIME_TRACE);
else if (!m_Opts.TimeTrace.empty()) {
CComPtr<IDxcBlob> pData;
CComPtr<IDxcBlobWide> pName;
IFT(pResult->GetOutput(DXC_OUT_TIME_TRACE, IID_PPV_ARGS(&pData),
&pName));
WriteBlobToFile(pData, m_Opts.TimeTrace, m_Opts.DefaultTextCodePage);
}
WriteDxcOutputToFile(DXC_OUT_ROOT_SIGNATURE, pResult,
m_Opts.DefaultTextCodePage);
WriteDxcOutputToFile(DXC_OUT_SHADER_HASH, pResult,
m_Opts.DefaultTextCodePage);
WriteDxcOutputToFile(DXC_OUT_REFLECTION, pResult,
m_Opts.DefaultTextCodePage);
WriteDxcExtraOuputs(pResult);
}
}
}
return status;
}
int DxcContext::Link() {
CComPtr<IDxcLinker> pLinker;
IFT(CreateInstance(CLSID_DxcLinker, &pLinker));
llvm::StringRef InputFiles = m_Opts.InputFile;
llvm::StringRef InputFilesRef(InputFiles);
llvm::SmallVector<llvm::StringRef, 2> InputFileList;
InputFilesRef.split(InputFileList, ";");
std::vector<std::wstring> wInputFiles;
wInputFiles.reserve(InputFileList.size());
std::vector<LPCWSTR> wpInputFiles;
wpInputFiles.reserve(InputFileList.size());
for (auto &file : InputFileList) {
wInputFiles.emplace_back(StringRefWide(file.str()));
wpInputFiles.emplace_back(wInputFiles.back().c_str());
CComPtr<IDxcBlobEncoding> pLib;
ReadFileIntoBlob(m_dxcSupport, wInputFiles.back().c_str(), &pLib);
IFT(pLinker->RegisterLibrary(wInputFiles.back().c_str(), pLib));
}
CComPtr<IDxcOperationResult> pLinkResult;
std::vector<std::wstring> argStrings;
CopyArgsToWStrings(m_Opts.Args, CoreOption, argStrings);
std::vector<LPCWSTR> args;
args.reserve(argStrings.size());
for (const std::wstring &a : argStrings)
args.push_back(a.data());
IFT(pLinker->Link(StringRefWide(m_Opts.EntryPoint),
StringRefWide(m_Opts.TargetProfile), wpInputFiles.data(),
wpInputFiles.size(), args.data(), args.size(),
&pLinkResult));
HRESULT status;
IFT(pLinkResult->GetStatus(&status));
if (SUCCEEDED(status)) {
CComPtr<IDxcBlob> pContainer;
IFT(pLinkResult->GetResult(&pContainer));
if (pContainer.p != nullptr) {
ActOnBlob(pContainer.p);
}
} else {
CComPtr<IDxcBlobEncoding> pErrors;
IFT(pLinkResult->GetErrorBuffer(&pErrors));
if (pErrors != nullptr) {
printf("Link failed:\n%s",
static_cast<char *>(pErrors->GetBufferPointer()));
}
return 1;
}
return 0;
}
int DxcContext::DumpBinary() {