LLVM 23.0.0git
NVPTXGenericToNVVM.cpp
Go to the documentation of this file.
1//===-- GenericToNVVM.cpp - Convert generic module to NVVM module - C++ -*-===//
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// Convert generic global variables into either .global or .const access based
10// on the variable's "constant" qualifier.
11//
12//===----------------------------------------------------------------------===//
13
15#include "NVPTX.h"
16#include "NVVMProperties.h"
18#include "llvm/IR/Constants.h"
20#include "llvm/IR/IRBuilder.h"
22#include "llvm/IR/Intrinsics.h"
24#include "llvm/IR/Module.h"
25#include "llvm/IR/Operator.h"
26#include "llvm/IR/ValueMap.h"
28
29using namespace llvm;
30
31namespace {
32class GenericToNVVM {
33public:
34 bool runOnModule(Module &M);
35
36private:
37 Value *remapConstant(Module *M, Function *F, Constant *C,
38 IRBuilder<> &Builder);
39 Value *remapConstantVectorOrConstantAggregate(Module *M, Function *F,
40 Constant *C,
41 IRBuilder<> &Builder);
42 Value *remapConstantExpr(Module *M, Function *F, ConstantExpr *C,
43 IRBuilder<> &Builder);
44
45 typedef ValueMap<GlobalVariable *, GlobalVariable *> GVMapTy;
46 typedef ValueMap<Constant *, Value *> ConstantToValueMapTy;
47 GVMapTy GVMap;
48 ConstantToValueMapTy ConstantToValueMap;
49};
50} // end namespace
51
52bool GenericToNVVM::runOnModule(Module &M) {
53 // Create a clone of each global variable that has the default address space.
54 // The clone is created with the global address space specifier, and the pair
55 // of original global variable and its clone is placed in the GVMap for later
56 // use.
57
58 for (GlobalVariable &GV : llvm::make_early_inc_range(M.globals())) {
59 if (GV.getType()->getAddressSpace() == llvm::ADDRESS_SPACE_GENERIC &&
61 !GV.getName().starts_with("llvm.")) {
62 GlobalVariable *NewGV = new GlobalVariable(
63 M, GV.getValueType(), GV.isConstant(), GV.getLinkage(),
64 GV.hasInitializer() ? GV.getInitializer() : nullptr, "", &GV,
65 GV.getThreadLocalMode(), llvm::ADDRESS_SPACE_GLOBAL);
66 NewGV->copyAttributesFrom(&GV);
67 NewGV->copyMetadata(&GV, /*Offset=*/0);
68 GVMap[&GV] = NewGV;
69 }
70 }
71
72 // Return immediately, if every global variable has a specific address space
73 // specifier.
74 if (GVMap.empty()) {
75 return false;
76 }
77
78 // Walk through the instructions in function defitinions, and replace any use
79 // of original global variables in GVMap with a use of the corresponding
80 // copies in GVMap. If necessary, promote constants to instructions.
81 for (Function &F : M) {
82 if (F.isDeclaration()) {
83 continue;
84 }
85 IRBuilder<> Builder(&*F.getEntryBlock().getFirstNonPHIOrDbg());
86 for (BasicBlock &BB : F) {
87 for (Instruction &II : BB) {
88 for (unsigned i = 0, e = II.getNumOperands(); i < e; ++i) {
89 Value *Operand = II.getOperand(i);
90 if (isa<Constant>(Operand)) {
91 II.setOperand(
92 i, remapConstant(&M, &F, cast<Constant>(Operand), Builder));
93 }
94 }
95 }
96 }
97 ConstantToValueMap.clear();
98 }
99
100 // Copy GVMap over to a standard value map.
102 for (auto I = GVMap.begin(), E = GVMap.end(); I != E; ++I)
103 VM[I->first] = I->second;
104
105 // Walk through the global variable initializers, and replace any use of
106 // original global variables in GVMap with a use of the corresponding copies
107 // in GVMap. The copies need to be bitcast to the original global variable
108 // types, as we cannot use cvta in global variable initializers.
109 // Snapshot the map first: replaceAllUsesWith() and eraseFromParent() below
110 // fire ValueMap callbacks that mutate GVMap, so we must not hold an iterator
111 // into GVMap across them.
113 GVMap.begin(), GVMap.end());
114 for (auto [GV, NewGV] : GVs) {
115 // Remove GV from the map so that it can be RAUWed.
116 GVMap.erase(GV);
117
118 Constant *BitCastNewGV = ConstantExpr::getPointerCast(NewGV, GV->getType());
119 // At this point, the remaining uses of GV should be found only in global
120 // variable initializers, as other uses have been already been removed
121 // while walking through the instructions in function definitions.
122 GV->replaceAllUsesWith(BitCastNewGV);
123 std::string Name = std::string(GV->getName());
124 GV->eraseFromParent();
125 NewGV->setName(Name);
126 }
127 assert(GVMap.empty() && "Expected it to be empty by now");
128
129 return true;
130}
131
132Value *GenericToNVVM::remapConstant(Module *M, Function *F, Constant *C,
133 IRBuilder<> &Builder) {
134 // If the constant C has been converted already in the given function F, just
135 // return the converted value.
136 ConstantToValueMapTy::iterator CTII = ConstantToValueMap.find(C);
137 if (CTII != ConstantToValueMap.end()) {
138 return CTII->second;
139 }
140
141 Value *NewValue = C;
142 if (isa<GlobalVariable>(C)) {
143 // If the constant C is a global variable and is found in GVMap, substitute
144 //
145 // addrspacecast GVMap[C] to addrspace(0)
146 //
147 // for our use of C.
148 GVMapTy::iterator I = GVMap.find(cast<GlobalVariable>(C));
149 if (I != GVMap.end()) {
150 GlobalVariable *GV = I->second;
151 NewValue = Builder.CreateAddrSpaceCast(
152 GV, PointerType::get(GV->getContext(), llvm::ADDRESS_SPACE_GENERIC));
153 }
154 } else if (isa<ConstantAggregate>(C)) {
155 // If any element in the constant vector or aggregate C is or uses a global
156 // variable in GVMap, the constant C needs to be reconstructed, using a set
157 // of instructions.
158 NewValue = remapConstantVectorOrConstantAggregate(M, F, C, Builder);
159 } else if (isa<ConstantExpr>(C)) {
160 // If any operand in the constant expression C is or uses a global variable
161 // in GVMap, the constant expression C needs to be reconstructed, using a
162 // set of instructions.
163 NewValue = remapConstantExpr(M, F, cast<ConstantExpr>(C), Builder);
164 }
165
166 ConstantToValueMap[C] = NewValue;
167 return NewValue;
168}
169
170Value *GenericToNVVM::remapConstantVectorOrConstantAggregate(
171 Module *M, Function *F, Constant *C, IRBuilder<> &Builder) {
172 bool OperandChanged = false;
173 SmallVector<Value *, 4> NewOperands;
174 unsigned NumOperands = C->getNumOperands();
175
176 // Check if any element is or uses a global variable in GVMap, and thus
177 // converted to another value.
178 for (unsigned i = 0; i < NumOperands; ++i) {
179 Value *Operand = C->getOperand(i);
180 Value *NewOperand = remapConstant(M, F, cast<Constant>(Operand), Builder);
181 OperandChanged |= Operand != NewOperand;
182 NewOperands.push_back(NewOperand);
183 }
184
185 // If none of the elements has been modified, return C as it is.
186 if (!OperandChanged) {
187 return C;
188 }
189
190 // If any of the elements has been modified, construct the equivalent
191 // vector or aggregate value with a set instructions and the converted
192 // elements.
193 Value *NewValue = PoisonValue::get(C->getType());
194 if (isa<ConstantVector>(C)) {
195 for (unsigned i = 0; i < NumOperands; ++i) {
196 Value *Idx = ConstantInt::get(Type::getInt32Ty(M->getContext()), i);
197 NewValue = Builder.CreateInsertElement(NewValue, NewOperands[i], Idx);
198 }
199 } else {
200 for (unsigned i = 0; i < NumOperands; ++i) {
201 NewValue =
202 Builder.CreateInsertValue(NewValue, NewOperands[i], ArrayRef(i));
203 }
204 }
205
206 return NewValue;
207}
208
209Value *GenericToNVVM::remapConstantExpr(Module *M, Function *F, ConstantExpr *C,
210 IRBuilder<> &Builder) {
211 bool OperandChanged = false;
212 SmallVector<Value *, 4> NewOperands;
213 unsigned NumOperands = C->getNumOperands();
214
215 // Check if any operand is or uses a global variable in GVMap, and thus
216 // converted to another value.
217 for (unsigned i = 0; i < NumOperands; ++i) {
218 Value *Operand = C->getOperand(i);
219 Value *NewOperand = remapConstant(M, F, cast<Constant>(Operand), Builder);
220 OperandChanged |= Operand != NewOperand;
221 NewOperands.push_back(NewOperand);
222 }
223
224 // If none of the operands has been modified, return C as it is.
225 if (!OperandChanged) {
226 return C;
227 }
228
229 // If any of the operands has been modified, construct the instruction with
230 // the converted operands.
231 unsigned Opcode = C->getOpcode();
232 switch (Opcode) {
233 case Instruction::ExtractElement:
234 // ExtractElementConstantExpr
235 return Builder.CreateExtractElement(NewOperands[0], NewOperands[1]);
236 case Instruction::InsertElement:
237 // InsertElementConstantExpr
238 return Builder.CreateInsertElement(NewOperands[0], NewOperands[1],
239 NewOperands[2]);
240 case Instruction::ShuffleVector:
241 // ShuffleVector
242 return Builder.CreateShuffleVector(NewOperands[0], NewOperands[1],
243 NewOperands[2]);
244 case Instruction::GetElementPtr:
245 // GetElementPtrConstantExpr
246 return Builder.CreateGEP(cast<GEPOperator>(C)->getSourceElementType(),
247 NewOperands[0],
248 ArrayRef(&NewOperands[1], NumOperands - 1), "",
249 cast<GEPOperator>(C)->isInBounds());
250 case Instruction::Select:
251 // SelectConstantExpr
252 return Builder.CreateSelect(NewOperands[0], NewOperands[1], NewOperands[2]);
253 default:
254 // BinaryConstantExpr
255 if (Instruction::isBinaryOp(Opcode)) {
256 return Builder.CreateBinOp(Instruction::BinaryOps(C->getOpcode()),
257 NewOperands[0], NewOperands[1]);
258 }
259 // UnaryConstantExpr
260 if (Instruction::isCast(Opcode)) {
261 return Builder.CreateCast(Instruction::CastOps(C->getOpcode()),
262 NewOperands[0], C->getType());
263 }
264 llvm_unreachable("GenericToNVVM encountered an unsupported ConstantExpr");
265 }
266}
267
268namespace {
269class GenericToNVVMLegacyPass : public ModulePass {
270public:
271 static char ID;
272
273 GenericToNVVMLegacyPass() : ModulePass(ID) {}
274
275 bool runOnModule(Module &M) override;
276};
277} // namespace
278
279char GenericToNVVMLegacyPass::ID = 0;
280
282 return new GenericToNVVMLegacyPass();
283}
284
286 GenericToNVVMLegacyPass, "generic-to-nvvm",
287 "Ensure that the global variables are in the global address space", false,
288 false)
289
290bool GenericToNVVMLegacyPass::runOnModule(Module &M) {
291 return GenericToNVVM().runOnModule(M);
292}
293
295 return GenericToNVVM().runOnModule(M) ? PreservedAnalyses::none()
297}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static LLVM_ABI Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
LLVM_ABI void copyMetadata(const GlobalObject *Src, unsigned Offset)
Copy metadata from Src, adjusting offsets by Offset.
LLVM_ABI void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
Definition Globals.cpp:576
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2627
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2681
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2615
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr, FMFSource FMFSource={})
Definition IRBuilder.h:2276
Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2010
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Definition IRBuilder.h:2649
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1753
Value * CreateAddrSpaceCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2247
bool isCast() const
bool isBinaryOp() const
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:255
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
void push_back(const T &Elt)
bool empty() const
Definition ValueMap.h:143
iterator find(const KeyT &Val)
Definition ValueMap.h:160
iterator begin()
Definition ValueMap.h:138
iterator end()
Definition ValueMap.h:139
bool erase(const KeyT &Val)
Definition ValueMap.h:192
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:393
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
ModulePass * createGenericToNVVMLegacyPass()
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
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
ArrayRef(const T &OneElt) -> ArrayRef< T >
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
PTXOpaqueType getPTXOpaqueType(const GlobalVariable &GV)
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)