LLVM 19.0.0git
DXILPrepare.cpp
Go to the documentation of this file.
1//===- DXILPrepare.cpp - Prepare LLVM Module for DXIL encoding ------------===//
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/// \file This file contains pases and utilities to convert a modern LLVM
10/// module into a module compatible with the LLVM 3.7-based DirectX Intermediate
11/// Language (DXIL).
12//===----------------------------------------------------------------------===//
13
14#include "DXILMetadata.h"
16#include "DXILShaderFlags.h"
17#include "DirectX.h"
19#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/StringSet.h"
22#include "llvm/CodeGen/Passes.h"
24#include "llvm/IR/IRBuilder.h"
25#include "llvm/IR/Instruction.h"
26#include "llvm/IR/Module.h"
28#include "llvm/Pass.h"
31
32#define DEBUG_TYPE "dxil-prepare"
33
34using namespace llvm;
35using namespace llvm::dxil;
36
37namespace {
38
39constexpr bool isValidForDXIL(Attribute::AttrKind Attr) {
40 return is_contained({Attribute::Alignment,
41 Attribute::AlwaysInline,
42 Attribute::Builtin,
43 Attribute::ByVal,
44 Attribute::InAlloca,
45 Attribute::Cold,
46 Attribute::Convergent,
47 Attribute::InlineHint,
48 Attribute::InReg,
49 Attribute::JumpTable,
50 Attribute::MinSize,
51 Attribute::Naked,
52 Attribute::Nest,
53 Attribute::NoAlias,
54 Attribute::NoBuiltin,
55 Attribute::NoCapture,
56 Attribute::NoDuplicate,
57 Attribute::NoImplicitFloat,
58 Attribute::NoInline,
59 Attribute::NonLazyBind,
60 Attribute::NonNull,
61 Attribute::Dereferenceable,
62 Attribute::DereferenceableOrNull,
63 Attribute::Memory,
64 Attribute::NoRedZone,
65 Attribute::NoReturn,
66 Attribute::NoUnwind,
67 Attribute::OptimizeForSize,
68 Attribute::OptimizeNone,
69 Attribute::ReadNone,
70 Attribute::ReadOnly,
71 Attribute::Returned,
72 Attribute::ReturnsTwice,
73 Attribute::SExt,
74 Attribute::StackAlignment,
75 Attribute::StackProtect,
76 Attribute::StackProtectReq,
77 Attribute::StackProtectStrong,
78 Attribute::SafeStack,
79 Attribute::StructRet,
80 Attribute::SanitizeAddress,
81 Attribute::SanitizeThread,
82 Attribute::SanitizeMemory,
83 Attribute::UWTable,
84 Attribute::ZExt},
85 Attr);
86}
87
88static void collectDeadStringAttrs(AttributeMask &DeadAttrs, AttributeSet &&AS,
89 const StringSet<> &LiveKeys,
90 bool AllowExperimental) {
91 for (auto &Attr : AS) {
92 if (!Attr.isStringAttribute())
93 continue;
94 StringRef Key = Attr.getKindAsString();
95 if (LiveKeys.contains(Key))
96 continue;
97 if (AllowExperimental && Key.starts_with("exp-"))
98 continue;
99 DeadAttrs.addAttribute(Key);
100 }
101}
102
103static void removeStringFunctionAttributes(Function &F,
104 bool AllowExperimental) {
105 AttributeList Attrs = F.getAttributes();
106 const StringSet<> LiveKeys = {"waveops-include-helper-lanes",
107 "fp32-denorm-mode"};
108 // Collect DeadKeys in FnAttrs.
109 AttributeMask DeadAttrs;
110 collectDeadStringAttrs(DeadAttrs, Attrs.getFnAttrs(), LiveKeys,
111 AllowExperimental);
112 collectDeadStringAttrs(DeadAttrs, Attrs.getRetAttrs(), LiveKeys,
113 AllowExperimental);
114
115 F.removeFnAttrs(DeadAttrs);
116 F.removeRetAttrs(DeadAttrs);
117}
118
119class DXILPrepareModule : public ModulePass {
120
121 static Value *maybeGenerateBitcast(IRBuilder<> &Builder,
122 PointerTypeMap &PointerTypes,
123 Instruction &Inst, Value *Operand,
124 Type *Ty) {
125 // Omit bitcasts if the incoming value matches the instruction type.
126 auto It = PointerTypes.find(Operand);
127 if (It != PointerTypes.end())
128 if (cast<TypedPointerType>(It->second)->getElementType() == Ty)
129 return nullptr;
130 // Insert bitcasts where we are removing the instruction.
131 Builder.SetInsertPoint(&Inst);
132 // This code only gets hit in opaque-pointer mode, so the type of the
133 // pointer doesn't matter.
134 PointerType *PtrTy = cast<PointerType>(Operand->getType());
135 return Builder.Insert(
136 CastInst::Create(Instruction::BitCast, Operand,
137 Builder.getPtrTy(PtrTy->getAddressSpace())));
138 }
139
140public:
141 bool runOnModule(Module &M) override {
143 AttributeMask AttrMask;
145 I = Attribute::AttrKind(I + 1)) {
146 if (!isValidForDXIL(I))
147 AttrMask.addAttribute(I);
148 }
149
150 dxil::ValidatorVersionMD ValVerMD(M);
151 VersionTuple ValVer = ValVerMD.getAsVersionTuple();
152 bool SkipValidation = ValVer.getMajor() == 0 && ValVer.getMinor() == 0;
153
154 for (auto &F : M.functions()) {
155 F.removeFnAttrs(AttrMask);
156 F.removeRetAttrs(AttrMask);
157 // Only remove string attributes if we are not skipping validation.
158 // This will reserve the experimental attributes when validation version
159 // is 0.0 for experiment mode.
160 removeStringFunctionAttributes(F, SkipValidation);
161 for (size_t Idx = 0, End = F.arg_size(); Idx < End; ++Idx)
162 F.removeParamAttrs(Idx, AttrMask);
163
164 for (auto &BB : F) {
165 IRBuilder<> Builder(&BB);
166 for (auto &I : make_early_inc_range(BB)) {
167 if (I.getOpcode() == Instruction::FNeg) {
168 Builder.SetInsertPoint(&I);
169 Value *In = I.getOperand(0);
170 Value *Zero = ConstantFP::get(In->getType(), -0.0);
171 I.replaceAllUsesWith(Builder.CreateFSub(Zero, In));
172 I.eraseFromParent();
173 continue;
174 }
175
176 // Emtting NoOp bitcast instructions allows the ValueEnumerator to be
177 // unmodified as it reserves instruction IDs during contruction.
178 if (auto LI = dyn_cast<LoadInst>(&I)) {
179 if (Value *NoOpBitcast = maybeGenerateBitcast(
180 Builder, PointerTypes, I, LI->getPointerOperand(),
181 LI->getType())) {
182 LI->replaceAllUsesWith(
183 Builder.CreateLoad(LI->getType(), NoOpBitcast));
184 LI->eraseFromParent();
185 }
186 continue;
187 }
188 if (auto SI = dyn_cast<StoreInst>(&I)) {
189 if (Value *NoOpBitcast = maybeGenerateBitcast(
190 Builder, PointerTypes, I, SI->getPointerOperand(),
191 SI->getValueOperand()->getType())) {
192
193 SI->replaceAllUsesWith(
194 Builder.CreateStore(SI->getValueOperand(), NoOpBitcast));
195 SI->eraseFromParent();
196 }
197 continue;
198 }
199 if (auto GEP = dyn_cast<GetElementPtrInst>(&I)) {
200 if (Value *NoOpBitcast = maybeGenerateBitcast(
201 Builder, PointerTypes, I, GEP->getPointerOperand(),
202 GEP->getSourceElementType()))
203 GEP->setOperand(0, NoOpBitcast);
204 continue;
205 }
206 if (auto *CB = dyn_cast<CallBase>(&I)) {
207 CB->removeFnAttrs(AttrMask);
208 CB->removeRetAttrs(AttrMask);
209 for (size_t Idx = 0, End = CB->arg_size(); Idx < End; ++Idx)
210 CB->removeParamAttrs(Idx, AttrMask);
211 continue;
212 }
213 }
214 }
215 }
216 return true;
217 }
218
219 DXILPrepareModule() : ModulePass(ID) {}
220 void getAnalysisUsage(AnalysisUsage &AU) const override {
223 }
224 static char ID; // Pass identification.
225};
226char DXILPrepareModule::ID = 0;
227
228} // end anonymous namespace
229
230INITIALIZE_PASS_BEGIN(DXILPrepareModule, DEBUG_TYPE, "DXIL Prepare Module",
231 false, false)
232INITIALIZE_PASS_END(DXILPrepareModule, DEBUG_TYPE, "DXIL Prepare Module", false,
233 false)
234
236 return new DXILPrepareModule();
237}
#define DEBUG_TYPE
Definition: DXILPrepare.cpp:32
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
bool End
Definition: ELF_riscv.cpp:480
Hexagon Common GEP
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
Module.h This file contains the declarations for the Module class.
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:59
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:52
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
StringSet - A set-like wrapper for the StringMap.
Defines the llvm::VersionTuple class, which represents a version in the form major[....
Represent the analysis usage information of a pass.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
AttributeMask & addAttribute(Attribute::AttrKind Val)
Add an attribute to the mask.
Definition: AttributeMask.h:44
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition: Attributes.h:85
@ None
No attributes have been set.
Definition: Attributes.h:87
@ EndAttrKinds
Sentinel value useful for loops.
Definition: Attributes.h:90
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name, BasicBlock::iterator InsertBefore)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
The legacy pass manager's analysis pass to compute DXIL resource information.
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:155
iterator end()
Definition: DenseMap.h:84
Value * CreateFSub(Value *L, Value *R, const Twine &Name="", MDNode *FPMD=nullptr)
Definition: IRBuilder.h:1560
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Definition: IRBuilder.h:145
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition: IRBuilder.h:1790
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:1803
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition: IRBuilder.h:569
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:180
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2666
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:251
virtual bool runOnModule(Module &M)=0
runOnModule - Virtual method overriden by subclasses to process the module being operated on.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:98
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition: StringSet.h:23
bool contains(StringRef key) const
Check if the set contains the given key.
Definition: StringSet.h:55
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:29
unsigned getMajor() const
Retrieve the major version number.
Definition: VersionTuple.h:71
std::optional< unsigned > getMinor() const
Retrieve the minor version number, if provided.
Definition: VersionTuple.h:74
Wrapper pass for the legacy pass manager.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
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:656
ModulePass * createDXILPrepareModulePass()
Pass to convert modules into DXIL-compatable modules.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1879