LLVM 24.0.0git
DXILWriterPass.cpp
Go to the documentation of this file.
1//===- DXILWriterPass.cpp - Bitcode writing 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// DXILWriterPass implementation.
10//
11//===----------------------------------------------------------------------===//
12
13#include "DXILWriterPass.h"
14#include "DXILBitcodeWriter.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/StringRef.h"
18#include "llvm/IR/Constants.h"
19#include "llvm/IR/DebugInfo.h"
23#include "llvm/IR/Intrinsics.h"
24#include "llvm/IR/LLVMContext.h"
25#include "llvm/IR/Module.h"
26#include "llvm/IR/PassManager.h"
28#include "llvm/Pass.h"
33
34using namespace llvm;
35using namespace llvm::dxil;
36
40 "dx-pdb-path",
41 cl::desc("Write debug information to the given file, or automatically "
42 "named file in directory when ending in '/'"),
43 cl::value_desc("filename"));
45 "dx-source-in-debug-module",
46 cl::desc("Embed source code into debug module on DirectX target"),
47 cl::init(false));
49
50namespace {
51class WriteDXILPass : public llvm::ModulePass {
52 raw_ostream &OS; // raw_ostream to print on
53
54public:
55 static char ID; // Pass identification, replacement for typeid
56 WriteDXILPass() : ModulePass(ID), OS(dbgs()) {
58 }
59
60 explicit WriteDXILPass(raw_ostream &o) : ModulePass(ID), OS(o) {
62 }
63
64 StringRef getPassName() const override { return "Bitcode Writer"; }
65
66 bool runOnModule(Module &M) override {
67 WriteDXILToFile(M, OS);
68 return false;
69 }
70 void getAnalysisUsage(AnalysisUsage &AU) const override {
71 AU.setPreservesAll();
72 }
73};
74
75static void legalizeLifetimeIntrinsics(Module &M) {
76 LLVMContext &Ctx = M.getContext();
77 Type *I64Ty = IntegerType::get(Ctx, 64);
78 Type *PtrTy = PointerType::get(Ctx, 0);
79 Intrinsic::ID LifetimeIIDs[2] = {Intrinsic::lifetime_start,
80 Intrinsic::lifetime_end};
81 for (Intrinsic::ID &IID : LifetimeIIDs) {
82 Function *F = M.getFunction(Intrinsic::getName(IID, {PtrTy}, &M));
83 if (!F)
84 continue;
85
86 // Get or insert an LLVM 3.7-compliant lifetime intrinsic function of the
87 // form `void @llvm.lifetime.[start/end](i64, ptr)` with the NoUnwind
88 // attribute
89 AttributeList Attr;
90 Attr = Attr.addFnAttribute(Ctx, Attribute::NoUnwind);
91 FunctionCallee LifetimeCallee = M.getOrInsertFunction(
92 Intrinsic::getBaseName(IID), Attr, Type::getVoidTy(Ctx), I64Ty, PtrTy);
93
94 // Replace all calls to lifetime intrinsics with calls to the
95 // LLVM 3.7-compliant version of the lifetime intrinsic
96 for (User *U : make_early_inc_range(F->users())) {
98 assert(CI &&
99 "Expected user of a lifetime intrinsic function to be a CallInst");
100
101 // LLVM 3.7 lifetime intrinics require an i8* operand, so we insert
102 // a bitcast to ensure that is the case
103 Value *PtrOperand = CI->getArgOperand(0);
104 PointerType *PtrOpPtrTy = cast<PointerType>(PtrOperand->getType());
105 Value *NoOpBitCast = CastInst::Create(Instruction::BitCast, PtrOperand,
106 PtrOpPtrTy, "", CI->getIterator());
107
108 // LLVM 3.7 lifetime intrinsics have an explicit size operand, whose value
109 // we can obtain from the pointer operand which must be an AllocaInst (as
110 // of https://github.com/llvm/llvm-project/pull/149310)
111 AllocaInst *AI = dyn_cast<AllocaInst>(PtrOperand);
112 assert(AI &&
113 "The pointer operand of a lifetime intrinsic call must be an "
114 "AllocaInst");
115 std::optional<TypeSize> AllocSize =
117 assert(AllocSize.has_value() &&
118 "Expected the allocation size of AllocaInst to be known");
119 CallInst *NewCI = CallInst::Create(
120 LifetimeCallee,
121 {ConstantInt::get(I64Ty, AllocSize.value().getFixedValue()),
122 NoOpBitCast},
123 "", CI->getIterator());
125 NewCI->addParamAttr(1, ParamAttr);
126
127 CI->eraseFromParent();
128 }
129
130 F->eraseFromParent();
131 }
132}
133
134static void removeLifetimeIntrinsics(Module &M) {
135 Intrinsic::ID LifetimeIIDs[2] = {Intrinsic::lifetime_start,
136 Intrinsic::lifetime_end};
137 for (Intrinsic::ID &IID : LifetimeIIDs) {
138 Function *F = M.getFunction(Intrinsic::getBaseName(IID));
139 if (!F)
140 continue;
141
142 for (User *U : make_early_inc_range(F->users())) {
144 assert(CI && "Expected user of lifetime function to be a CallInst");
146 assert(BCI && "Expected pointer operand of CallInst to be a BitCastInst");
147 CI->eraseFromParent();
148 BCI->eraseFromParent();
149 }
150 F->eraseFromParent();
151 }
152}
153
154static void replaceNamedMetadataArray(Module &M, StringRef Name,
155 ArrayRef<Metadata *> NewOps) {
156 NamedMDNode *NMD = M.getNamedMetadata(Name);
157 if (!NMD)
158 return;
159 NMD->eraseFromParent();
160 M.getOrInsertNamedMetadata(Name)->addOperand(
161 MDTuple::get(M.getContext(), NewOps));
162}
163
164class EmbedDXILPass : public llvm::ModulePass {
165 std::string writeModule(Module &M, bool HasDebugInfo, bool WriteDebug) {
166 std::string Data;
167 llvm::raw_string_ostream OS(Data);
168
169 if (HasDebugInfo) {
170 if (WriteDebug) {
171 if (!SourceInDebugModule) {
172 // Replace dx.source metadata nodes with stubs.
173 LLVMContext &Ctx = M.getContext();
174 MDString *EmptyString = MDString::get(Ctx, "");
175 replaceNamedMetadataArray(M, "dx.source.contents",
176 {EmptyString, EmptyString});
177 replaceNamedMetadataArray(M, "dx.source.defines", {});
178 replaceNamedMetadataArray(M, "dx.source.mainFileName", {EmptyString});
179 replaceNamedMetadataArray(M, "dx.source.args", {});
180 }
181 } else {
182 // If we have an ILDB part, strip DXIL from all debug info.
184
185 // Also, manually remove debug version flags and dx.source nodes.
186 if (NamedMDNode *Flags = M.getModuleFlagsMetadata()) {
188 M.getModuleFlagsMetadata(FlagEntries);
189 Flags->eraseFromParent();
190 for (llvm::Module::ModuleFlagEntry &Entry : FlagEntries) {
191 if (Entry.Key->getString() == "Dwarf Version" ||
192 Entry.Key->getString() == "Debug Info Version") {
193 continue;
194 }
195 M.addModuleFlag(Entry.Behavior, Entry.Key->getString(), Entry.Val);
196 }
197 }
198 for (NamedMDNode &NMD : llvm::make_early_inc_range(M.named_metadata()))
199 if (NMD.getName().starts_with("dx.source"))
200 NMD.eraseFromParent();
201 }
202 } else {
203#ifdef EXPENSIVE_CHECKS
204 assert(
205 StripDebugInfo(M) == false &&
206 "The module must not contain any debug info here."
207 "Shader modules with debug info must have !DICompileUnit metadata.");
208#endif
209 }
210 WriteDXILToFile(M, OS);
211 return Data;
212 }
213
214 GlobalVariable *createSectionGlobal(Module &M, StringRef Data,
215 StringRef GlobalName,
216 StringRef SectionName) {
217 Constant *ModuleConstant =
219 auto *GV = new llvm::GlobalVariable(M, ModuleConstant->getType(), true,
221 ModuleConstant, GlobalName);
222 GV->setSection(SectionName);
223 GV->setAlignment(Align(4));
224 return GV;
225 }
226
227public:
228 static char ID; // Pass identification, replacement for typeid
229 EmbedDXILPass() : ModulePass(ID) {
231 }
232
233 StringRef getPassName() const override { return "DXIL Embedder"; }
234
235 bool runOnModule(Module &M) override {
236 // Perform late legalization of lifetime intrinsics that would otherwise
237 // fail the Module Verifier if performed in an earlier pass
238 legalizeLifetimeIntrinsics(M);
239
240 bool HasDebugInfo = !M.debug_compile_units().empty();
241
242 if (SlimDebug && EmbedDebug)
243 reportFatalUsageError("/Qembed_debug is not compatible with /Zs");
244
245 // If both StripDebug and EmbedDebug are specified, StripDebug is ignored.
246 if (StripDebug && EmbedDebug)
247 StripDebug = false;
248 // Enable EmbedDebug if there is debug info, but it is not being stripped
249 // or written to a PDB file.
250 if (HasDebugInfo && !StripDebug && !SlimDebug && PdbDebugPath.empty())
251 EmbedDebug = true;
252 if (!HasDebugInfo && EmbedDebug)
254 "Missing debug info for embedding into the container");
255 if (!HasDebugInfo && !PdbDebugPath.empty())
256 reportFatalUsageError("Missing debug info for writing to the PDB file");
257
258 std::string ILDBData;
259 if (HasDebugInfo) {
260 // Write DXIL with debug info to ILDB part.
261 // Clone the module to avoid alternating it with DebugInfoPass
262 // before stripping the debug info later.
263 ILDBData =
264 writeModule(*llvm::CloneModule(M), HasDebugInfo, /*WriteDebug=*/true);
265 }
266
267 // Clone the module to save dx.source metadata nodes from stripping, as they
268 // are needed for DXILMetadataAnalysisWrapperPass.
269 std::string DXILData =
270 writeModule(*llvm::CloneModule(M), HasDebugInfo, /*WriteDebug=*/false);
271
272 // We no longer need lifetime intrinsics after bitcode serialization, so we
273 // simply remove them to keep the Module Verifier happy after our
274 // not-so-legal legalizations
275 removeLifetimeIntrinsics(M);
276
278 if (HasDebugInfo) {
279 // Create a GV after both parts are written, otherwise it gets
280 // added to DXIL when `writeModule` is called the second time.
281 Globals.emplace_back(createSectionGlobal(M, ILDBData, "dx.ildb", "ILDB"));
282 }
283 Globals.emplace_back(createSectionGlobal(M, DXILData, "dx.dxil", "DXIL"));
284 appendToCompilerUsed(M, Globals);
285 return true;
286 }
287
288 void getAnalysisUsage(AnalysisUsage &AU) const override {
289 AU.setPreservesAll();
290 }
291};
292} // namespace
293
294char WriteDXILPass::ID = 0;
295INITIALIZE_PASS_BEGIN(WriteDXILPass, "dxil-write-bitcode", "Write Bitcode",
296 false, true)
298INITIALIZE_PASS_END(WriteDXILPass, "dxil-write-bitcode", "Write Bitcode", false,
299 true)
300
302 return new WriteDXILPass(Str);
303}
304
305char EmbedDXILPass::ID = 0;
306INITIALIZE_PASS(EmbedDXILPass, "dxil-embed", "Embed DXIL", false, true)
307
308ModulePass *llvm::createDXILEmbedderPass() { return new EmbedDXILPass(); }
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
@ ParamAttr
This file contains the declarations for the subclasses of Constant, which represent the different fla...
cl::opt< bool > SourceInDebugModule("dx-source-in-debug-module", cl::desc("Embed source code into debug module on DirectX target"), cl::init(false))
cl::opt< bool > StripDebug
cl::opt< bool > SlimDebug
cl::opt< bool > EmbedDebug
cl::opt< std::string > PdbDebugPath("dx-pdb-path", cl::desc("Write debug information to the given file, or automatically " "named file in directory when ending in '/'"), cl::value_desc("filename"))
This file provides a bitcode writing pass.
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
cl::opt< bool > EmbedDebug("dx-embed-debug", cl::desc("Embed PDB in shader container"))
cl::opt< bool > StripDebug("dx-strip-debug", cl::desc("Strip debug information from shader bytecode"))
cl::opt< bool > SlimDebug("dx-slim-debug", cl::desc("Generate slim PDB without ILDB part"))
#define F(x, y, z)
Definition MD5.cpp:54
This is the interface to build a ModuleSummaryIndex for a module.
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file contains some templates that are useful if you are working with the STL at all.
an instruction to allocate memory on the stack
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
void setPreservesAll()
Set by analyses that do not transform their input at all.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
This class represents a no-op cast from one type to another.
AttributeSet getParamAttributes(unsigned ArgNo) const
Return the param attributes for this call.
Value * getArgOperand(unsigned i) const
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition Constants.h:878
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:348
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:615
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1513
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:255
Legacy wrapper pass to provide the ModuleSummaryIndex object.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
A tuple of MDNodes.
Definition Metadata.h:1755
LLVM_ABI StringRef getName() const
LLVM_ABI void eraseFromParent()
Drop all references and remove the node from parent module.
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:911
reference emplace_back(ArgTypes &&... Args)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:282
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ Entry
Definition COFF.h:862
LLVM_ABI StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
LLVM_ABI StringRef getBaseName(ID id)
Return the LLVM name for an intrinsic, without encoded types for overloading, such as "llvm....
initializer< Ty > init(const Ty &Val)
void WriteDXILToFile(Module &M, raw_ostream &Out)
Write the specified module to the specified raw output stream.
This is an optimization pass for GlobalISel generic memory operations.
ArrayRef< CharT > arrayRefFromStringRef(StringRef Input)
Construct an array ref of bytes from a string ref.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
ModulePass * createDXILWriterPass(raw_ostream &Str)
Create and return a pass that writes the module to the specified ostream.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
LLVM_ABI size_t writeModule(const Module &M, uint8_t *Dest, size_t MaxSize)
Fuzzer friendly interface for the llvm bitcode printer.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
void initializeEmbedDXILPassPass(PassRegistry &)
Initializer for dxil embedder pass.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
ModulePass * createDXILEmbedderPass()
Create and return a pass that writes the module to a global variable in the module for later emission...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void initializeWriteDXILPassPass(PassRegistry &)
Initializer for dxil writer pass.
LLVM_ABI std::unique_ptr< Module > CloneModule(const Module &M)
Return an exact copy of the specified module.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177