1//===- DXILContainerPDB.cpp - DirectX PDB writer pass ---------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "DirectX.h"
10#include "MCTargetDesc/DirectXContainerObjectWriter.h"
11#include "llvm/ADT/ScopeExit.h"
12#include "llvm/ADT/StringSet.h"
13#include "llvm/DebugInfo/CodeView/GUID.h"
14#include "llvm/DebugInfo/MSF/MSFBuilder.h"
15#include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
16#include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
17#include "llvm/IR/Analysis.h"
18#include "llvm/IR/Constants.h"
19#include "llvm/IR/Module.h"
20#include "llvm/IR/PassManager.h"
21#include "llvm/MC/MCDXContainerWriter.h"
22#include "llvm/Pass.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/Support/FileSystem.h"
25#include "llvm/Support/IOSandbox.h"
26#include "llvm/Support/VirtualFileSystem.h"
27#include "llvm/Transforms/Utils/ModuleUtils.h"
28
29using namespace llvm;
30
31namespace {
32
33class DXILContainerPDBImpl : MCDXContainerBaseWriter {
34 Module *M = nullptr;
35 SmallVector<MCDXContainerPart> Parts;
36
37 void reset() {
38 M = nullptr;
39 Parts.clear();
40 }
41
42public:
43 bool shouldSkipSection(StringRef SectionName, size_t SectionSize) override;
44 ArrayRef<MCDXContainerPart> collectParts() override;
45 bool runOnModule(Module &M);
46};
47
48class DXILContainerPDBLegacy : public ModulePass {
49public:
50 static char ID;
51 DXILContainerPDBLegacy() : ModulePass(ID) {}
52
53 StringRef getPassName() const override { return "DirectX PDB Emitter"; }
54
55 bool runOnModule(Module &M) override;
56
57 void getAnalysisUsage(AnalysisUsage &AU) const override {
58 AU.setPreservesAll();
59 }
60};
61
62} // namespace
63
64bool DXILContainerPDBImpl::shouldSkipSection(StringRef SectionName,
65 size_t SectionSize) {
66 if (MCDXContainerBaseWriter::shouldSkipSection(SectionName, SectionSize))
67 return true;
68 if (dxil::SlimDebug && SectionName == "ILDB")
69 return true;
70
71 // Skip sections that are irrelevant for debug info.
72 static const StringSet<> DebugSections{"ILDB", "ILDN", "HASH", "PDBI",
73 "SRCI", "STAT", "RDAT", "VERS"};
74 return !DebugSections.contains(key: SectionName);
75}
76
77static StringRef getGlobalData(const GlobalVariable &GV) {
78 if (GV.hasInitializer())
79 if (const auto *Data =
80 dyn_cast<ConstantDataSequential>(Val: GV.getInitializer()))
81 return Data->getRawDataValues();
82 return {};
83}
84
85ArrayRef<MCDXContainerPart> DXILContainerPDBImpl::collectParts() {
86 Parts.clear();
87 for (const GlobalVariable &GV : M->globals()) {
88 StringRef Name = GV.getSection();
89 StringRef Data = getGlobalData(GV);
90
91 if (Data.empty())
92 continue;
93 if (shouldSkipSection(SectionName: Name, SectionSize: Data.size()))
94 continue;
95
96 Parts.push_back(Elt: {.Name: Name, .Data: Data});
97 }
98 return Parts;
99}
100
101static GlobalVariable *createPrivateDataGlobal(Module &M, StringRef Data) {
102 Constant *Content =
103 ConstantDataArray::getString(Context&: M.getContext(), Initializer: Data, /*AddNull*/ false);
104 auto *GV =
105 new GlobalVariable(M, Content->getType(), true,
106 GlobalValue::PrivateLinkage, Content, "dx.priv");
107 GV->setSection("PRIV");
108 GV->setAlignment(Align(1));
109 return GV;
110}
111
112bool DXILContainerPDBImpl::runOnModule(Module &M) {
113 llvm::scope_exit Cleanup([&]() { reset(); });
114 this->M = &M;
115
116 SmallString<128> DebugFileName;
117 ArrayRef<char> ModuleHash;
118 for (const GlobalVariable &GV : M.globals()) {
119 if (GV.getSection() == PdbFileNameSectionName) {
120 assert(DebugFileName.empty() && "Duplicate PDBNAME section");
121 DebugFileName = getGlobalData(GV);
122 } else if (GV.getSection() == ModuleHashSectionName) {
123 assert(ModuleHash.empty() && "Duplicate PBDHASH section");
124 StringRef Data = getGlobalData(GV);
125 ModuleHash = ArrayRef(Data.data(), Data.size());
126 }
127 }
128
129 // PDB emission was not requested.
130 if (DebugFileName.empty() && !dxil::PdbInPrivate)
131 return false;
132 if (ModuleHash.empty())
133 report_fatal_error(reason: "Module hash for PDB not found");
134
135 bool DeleteAfterRead = false;
136 if (DebugFileName.empty()) {
137 if (std::error_code EC =
138 sys::fs::createTemporaryFile(Prefix: "dxil", Suffix: "pdb", ResultPath&: DebugFileName))
139 reportFatalInternalError(reason: "Failed to create temporary PDB file");
140 DeleteAfterRead = true;
141 }
142 llvm::scope_exit FileCleanup([&]() {
143 if (DeleteAfterRead)
144 sys::fs::remove(path: DebugFileName);
145 });
146
147 BumpPtrAllocator Allocator;
148 pdb::PDBFileBuilder Builder(Allocator);
149
150 // DirectXShaderCompiler uses block size 512.
151 if (Error Err = Builder.initialize(BlockSize: 512))
152 reportFatalInternalError(Err: std::move(Err));
153
154 // Reserved streams that should be empty.
155 static_assert(pdb::kSpecialStreamCount == 5 &&
156 "First 5 streams should be empty in DirectX PDB file");
157 for (uint32_t I = 0; I < pdb::kSpecialStreamCount; ++I) {
158 if (auto Err = Builder.getMsfBuilder().addStream(Size: 0).takeError())
159 reportFatalInternalError(Err: std::move(Err));
160 }
161
162 // Add DXContainer stream.
163 if (auto Err = Builder.getMsfBuilder().addStream(Size: 0).takeError())
164 reportFatalInternalError(Err: std::move(Err));
165
166 // InfoStream must be filled. Bitcode hash from HASH part is used for PDB
167 // GUID.
168 codeview::GUID PdbGuid;
169 assert(ModuleHash.size() == std::size(PdbGuid.Guid) &&
170 "Module hash length must be match GUID length");
171 std::copy_n(first: ModuleHash.begin(), n: std::size(PdbGuid.Guid), result: PdbGuid.Guid);
172
173 auto &InfoBuilder = Builder.getInfoBuilder();
174 InfoBuilder.setAge(1);
175 InfoBuilder.setGuid(PdbGuid);
176 InfoBuilder.setSignature(0);
177 InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
178
179 // Write DXContainer.
180 raw_svector_ostream OS(*Builder.getDXContainerData());
181 write(OS, TT: M.getTargetTriple());
182
183 // Write PDB file.
184 codeview::GUID IgnoredOutGuid;
185 {
186 // FIXME(sandboxing): Remove this by routing output through OutputBackend.
187 auto BypassSandbox = sys::sandbox::scopedDisable();
188 if (Error Err = Builder.commit(Filename: DebugFileName, Guid: &IgnoredOutGuid))
189 reportFatalUsageError(reason: "Couldn't write to PDB file: " +
190 Twine(toString(E: std::move(Err))));
191 }
192
193 if (!dxil::PdbInPrivate)
194 return false;
195
196 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
197 M.getContext().getVirtualFileSystem().getBufferForFile(
198 Name: DebugFileName, /*FileSize=*/-1, /*RequiresNullTerminator=*/false,
199 /*IsVolatile=*/false, /*IsText=*/false);
200 if (!Buf)
201 reportFatalInternalError(reason: "Failed to read PDB for PRIV embedding");
202
203 appendToCompilerUsed(M, Values: createPrivateDataGlobal(M, Data: (*Buf)->getBuffer()));
204
205 return true;
206}
207
208char DXILContainerPDBLegacy::ID = 0;
209INITIALIZE_PASS(DXILContainerPDBLegacy, "dxil-container-pdb",
210 "DirectX PDB Emitter", false, true)
211
212ModulePass *llvm::createDXILContainerPDBLegacyPass() {
213 return new DXILContainerPDBLegacy();
214}
215
216bool DXILContainerPDBLegacy::runOnModule(Module &M) {
217 DXILContainerPDBImpl Impl;
218 return Impl.runOnModule(M);
219}
220
221PreservedAnalyses DXILContainerPDBPass::run(Module &M,
222 ModuleAnalysisManager &MAM) {
223 DXILContainerPDBImpl Impl;
224 Impl.runOnModule(M);
225 return PreservedAnalyses::all();
226}
227