1 //===-- GenericToNVVM.cpp - Convert generic module to NVVM module - C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Convert generic global variables into either .global or .const access based
11 // on the variable's "constant" qualifier.
13 //===----------------------------------------------------------------------===//
16 #include "MCTargetDesc/NVPTXBaseInfo.h"
17 #include "NVPTXUtilities.h"
18 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
19 #include "llvm/CodeGen/ValueTypes.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/IRBuilder.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/Intrinsics.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/IR/ValueMap.h"
28 #include "llvm/PassManager.h"
33 void initializeGenericToNVVMPass(PassRegistry &);
37 class GenericToNVVM : public ModulePass {
41 GenericToNVVM() : ModulePass(ID) {}
43 virtual bool runOnModule(Module &M);
45 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
49 Value *getOrInsertCVTA(Module *M, Function *F, GlobalVariable *GV,
50 IRBuilder<> &Builder);
51 Value *remapConstant(Module *M, Function *F, Constant *C,
52 IRBuilder<> &Builder);
53 Value *remapConstantVectorOrConstantAggregate(Module *M, Function *F,
55 IRBuilder<> &Builder);
56 Value *remapConstantExpr(Module *M, Function *F, ConstantExpr *C,
57 IRBuilder<> &Builder);
58 void remapNamedMDNode(Module *M, NamedMDNode *N);
59 MDNode *remapMDNode(Module *M, MDNode *N);
61 typedef ValueMap<GlobalVariable *, GlobalVariable *> GVMapTy;
62 typedef ValueMap<Constant *, Value *> ConstantToValueMapTy;
64 ConstantToValueMapTy ConstantToValueMap;
68 char GenericToNVVM::ID = 0;
70 ModulePass *llvm::createGenericToNVVMPass() { return new GenericToNVVM(); }
73 GenericToNVVM, "generic-to-nvvm",
74 "Ensure that the global variables are in the global address space", false,
77 bool GenericToNVVM::runOnModule(Module &M) {
78 // Create a clone of each global variable that has the default address space.
79 // The clone is created with the global address space specifier, and the pair
80 // of original global variable and its clone is placed in the GVMap for later
83 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
85 GlobalVariable *GV = I++;
86 if (GV->getType()->getAddressSpace() == llvm::ADDRESS_SPACE_GENERIC &&
87 !llvm::isTexture(*GV) && !llvm::isSurface(*GV) &&
88 !GV->getName().startswith("llvm.")) {
89 GlobalVariable *NewGV = new GlobalVariable(
90 M, GV->getType()->getElementType(), GV->isConstant(),
92 GV->hasInitializer() ? GV->getInitializer() : nullptr,
93 "", GV, GV->getThreadLocalMode(), llvm::ADDRESS_SPACE_GLOBAL);
94 NewGV->copyAttributesFrom(GV);
99 // Return immediately, if every global variable has a specific address space
105 // Walk through the instructions in function defitinions, and replace any use
106 // of original global variables in GVMap with a use of the corresponding
107 // copies in GVMap. If necessary, promote constants to instructions.
108 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
109 if (I->isDeclaration()) {
112 IRBuilder<> Builder(I->getEntryBlock().getFirstNonPHIOrDbg());
113 for (Function::iterator BBI = I->begin(), BBE = I->end(); BBI != BBE;
115 for (BasicBlock::iterator II = BBI->begin(), IE = BBI->end(); II != IE;
117 for (unsigned i = 0, e = II->getNumOperands(); i < e; ++i) {
118 Value *Operand = II->getOperand(i);
119 if (isa<Constant>(Operand)) {
121 i, remapConstant(&M, I, cast<Constant>(Operand), Builder));
126 ConstantToValueMap.clear();
129 // Walk through the metadata section and update the debug information
130 // associated with the global variables in the default address space.
131 for (Module::named_metadata_iterator I = M.named_metadata_begin(),
132 E = M.named_metadata_end();
134 remapNamedMDNode(&M, I);
137 // Walk through the global variable initializers, and replace any use of
138 // original global variables in GVMap with a use of the corresponding copies
139 // in GVMap. The copies need to be bitcast to the original global variable
140 // types, as we cannot use cvta in global variable initializers.
141 for (GVMapTy::iterator I = GVMap.begin(), E = GVMap.end(); I != E;) {
142 GlobalVariable *GV = I->first;
143 GlobalVariable *NewGV = I->second;
145 Constant *BitCastNewGV = ConstantExpr::getPointerCast(NewGV, GV->getType());
146 // At this point, the remaining uses of GV should be found only in global
147 // variable initializers, as other uses have been already been removed
148 // while walking through the instructions in function definitions.
149 for (Value::use_iterator UI = GV->use_begin(), UE = GV->use_end();
151 (UI++)->set(BitCastNewGV);
152 std::string Name = GV->getName();
153 GV->removeDeadConstantUsers();
154 GV->eraseFromParent();
155 NewGV->setName(Name);
162 Value *GenericToNVVM::getOrInsertCVTA(Module *M, Function *F,
164 IRBuilder<> &Builder) {
165 PointerType *GVType = GV->getType();
166 Value *CVTA = nullptr;
168 // See if the address space conversion requires the operand to be bitcast
169 // to i8 addrspace(n)* first.
170 EVT ExtendedGVType = EVT::getEVT(GVType->getElementType(), true);
171 if (!ExtendedGVType.isInteger() && !ExtendedGVType.isFloatingPoint()) {
172 // A bitcast to i8 addrspace(n)* on the operand is needed.
173 LLVMContext &Context = M->getContext();
174 unsigned int AddrSpace = GVType->getAddressSpace();
175 Type *DestTy = PointerType::get(Type::getInt8Ty(Context), AddrSpace);
176 CVTA = Builder.CreateBitCast(GV, DestTy, "cvta");
177 // Insert the address space conversion.
179 PointerType::get(Type::getInt8Ty(Context), llvm::ADDRESS_SPACE_GENERIC);
180 SmallVector<Type *, 2> ParamTypes;
181 ParamTypes.push_back(ResultType);
182 ParamTypes.push_back(DestTy);
183 Function *CVTAFunction = Intrinsic::getDeclaration(
184 M, Intrinsic::nvvm_ptr_global_to_gen, ParamTypes);
185 CVTA = Builder.CreateCall(CVTAFunction, CVTA, "cvta");
186 // Another bitcast from i8 * to <the element type of GVType> * is
189 PointerType::get(GVType->getElementType(), llvm::ADDRESS_SPACE_GENERIC);
190 CVTA = Builder.CreateBitCast(CVTA, DestTy, "cvta");
192 // A simple CVTA is enough.
193 SmallVector<Type *, 2> ParamTypes;
194 ParamTypes.push_back(PointerType::get(GVType->getElementType(),
195 llvm::ADDRESS_SPACE_GENERIC));
196 ParamTypes.push_back(GVType);
197 Function *CVTAFunction = Intrinsic::getDeclaration(
198 M, Intrinsic::nvvm_ptr_global_to_gen, ParamTypes);
199 CVTA = Builder.CreateCall(CVTAFunction, GV, "cvta");
205 Value *GenericToNVVM::remapConstant(Module *M, Function *F, Constant *C,
206 IRBuilder<> &Builder) {
207 // If the constant C has been converted already in the given function F, just
208 // return the converted value.
209 ConstantToValueMapTy::iterator CTII = ConstantToValueMap.find(C);
210 if (CTII != ConstantToValueMap.end()) {
215 if (isa<GlobalVariable>(C)) {
216 // If the constant C is a global variable and is found in GVMap, generate a
217 // set set of instructions that convert the clone of C with the global
218 // address space specifier to a generic pointer.
219 // The constant C cannot be used here, as it will be erased from the
220 // module eventually. And the clone of C with the global address space
221 // specifier cannot be used here either, as it will affect the types of
222 // other instructions in the function. Hence, this address space conversion
224 GVMapTy::iterator I = GVMap.find(cast<GlobalVariable>(C));
225 if (I != GVMap.end()) {
226 NewValue = getOrInsertCVTA(M, F, I->second, Builder);
228 } else if (isa<ConstantVector>(C) || isa<ConstantArray>(C) ||
229 isa<ConstantStruct>(C)) {
230 // If any element in the constant vector or aggregate C is or uses a global
231 // variable in GVMap, the constant C needs to be reconstructed, using a set
233 NewValue = remapConstantVectorOrConstantAggregate(M, F, C, Builder);
234 } else if (isa<ConstantExpr>(C)) {
235 // If any operand in the constant expression C is or uses a global variable
236 // in GVMap, the constant expression C needs to be reconstructed, using a
237 // set of instructions.
238 NewValue = remapConstantExpr(M, F, cast<ConstantExpr>(C), Builder);
241 ConstantToValueMap[C] = NewValue;
245 Value *GenericToNVVM::remapConstantVectorOrConstantAggregate(
246 Module *M, Function *F, Constant *C, IRBuilder<> &Builder) {
247 bool OperandChanged = false;
248 SmallVector<Value *, 4> NewOperands;
249 unsigned NumOperands = C->getNumOperands();
251 // Check if any element is or uses a global variable in GVMap, and thus
252 // converted to another value.
253 for (unsigned i = 0; i < NumOperands; ++i) {
254 Value *Operand = C->getOperand(i);
255 Value *NewOperand = remapConstant(M, F, cast<Constant>(Operand), Builder);
256 OperandChanged |= Operand != NewOperand;
257 NewOperands.push_back(NewOperand);
260 // If none of the elements has been modified, return C as it is.
261 if (!OperandChanged) {
265 // If any of the elements has been modified, construct the equivalent
266 // vector or aggregate value with a set instructions and the converted
268 Value *NewValue = UndefValue::get(C->getType());
269 if (isa<ConstantVector>(C)) {
270 for (unsigned i = 0; i < NumOperands; ++i) {
271 Value *Idx = ConstantInt::get(Type::getInt32Ty(M->getContext()), i);
272 NewValue = Builder.CreateInsertElement(NewValue, NewOperands[i], Idx);
275 for (unsigned i = 0; i < NumOperands; ++i) {
277 Builder.CreateInsertValue(NewValue, NewOperands[i], makeArrayRef(i));
284 Value *GenericToNVVM::remapConstantExpr(Module *M, Function *F, ConstantExpr *C,
285 IRBuilder<> &Builder) {
286 bool OperandChanged = false;
287 SmallVector<Value *, 4> NewOperands;
288 unsigned NumOperands = C->getNumOperands();
290 // Check if any operand is or uses a global variable in GVMap, and thus
291 // converted to another value.
292 for (unsigned i = 0; i < NumOperands; ++i) {
293 Value *Operand = C->getOperand(i);
294 Value *NewOperand = remapConstant(M, F, cast<Constant>(Operand), Builder);
295 OperandChanged |= Operand != NewOperand;
296 NewOperands.push_back(NewOperand);
299 // If none of the operands has been modified, return C as it is.
300 if (!OperandChanged) {
304 // If any of the operands has been modified, construct the instruction with
305 // the converted operands.
306 unsigned Opcode = C->getOpcode();
308 case Instruction::ICmp:
309 // CompareConstantExpr (icmp)
310 return Builder.CreateICmp(CmpInst::Predicate(C->getPredicate()),
311 NewOperands[0], NewOperands[1]);
312 case Instruction::FCmp:
313 // CompareConstantExpr (fcmp)
314 assert(false && "Address space conversion should have no effect "
315 "on float point CompareConstantExpr (fcmp)!");
317 case Instruction::ExtractElement:
318 // ExtractElementConstantExpr
319 return Builder.CreateExtractElement(NewOperands[0], NewOperands[1]);
320 case Instruction::InsertElement:
321 // InsertElementConstantExpr
322 return Builder.CreateInsertElement(NewOperands[0], NewOperands[1],
324 case Instruction::ShuffleVector:
326 return Builder.CreateShuffleVector(NewOperands[0], NewOperands[1],
328 case Instruction::ExtractValue:
329 // ExtractValueConstantExpr
330 return Builder.CreateExtractValue(NewOperands[0], C->getIndices());
331 case Instruction::InsertValue:
332 // InsertValueConstantExpr
333 return Builder.CreateInsertValue(NewOperands[0], NewOperands[1],
335 case Instruction::GetElementPtr:
336 // GetElementPtrConstantExpr
337 return cast<GEPOperator>(C)->isInBounds()
340 makeArrayRef(&NewOperands[1], NumOperands - 1))
341 : Builder.CreateInBoundsGEP(
343 makeArrayRef(&NewOperands[1], NumOperands - 1));
344 case Instruction::Select:
345 // SelectConstantExpr
346 return Builder.CreateSelect(NewOperands[0], NewOperands[1], NewOperands[2]);
348 // BinaryConstantExpr
349 if (Instruction::isBinaryOp(Opcode)) {
350 return Builder.CreateBinOp(Instruction::BinaryOps(C->getOpcode()),
351 NewOperands[0], NewOperands[1]);
354 if (Instruction::isCast(Opcode)) {
355 return Builder.CreateCast(Instruction::CastOps(C->getOpcode()),
356 NewOperands[0], C->getType());
358 assert(false && "GenericToNVVM encountered an unsupported ConstantExpr");
363 void GenericToNVVM::remapNamedMDNode(Module *M, NamedMDNode *N) {
365 bool OperandChanged = false;
366 SmallVector<MDNode *, 16> NewOperands;
367 unsigned NumOperands = N->getNumOperands();
369 // Check if any operand is or contains a global variable in GVMap, and thus
370 // converted to another value.
371 for (unsigned i = 0; i < NumOperands; ++i) {
372 MDNode *Operand = N->getOperand(i);
373 MDNode *NewOperand = remapMDNode(M, Operand);
374 OperandChanged |= Operand != NewOperand;
375 NewOperands.push_back(NewOperand);
378 // If none of the operands has been modified, return immediately.
379 if (!OperandChanged) {
383 // Replace the old operands with the new operands.
384 N->dropAllReferences();
385 for (SmallVectorImpl<MDNode *>::iterator I = NewOperands.begin(),
386 E = NewOperands.end();
392 MDNode *GenericToNVVM::remapMDNode(Module *M, MDNode *N) {
394 bool OperandChanged = false;
395 SmallVector<Value *, 8> NewOperands;
396 unsigned NumOperands = N->getNumOperands();
398 // Check if any operand is or contains a global variable in GVMap, and thus
399 // converted to another value.
400 for (unsigned i = 0; i < NumOperands; ++i) {
401 Value *Operand = N->getOperand(i);
402 Value *NewOperand = Operand;
404 if (isa<GlobalVariable>(Operand)) {
405 GVMapTy::iterator I = GVMap.find(cast<GlobalVariable>(Operand));
406 if (I != GVMap.end()) {
407 NewOperand = I->second;
408 if (++i < NumOperands) {
409 NewOperands.push_back(NewOperand);
410 // Address space of the global variable follows the global variable
411 // in the global variable debug info (see createGlobalVariable in
412 // lib/Analysis/DIBuilder.cpp).
414 ConstantInt::get(Type::getInt32Ty(M->getContext()),
415 I->second->getType()->getAddressSpace());
418 } else if (isa<MDNode>(Operand)) {
419 NewOperand = remapMDNode(M, cast<MDNode>(Operand));
422 OperandChanged |= Operand != NewOperand;
423 NewOperands.push_back(NewOperand);
426 // If none of the operands has been modified, return N as it is.
427 if (!OperandChanged) {
431 // If any of the operands has been modified, create a new MDNode with the new
433 return MDNode::get(M->getContext(), makeArrayRef(NewOperands));