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 "DirectX.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/StringRef.h"
20#include "llvm/IR/Analysis.h"
21#include "llvm/IR/Constants.h"
22#include "llvm/IR/DebugInfo.h"
26#include "llvm/IR/Intrinsics.h"
27#include "llvm/IR/LLVMContext.h"
28#include "llvm/IR/Module.h"
29#include "llvm/IR/PassManager.h"
31#include "llvm/Pass.h"
35
36using namespace llvm;
37using namespace llvm::dxil;
38
39namespace {
40class DXILWriterLegacy : public llvm::ModulePass {
41 raw_ostream &OS; // raw_ostream to print on
42
43public:
44 static char ID; // Pass identification, replacement for typeid
45 DXILWriterLegacy() : ModulePass(ID), OS(dbgs()) {
47 }
48
49 explicit DXILWriterLegacy(raw_ostream &o) : ModulePass(ID), OS(o) {
51 }
52
53 StringRef getPassName() const override { return "Bitcode Writer"; }
54
55 bool runOnModule(Module &M) override {
56 WriteDXILToFile(M, OS);
57 return false;
58 }
59 void getAnalysisUsage(AnalysisUsage &AU) const override {
60 AU.setPreservesAll();
61 }
62};
63
64static void legalizeLifetimeIntrinsics(Module &M) {
65 LLVMContext &Ctx = M.getContext();
66 Type *I64Ty = IntegerType::get(Ctx, 64);
67 Type *PtrTy = PointerType::get(Ctx, 0);
68 Intrinsic::ID LifetimeIIDs[2] = {Intrinsic::lifetime_start,
69 Intrinsic::lifetime_end};
70 for (Intrinsic::ID &IID : LifetimeIIDs) {
71 Function *F = M.getFunction(Intrinsic::getName(IID, {PtrTy}, &M));
72 if (!F)
73 continue;
74
75 // Get or insert an LLVM 3.7-compliant lifetime intrinsic function of the
76 // form `void @llvm.lifetime.[start/end](i64, ptr)` with the NoUnwind
77 // attribute
78 AttributeList Attr;
79 Attr = Attr.addFnAttribute(Ctx, Attribute::NoUnwind);
80 FunctionCallee LifetimeCallee = M.getOrInsertFunction(
81 Intrinsic::getBaseName(IID), Attr, Type::getVoidTy(Ctx), I64Ty, PtrTy);
82
83 // Replace all calls to lifetime intrinsics with calls to the
84 // LLVM 3.7-compliant version of the lifetime intrinsic
85 for (User *U : make_early_inc_range(F->users())) {
87 assert(CI &&
88 "Expected user of a lifetime intrinsic function to be a CallInst");
89
90 // LLVM 3.7 lifetime intrinics require an i8* operand, so we insert
91 // a bitcast to ensure that is the case
92 Value *PtrOperand = CI->getArgOperand(0);
93 PointerType *PtrOpPtrTy = cast<PointerType>(PtrOperand->getType());
94 Value *NoOpBitCast = CastInst::Create(Instruction::BitCast, PtrOperand,
95 PtrOpPtrTy, "", CI->getIterator());
96
97 // LLVM 3.7 lifetime intrinsics have an explicit size operand, whose value
98 // we can obtain from the pointer operand which must be an AllocaInst (as
99 // of https://github.com/llvm/llvm-project/pull/149310)
100 AllocaInst *AI = dyn_cast<AllocaInst>(PtrOperand);
101 assert(AI &&
102 "The pointer operand of a lifetime intrinsic call must be an "
103 "AllocaInst");
104 std::optional<TypeSize> AllocSize =
106 assert(AllocSize.has_value() &&
107 "Expected the allocation size of AllocaInst to be known");
108 CallInst *NewCI = CallInst::Create(
109 LifetimeCallee,
110 {ConstantInt::get(I64Ty, AllocSize.value().getFixedValue()),
111 NoOpBitCast},
112 "", CI->getIterator());
114 NewCI->addParamAttr(1, ParamAttr);
115
116 CI->eraseFromParent();
117 }
118
119 F->eraseFromParent();
120 }
121}
122
123static void removeLifetimeIntrinsics(Module &M) {
124 Intrinsic::ID LifetimeIIDs[2] = {Intrinsic::lifetime_start,
125 Intrinsic::lifetime_end};
126 for (Intrinsic::ID &IID : LifetimeIIDs) {
127 Function *F = M.getFunction(Intrinsic::getBaseName(IID));
128 if (!F)
129 continue;
130
131 for (User *U : make_early_inc_range(F->users())) {
133 assert(CI && "Expected user of lifetime function to be a CallInst");
135 assert(BCI && "Expected pointer operand of CallInst to be a BitCastInst");
136 CI->eraseFromParent();
137 BCI->eraseFromParent();
138 }
139 F->eraseFromParent();
140 }
141}
142
143static void replaceNamedMetadataArray(Module &M, StringRef Name,
144 ArrayRef<Metadata *> NewOps) {
145 NamedMDNode *NMD = M.getNamedMetadata(Name);
146 if (!NMD)
147 return;
148 NMD->eraseFromParent();
149 M.getOrInsertNamedMetadata(Name)->addOperand(
150 MDTuple::get(M.getContext(), NewOps));
151}
152
153class DXILEmbedderLegacy : public llvm::ModulePass {
154public:
155 static char ID; // Pass identification, replacement for typeid
156 DXILEmbedderLegacy() : ModulePass(ID) {
158 }
159
160 StringRef getPassName() const override { return "DXIL Embedder"; }
161
162 bool runOnModule(Module &M) override;
163
164 void getAnalysisUsage(AnalysisUsage &AU) const override {
165 AU.setPreservesAll();
166 }
167};
168} // namespace
169
170static std::string writeModule(const DirectXMCOptions &Opts, Module &M,
171 bool HasDebugInfo, bool WriteDebug) {
172 std::string Data;
174
175 if (HasDebugInfo) {
176 if (WriteDebug) {
177 if (!Opts.source_in_debug_module) {
178 // Replace dx.source metadata nodes with stubs.
179 LLVMContext &Ctx = M.getContext();
180 MDString *EmptyString = MDString::get(Ctx, "");
181 replaceNamedMetadataArray(M, "dx.source.contents",
182 {EmptyString, EmptyString});
183 replaceNamedMetadataArray(M, "dx.source.defines", {});
184 replaceNamedMetadataArray(M, "dx.source.mainFileName", {EmptyString});
185 replaceNamedMetadataArray(M, "dx.source.args", {});
186 }
187 } else {
188 // If we have an ILDB part, strip DXIL from all debug info.
190
191 // Also, manually remove debug version flags and dx.source nodes.
192 if (NamedMDNode *Flags = M.getModuleFlagsMetadata()) {
194 M.getModuleFlagsMetadata(FlagEntries);
195 Flags->eraseFromParent();
196 for (llvm::Module::ModuleFlagEntry &Entry : FlagEntries) {
197 if (Entry.Key->getString() == "Dwarf Version" ||
198 Entry.Key->getString() == "Debug Info Version") {
199 continue;
200 }
201 M.addModuleFlag(Entry.Behavior, Entry.Key->getString(), Entry.Val);
202 }
203 }
204 for (NamedMDNode &NMD : llvm::make_early_inc_range(M.named_metadata()))
205 if (NMD.getName().starts_with("dx.source"))
206 NMD.eraseFromParent();
207 }
208 } else {
209#ifdef EXPENSIVE_CHECKS
210 assert(StripDebugInfo(M) == false &&
211 "The module must not contain any debug info here."
212 "Shader modules with debug info must have !DICompileUnit metadata.");
213#endif
214 }
215 WriteDXILToFile(M, OS);
216 return Data;
217}
218
220 StringRef GlobalName,
222 Constant *ModuleConstant =
224 auto *GV = new llvm::GlobalVariable(M, ModuleConstant->getType(), true,
226 ModuleConstant, GlobalName);
227 GV->setSection(SectionName);
228 GV->setAlignment(Align(4));
229 return GV;
230}
231
233 // Perform late legalization of lifetime intrinsics that would otherwise
234 // fail the Module Verifier if performed in an earlier pass
235 legalizeLifetimeIntrinsics(M);
236
237 bool HasDebugInfo = !M.debug_compile_units().empty();
238
239 const auto &Opts = M.getContext().getLibraryOptions().get<DirectXMCOptions>();
240 if (Opts.slim_debug && Opts.embed_debug)
241 reportFatalUsageError("/Qembed_debug is not compatible with /Zs");
242 if (!HasDebugInfo && Opts.embed_debug)
244 "Missing debug info for embedding into the container");
245 if (!HasDebugInfo && !Opts.pdb_path.empty())
246 reportFatalUsageError("Missing debug info for writing to the PDB file");
247
248 std::string ILDBData;
249 if (HasDebugInfo) {
250 // Write DXIL with debug info to ILDB part.
251 // Clone the module to avoid alternating it with DebugInfoPass
252 // before stripping the debug info later.
253 ILDBData = writeModule(Opts, *llvm::CloneModule(M), HasDebugInfo,
254 /*WriteDebug=*/true);
255 }
256
257 // Clone the module to save dx.source metadata nodes from stripping, as they
258 // are needed for DXILMetadataAnalysisWrapperPass.
259 std::string DXILData = writeModule(Opts, *llvm::CloneModule(M), HasDebugInfo,
260 /*WriteDebug=*/false);
261
262 // We no longer need lifetime intrinsics after bitcode serialization, so we
263 // simply remove them to keep the Module Verifier happy after our
264 // not-so-legal legalizations
265 removeLifetimeIntrinsics(M);
266
268 if (HasDebugInfo) {
269 // Create a GV after both parts are written, otherwise it gets
270 // added to DXIL when `writeModule` is called the second time.
271 Globals.emplace_back(createSectionGlobal(M, ILDBData, "dx.ildb", "ILDB"));
272 }
273 Globals.emplace_back(createSectionGlobal(M, DXILData, "dx.dxil", "DXIL"));
274 appendToCompilerUsed(M, Globals);
275 return true;
276}
277
278bool DXILEmbedderLegacy::runOnModule(Module &M) {
279 return runEmbedderOnModule(M);
280}
281
286
287char DXILWriterLegacy::ID = 0;
288INITIALIZE_PASS_BEGIN(DXILWriterLegacy, "dxil-writer", "Write Bitcode", false,
289 true)
291INITIALIZE_PASS_END(DXILWriterLegacy, "dxil-writer", "Write Bitcode", false,
292 true)
293
295 return new DXILWriterLegacy(Str);
296}
297
298char DXILEmbedderLegacy::ID = 0;
299INITIALIZE_PASS(DXILEmbedderLegacy, "dxil-embedder", "Embed DXIL", false, true)
300
302 return new DXILEmbedderLegacy();
303}
304
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...
static bool runEmbedderOnModule(Module &M)
static GlobalVariable * createSectionGlobal(Module &M, StringRef Data, StringRef GlobalName, StringRef SectionName)
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.
ModuleAnalysisManager MAM
#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:107
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
This is an important base class in LLVM.
Definition Constant.h:44
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
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:333
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
A single uniqued string.
Definition Metadata.h:734
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:595
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1534
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:253
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:1806
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:882
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
reference emplace_back(ArgTypes &&... Args)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
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:267
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
A raw_ostream that writes to an std::string.
Pass manager infrastructure for declaring and invalidating analyses.
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....
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
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
ModulePass * createDXILWriterLegacyPass(raw_ostream &Str)
void initializeDXILWriterLegacyPass(PassRegistry &)
Initializer for dxil writer pass.
ModulePass * createDXILEmbedderLegacyPass()
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
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.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI std::unique_ptr< Module > CloneModule(const Module &M)
Return an exact copy of the specified module.
void initializeDXILEmbedderLegacyPass(PassRegistry &)
Initializer for dxil embedder pass.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
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