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"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/StringRef.h"
19#include "llvm/IR/Constants.h"
20#include "llvm/IR/DebugInfo.h"
24#include "llvm/IR/Intrinsics.h"
25#include "llvm/IR/LLVMContext.h"
26#include "llvm/IR/Module.h"
27#include "llvm/IR/PassManager.h"
29#include "llvm/Pass.h"
34
35using namespace llvm;
36using namespace llvm::dxil;
37
39 "dx-source-in-debug-module",
40 cl::desc("Embed source code into debug module on DirectX target"),
41 cl::init(false));
42
43namespace {
44class WriteDXILPass : public llvm::ModulePass {
45 raw_ostream &OS; // raw_ostream to print on
46
47public:
48 static char ID; // Pass identification, replacement for typeid
49 WriteDXILPass() : ModulePass(ID), OS(dbgs()) {
51 }
52
53 explicit WriteDXILPass(raw_ostream &o) : ModulePass(ID), OS(o) {
55 }
56
57 StringRef getPassName() const override { return "Bitcode Writer"; }
58
59 bool runOnModule(Module &M) override {
60 WriteDXILToFile(M, OS);
61 return false;
62 }
63 void getAnalysisUsage(AnalysisUsage &AU) const override {
64 AU.setPreservesAll();
65 }
66};
67
68static void legalizeLifetimeIntrinsics(Module &M) {
69 LLVMContext &Ctx = M.getContext();
70 Type *I64Ty = IntegerType::get(Ctx, 64);
71 Type *PtrTy = PointerType::get(Ctx, 0);
72 Intrinsic::ID LifetimeIIDs[2] = {Intrinsic::lifetime_start,
73 Intrinsic::lifetime_end};
74 for (Intrinsic::ID &IID : LifetimeIIDs) {
75 Function *F = M.getFunction(Intrinsic::getName(IID, {PtrTy}, &M));
76 if (!F)
77 continue;
78
79 // Get or insert an LLVM 3.7-compliant lifetime intrinsic function of the
80 // form `void @llvm.lifetime.[start/end](i64, ptr)` with the NoUnwind
81 // attribute
82 AttributeList Attr;
83 Attr = Attr.addFnAttribute(Ctx, Attribute::NoUnwind);
84 FunctionCallee LifetimeCallee = M.getOrInsertFunction(
85 Intrinsic::getBaseName(IID), Attr, Type::getVoidTy(Ctx), I64Ty, PtrTy);
86
87 // Replace all calls to lifetime intrinsics with calls to the
88 // LLVM 3.7-compliant version of the lifetime intrinsic
89 for (User *U : make_early_inc_range(F->users())) {
91 assert(CI &&
92 "Expected user of a lifetime intrinsic function to be a CallInst");
93
94 // LLVM 3.7 lifetime intrinics require an i8* operand, so we insert
95 // a bitcast to ensure that is the case
96 Value *PtrOperand = CI->getArgOperand(0);
97 PointerType *PtrOpPtrTy = cast<PointerType>(PtrOperand->getType());
98 Value *NoOpBitCast = CastInst::Create(Instruction::BitCast, PtrOperand,
99 PtrOpPtrTy, "", CI->getIterator());
100
101 // LLVM 3.7 lifetime intrinsics have an explicit size operand, whose value
102 // we can obtain from the pointer operand which must be an AllocaInst (as
103 // of https://github.com/llvm/llvm-project/pull/149310)
104 AllocaInst *AI = dyn_cast<AllocaInst>(PtrOperand);
105 assert(AI &&
106 "The pointer operand of a lifetime intrinsic call must be an "
107 "AllocaInst");
108 std::optional<TypeSize> AllocSize =
110 assert(AllocSize.has_value() &&
111 "Expected the allocation size of AllocaInst to be known");
112 CallInst *NewCI = CallInst::Create(
113 LifetimeCallee,
114 {ConstantInt::get(I64Ty, AllocSize.value().getFixedValue()),
115 NoOpBitCast},
116 "", CI->getIterator());
118 NewCI->addParamAttr(1, ParamAttr);
119
120 CI->eraseFromParent();
121 }
122
123 F->eraseFromParent();
124 }
125}
126
127static void removeLifetimeIntrinsics(Module &M) {
128 Intrinsic::ID LifetimeIIDs[2] = {Intrinsic::lifetime_start,
129 Intrinsic::lifetime_end};
130 for (Intrinsic::ID &IID : LifetimeIIDs) {
131 Function *F = M.getFunction(Intrinsic::getBaseName(IID));
132 if (!F)
133 continue;
134
135 for (User *U : make_early_inc_range(F->users())) {
137 assert(CI && "Expected user of lifetime function to be a CallInst");
139 assert(BCI && "Expected pointer operand of CallInst to be a BitCastInst");
140 CI->eraseFromParent();
141 BCI->eraseFromParent();
142 }
143 F->eraseFromParent();
144 }
145}
146
147static void replaceNamedMetadataArray(Module &M, StringRef Name,
148 ArrayRef<Metadata *> NewOps) {
149 NamedMDNode *NMD = M.getNamedMetadata(Name);
150 if (!NMD)
151 return;
152 NMD->eraseFromParent();
153 M.getOrInsertNamedMetadata(Name)->addOperand(
154 MDTuple::get(M.getContext(), NewOps));
155}
156
157class EmbedDXILPass : public llvm::ModulePass {
158 std::string writeModule(Module &M, bool HasDebugInfo, bool WriteDebug) {
159 std::string Data;
160 llvm::raw_string_ostream OS(Data);
161
162 if (HasDebugInfo) {
163 if (WriteDebug) {
164 if (!SourceInDebugModule) {
165 // Replace dx.source metadata nodes with stubs.
166 LLVMContext &Ctx = M.getContext();
167 MDString *EmptyString = MDString::get(Ctx, "");
168 replaceNamedMetadataArray(M, "dx.source.contents",
169 {EmptyString, EmptyString});
170 replaceNamedMetadataArray(M, "dx.source.defines", {});
171 replaceNamedMetadataArray(M, "dx.source.mainFileName", {EmptyString});
172 replaceNamedMetadataArray(M, "dx.source.args", {});
173 }
174 } else {
175 // If we have an ILDB part, strip DXIL from all debug info.
177
178 // Also, manually remove debug version flags and dx.source nodes.
179 if (NamedMDNode *Flags = M.getModuleFlagsMetadata()) {
181 M.getModuleFlagsMetadata(FlagEntries);
182 Flags->eraseFromParent();
183 for (llvm::Module::ModuleFlagEntry &Entry : FlagEntries) {
184 if (Entry.Key->getString() == "Dwarf Version" ||
185 Entry.Key->getString() == "Debug Info Version") {
186 continue;
187 }
188 M.addModuleFlag(Entry.Behavior, Entry.Key->getString(), Entry.Val);
189 }
190 }
191 for (NamedMDNode &NMD : llvm::make_early_inc_range(M.named_metadata()))
192 if (NMD.getName().starts_with("dx.source"))
193 NMD.eraseFromParent();
194 }
195 } else {
196#ifdef EXPENSIVE_CHECKS
197 assert(
198 StripDebugInfo(M) == false &&
199 "The module must not contain any debug info here."
200 "Shader modules with debug info must have !DICompileUnit metadata.");
201#endif
202 }
203 WriteDXILToFile(M, OS);
204 return Data;
205 }
206
207 GlobalVariable *createSectionGlobal(Module &M, StringRef Data,
208 StringRef GlobalName,
209 StringRef SectionName) {
210 Constant *ModuleConstant =
212 auto *GV = new llvm::GlobalVariable(M, ModuleConstant->getType(), true,
214 ModuleConstant, GlobalName);
215 GV->setSection(SectionName);
216 GV->setAlignment(Align(4));
217 return GV;
218 }
219
220public:
221 static char ID; // Pass identification, replacement for typeid
222 EmbedDXILPass() : ModulePass(ID) {
224 }
225
226 StringRef getPassName() const override { return "DXIL Embedder"; }
227
228 bool runOnModule(Module &M) override {
229 // Perform late legalization of lifetime intrinsics that would otherwise
230 // fail the Module Verifier if performed in an earlier pass
231 legalizeLifetimeIntrinsics(M);
232
233 bool HasDebugInfo = !M.debug_compile_units().empty();
234
235 if (SlimDebug && EmbedDebug)
236 reportFatalUsageError("/Qembed_debug is not compatible with /Zs");
237 if (!HasDebugInfo && EmbedDebug)
239 "Missing debug info for embedding into the container");
240 if (!HasDebugInfo && !PdbDebugPath.empty())
241 reportFatalUsageError("Missing debug info for writing to the PDB file");
242
243 std::string ILDBData;
244 if (HasDebugInfo) {
245 // Write DXIL with debug info to ILDB part.
246 // Clone the module to avoid alternating it with DebugInfoPass
247 // before stripping the debug info later.
248 ILDBData =
249 writeModule(*llvm::CloneModule(M), HasDebugInfo, /*WriteDebug=*/true);
250 }
251
252 // Clone the module to save dx.source metadata nodes from stripping, as they
253 // are needed for DXILMetadataAnalysisWrapperPass.
254 std::string DXILData =
255 writeModule(*llvm::CloneModule(M), HasDebugInfo, /*WriteDebug=*/false);
256
257 // We no longer need lifetime intrinsics after bitcode serialization, so we
258 // simply remove them to keep the Module Verifier happy after our
259 // not-so-legal legalizations
260 removeLifetimeIntrinsics(M);
261
263 if (HasDebugInfo) {
264 // Create a GV after both parts are written, otherwise it gets
265 // added to DXIL when `writeModule` is called the second time.
266 Globals.emplace_back(createSectionGlobal(M, ILDBData, "dx.ildb", "ILDB"));
267 }
268 Globals.emplace_back(createSectionGlobal(M, DXILData, "dx.dxil", "DXIL"));
269 appendToCompilerUsed(M, Globals);
270 return true;
271 }
272
273 void getAnalysisUsage(AnalysisUsage &AU) const override {
274 AU.setPreservesAll();
275 }
276};
277} // namespace
278
279char WriteDXILPass::ID = 0;
280INITIALIZE_PASS_BEGIN(WriteDXILPass, "dxil-write-bitcode", "Write Bitcode",
281 false, true)
283INITIALIZE_PASS_END(WriteDXILPass, "dxil-write-bitcode", "Write Bitcode", false,
284 true)
285
287 return new WriteDXILPass(Str);
288}
289
290char EmbedDXILPass::ID = 0;
291INITIALIZE_PASS(EmbedDXILPass, "dxil-embed", "Embed DXIL", false, true)
292
293ModulePass *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...
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.
#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:338
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:597
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1525
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:1797
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:887
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:272
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
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)
cl::opt< bool > EmbedDebug
cl::opt< std::string > PdbDebugPath
cl::opt< bool > SlimDebug
cl::opt< bool > SourceInDebugModule
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:649
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