LLVM 24.0.0git
DXContainerPDB.cpp
Go to the documentation of this file.
1//===- DXContainerPDB.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"
11#include "llvm/ADT/ScopeExit.h"
12#include "llvm/ADT/StringSet.h"
18#include "llvm/IR/Constants.h"
19#include "llvm/IR/Module.h"
21#include "llvm/Pass.h"
27
28using namespace llvm;
29
30namespace {
31
32class DXContainerPDB : public ModulePass, MCDXContainerBaseWriter {
33 Module *M = nullptr;
35
36 void reset() {
37 M = nullptr;
38 Parts.clear();
39 }
40
41public:
42 static char ID;
43 DXContainerPDB() : ModulePass(ID) {}
44
45 StringRef getPassName() const override { return "DirectX PDB Emitter"; }
46
47 bool runOnModule(Module &M) override;
48
49 void getAnalysisUsage(AnalysisUsage &AU) const override {
50 AU.setPreservesAll();
51 }
52
53 bool shouldSkipSection(StringRef SectionName, size_t SectionSize) override;
54 ArrayRef<MCDXContainerPart> collectParts() override;
55};
56
57} // namespace
58
59bool DXContainerPDB::shouldSkipSection(StringRef SectionName,
60 size_t SectionSize) {
61 if (MCDXContainerBaseWriter::shouldSkipSection(SectionName, SectionSize))
62 return true;
63 if (dxil::SlimDebug && SectionName == "ILDB")
64 return true;
65
66 // Skip sections that are irrelevant for debug info.
67 static const StringSet<> DebugSections{"ILDB", "ILDN", "HASH", "PDBI",
68 "SRCI", "STAT", "RDAT", "VERS"};
69 return !DebugSections.contains(SectionName);
70}
71
73 if (GV.hasInitializer())
74 if (const auto *Data =
76 return Data->getRawDataValues();
77 return {};
78}
79
80ArrayRef<MCDXContainerPart> DXContainerPDB::collectParts() {
81 Parts.clear();
82 for (const GlobalVariable &GV : M->globals()) {
83 StringRef Name = GV.getSection();
84 StringRef Data = getGlobalData(GV);
85
86 if (Data.empty())
87 continue;
88 if (shouldSkipSection(Name, Data.size()))
89 continue;
90
91 Parts.push_back({Name, Data});
92 }
93 return Parts;
94}
95
97 Constant *Content =
98 ConstantDataArray::getString(M.getContext(), Data, /*AddNull*/ false);
99 auto *GV =
100 new GlobalVariable(M, Content->getType(), true,
101 GlobalValue::PrivateLinkage, Content, "dx.priv");
102 GV->setSection("PRIV");
103 GV->setAlignment(Align(1));
104 return GV;
105}
106
107bool DXContainerPDB::runOnModule(Module &M) {
108 llvm::scope_exit Cleanup([&]() { reset(); });
109 this->M = &M;
110
111 SmallString<128> DebugFileName;
112 ArrayRef<char> ModuleHash;
113 for (const GlobalVariable &GV : M.globals()) {
114 if (GV.getSection() == PdbFileNameSectionName) {
115 assert(DebugFileName.empty() && "Duplicate PDBNAME section");
116 DebugFileName = getGlobalData(GV);
117 } else if (GV.getSection() == ModuleHashSectionName) {
118 assert(ModuleHash.empty() && "Duplicate PBDHASH section");
119 StringRef Data = getGlobalData(GV);
120 ModuleHash = ArrayRef(Data.data(), Data.size());
121 }
122 }
123
124 // PDB emission was not requested.
125 if (DebugFileName.empty() && !dxil::PdbInPrivate)
126 return false;
127 if (ModuleHash.empty())
128 report_fatal_error("Module hash for PDB not found");
129
130 bool DeleteAfterRead = false;
131 if (DebugFileName.empty()) {
132 if (std::error_code EC =
133 sys::fs::createTemporaryFile("dxil", "pdb", DebugFileName))
134 reportFatalInternalError("Failed to create temporary PDB file");
135 DeleteAfterRead = true;
136 }
137 llvm::scope_exit FileCleanup([&]() {
138 if (DeleteAfterRead)
139 sys::fs::remove(DebugFileName);
140 });
141
143 pdb::PDBFileBuilder Builder(Allocator);
144
145 // DirectXShaderCompiler uses block size 512.
146 if (Error Err = Builder.initialize(512))
147 reportFatalInternalError(std::move(Err));
148
149 // Reserved streams that should be empty.
150 static_assert(pdb::kSpecialStreamCount == 5 &&
151 "First 5 streams should be empty in DirectX PDB file");
152 for (uint32_t I = 0; I < pdb::kSpecialStreamCount; ++I) {
153 if (auto Err = Builder.getMsfBuilder().addStream(0).takeError())
154 reportFatalInternalError(std::move(Err));
155 }
156
157 // Add DXContainer stream.
158 if (auto Err = Builder.getMsfBuilder().addStream(0).takeError())
159 reportFatalInternalError(std::move(Err));
160
161 // InfoStream must be filled. Bitcode hash from HASH part is used for PDB
162 // GUID.
163 codeview::GUID PdbGuid;
164 assert(ModuleHash.size() == std::size(PdbGuid.Guid) &&
165 "Module hash length must be match GUID length");
166 std::copy_n(ModuleHash.begin(), std::size(PdbGuid.Guid), PdbGuid.Guid);
167
168 auto &InfoBuilder = Builder.getInfoBuilder();
169 InfoBuilder.setAge(1);
170 InfoBuilder.setGuid(PdbGuid);
171 InfoBuilder.setSignature(0);
172 InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
173
174 // Write DXContainer.
175 raw_svector_ostream OS(*Builder.getDXContainerData());
176 write(OS, M.getTargetTriple());
177
178 // Write PDB file.
179 codeview::GUID IgnoredOutGuid;
180 {
181 // FIXME(sandboxing): Remove this by routing output through OutputBackend.
182 auto BypassSandbox = sys::sandbox::scopedDisable();
183 if (Error Err = Builder.commit(DebugFileName, &IgnoredOutGuid))
184 reportFatalUsageError("Couldn't write to PDB file: " +
185 Twine(toString(std::move(Err))));
186 }
187
189 return false;
190
191 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
192 M.getContext().getVirtualFileSystem().getBufferForFile(
193 DebugFileName, /*FileSize=*/-1, /*RequiresNullTerminator=*/false,
194 /*IsVolatile=*/false, /*IsText=*/false);
195 if (!Buf)
196 reportFatalInternalError("Failed to read PDB for PRIV embedding");
197
198 appendToCompilerUsed(M, createPrivateDataGlobal(M, (*Buf)->getBuffer()));
199
200 return true;
201}
202
203char DXContainerPDB::ID = 0;
204INITIALIZE_PASS(DXContainerPDB, "dxil-pdb", "DirectX PDB Emitter", false, true)
205
206ModulePass *llvm::createDXContainerPDBPass() { return new DXContainerPDB(); }
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static StringRef getGlobalData(const GlobalVariable &GV)
static GlobalVariable * createPrivateDataGlobal(Module &M, StringRef Data)
ManagedStatic< HTTPClientCleanup > Cleanup
Module.h This file contains the declarations for the Module class.
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
Basic Register Allocator
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
StringSet - A set-like wrapper for the StringMap.
Defines the virtual file system interface vfs::FileSystem.
void setPreservesAll()
Set by analyses that do not transform their input at all.
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
This is an important base class in LLVM.
Definition Constant.h:43
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
virtual bool shouldSkipSection(StringRef SectionName, size_t SectionSize)
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:253
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
void push_back(const T &Elt)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool contains(StringRef key) const
Check if the set contains the given key.
Definition StringSet.h:60
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
cl::opt< bool > SlimDebug
cl::opt< bool > PdbInPrivate
@ kSpecialStreamCount
LLVM_ABI std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
LLVM_ABI std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD, SmallVectorImpl< char > &ResultPath, OpenFlags Flags=OF_None)
Create a file in the system temporary directory.
Definition Path.cpp:936
ScopedSetting scopedDisable()
Definition IOSandbox.h:36
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
scope_exit(Callable) -> scope_exit< Callable >
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI void reportFatalInternalError(Error Err)
Report a fatal error that indicates a bug in LLVM.
Definition Error.cpp:173
static constexpr StringLiteral ModuleHashSectionName
Contains module hash.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391
LLVM_ABI Error write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
Definition DWP.cpp:746
ModulePass * createDXContainerPDBPass()
Pass for emitting DirectX PDB files.
static constexpr StringLiteral PdbFileNameSectionName
Contains PDB output file name.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
uint8_t Guid[16]
Definition GUID.h:23