blob: 916b0e1156640553214f044c95184904c3d8d32d [file] [log] [blame]
Justin Holewinski01f89f02013-05-20 12:13:32 +00001//===-- GenericToNVVM.cpp - Convert generic module to NVVM module - C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Convert generic global variables into either .global or .const access based
11// on the variable's "constant" qualifier.
12//
13//===----------------------------------------------------------------------===//
14
Justin Holewinski01f89f02013-05-20 12:13:32 +000015#include "MCTargetDesc/NVPTXBaseInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000016#include "NVPTX.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000017#include "NVPTXUtilities.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000018#include "llvm/CodeGen/ValueTypes.h"
Justin Holewinski01f89f02013-05-20 12:13:32 +000019#include "llvm/IR/Constants.h"
20#include "llvm/IR/DerivedTypes.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000021#include "llvm/IR/IRBuilder.h"
Justin Holewinski01f89f02013-05-20 12:13:32 +000022#include "llvm/IR/Instructions.h"
23#include "llvm/IR/Intrinsics.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000024#include "llvm/IR/LegacyPassManager.h"
Justin Holewinski01f89f02013-05-20 12:13:32 +000025#include "llvm/IR/Module.h"
26#include "llvm/IR/Operator.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000027#include "llvm/IR/ValueMap.h"
Duncan P. N. Exon Smith9f6bddd2015-01-14 05:14:30 +000028#include "llvm/Transforms/Utils/ValueMapper.h"
Justin Holewinski01f89f02013-05-20 12:13:32 +000029
30using namespace llvm;
31
32namespace llvm {
33void initializeGenericToNVVMPass(PassRegistry &);
34}
35
36namespace {
37class GenericToNVVM : public ModulePass {
38public:
39 static char ID;
40
41 GenericToNVVM() : ModulePass(ID) {}
42
Craig Topper2865c982014-04-29 07:57:44 +000043 bool runOnModule(Module &M) override;
Justin Holewinski01f89f02013-05-20 12:13:32 +000044
Craig Topper2865c982014-04-29 07:57:44 +000045 void getAnalysisUsage(AnalysisUsage &AU) const override {}
Justin Holewinski01f89f02013-05-20 12:13:32 +000046
47private:
48 Value *getOrInsertCVTA(Module *M, Function *F, GlobalVariable *GV,
49 IRBuilder<> &Builder);
50 Value *remapConstant(Module *M, Function *F, Constant *C,
51 IRBuilder<> &Builder);
52 Value *remapConstantVectorOrConstantAggregate(Module *M, Function *F,
53 Constant *C,
54 IRBuilder<> &Builder);
55 Value *remapConstantExpr(Module *M, Function *F, ConstantExpr *C,
56 IRBuilder<> &Builder);
Justin Holewinski01f89f02013-05-20 12:13:32 +000057
58 typedef ValueMap<GlobalVariable *, GlobalVariable *> GVMapTy;
59 typedef ValueMap<Constant *, Value *> ConstantToValueMapTy;
60 GVMapTy GVMap;
61 ConstantToValueMapTy ConstantToValueMap;
62};
Gautam Chakrabarti35bd9522014-01-27 20:03:35 +000063} // end namespace
Justin Holewinski01f89f02013-05-20 12:13:32 +000064
65char GenericToNVVM::ID = 0;
66
67ModulePass *llvm::createGenericToNVVMPass() { return new GenericToNVVM(); }
68
69INITIALIZE_PASS(
70 GenericToNVVM, "generic-to-nvvm",
71 "Ensure that the global variables are in the global address space", false,
72 false)
73
74bool GenericToNVVM::runOnModule(Module &M) {
75 // Create a clone of each global variable that has the default address space.
76 // The clone is created with the global address space specifier, and the pair
77 // of original global variable and its clone is placed in the GVMap for later
78 // use.
79
80 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
81 I != E;) {
Duncan P. N. Exon Smith61149b82015-10-20 00:54:09 +000082 GlobalVariable *GV = &*I++;
Justin Holewinski01f89f02013-05-20 12:13:32 +000083 if (GV->getType()->getAddressSpace() == llvm::ADDRESS_SPACE_GENERIC &&
84 !llvm::isTexture(*GV) && !llvm::isSurface(*GV) &&
Justin Holewinskie519a432014-06-27 18:36:02 +000085 !llvm::isSampler(*GV) && !GV->getName().startswith("llvm.")) {
Justin Holewinski01f89f02013-05-20 12:13:32 +000086 GlobalVariable *NewGV = new GlobalVariable(
Manuel Jacob5f6eaac2016-01-16 20:30:46 +000087 M, GV->getValueType(), GV->isConstant(),
Craig Topper062a2ba2014-04-25 05:30:21 +000088 GV->getLinkage(),
89 GV->hasInitializer() ? GV->getInitializer() : nullptr,
Justin Holewinski01f89f02013-05-20 12:13:32 +000090 "", GV, GV->getThreadLocalMode(), llvm::ADDRESS_SPACE_GLOBAL);
91 NewGV->copyAttributesFrom(GV);
92 GVMap[GV] = NewGV;
93 }
94 }
95
96 // Return immediately, if every global variable has a specific address space
97 // specifier.
98 if (GVMap.empty()) {
99 return false;
100 }
101
102 // Walk through the instructions in function defitinions, and replace any use
103 // of original global variables in GVMap with a use of the corresponding
104 // copies in GVMap. If necessary, promote constants to instructions.
105 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
106 if (I->isDeclaration()) {
107 continue;
108 }
109 IRBuilder<> Builder(I->getEntryBlock().getFirstNonPHIOrDbg());
110 for (Function::iterator BBI = I->begin(), BBE = I->end(); BBI != BBE;
111 ++BBI) {
112 for (BasicBlock::iterator II = BBI->begin(), IE = BBI->end(); II != IE;
113 ++II) {
114 for (unsigned i = 0, e = II->getNumOperands(); i < e; ++i) {
115 Value *Operand = II->getOperand(i);
116 if (isa<Constant>(Operand)) {
117 II->setOperand(
Duncan P. N. Exon Smith61149b82015-10-20 00:54:09 +0000118 i, remapConstant(&M, &*I, cast<Constant>(Operand), Builder));
Justin Holewinski01f89f02013-05-20 12:13:32 +0000119 }
120 }
121 }
122 }
123 ConstantToValueMap.clear();
124 }
125
Duncan P. N. Exon Smith9f6bddd2015-01-14 05:14:30 +0000126 // Copy GVMap over to a standard value map.
127 ValueToValueMapTy VM;
128 for (auto I = GVMap.begin(), E = GVMap.end(); I != E; ++I)
129 VM[I->first] = I->second;
130
Justin Holewinski01f89f02013-05-20 12:13:32 +0000131 // Walk through the global variable initializers, and replace any use of
132 // original global variables in GVMap with a use of the corresponding copies
133 // in GVMap. The copies need to be bitcast to the original global variable
134 // types, as we cannot use cvta in global variable initializers.
135 for (GVMapTy::iterator I = GVMap.begin(), E = GVMap.end(); I != E;) {
136 GlobalVariable *GV = I->first;
137 GlobalVariable *NewGV = I->second;
Duncan P. N. Exon Smith7b859ff2014-08-19 00:20:02 +0000138
139 // Remove GV from the map so that it can be RAUWed. Note that
140 // DenseMap::erase() won't invalidate any iterators but this one.
141 auto Next = std::next(I);
142 GVMap.erase(I);
143 I = Next;
144
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +0000145 Constant *BitCastNewGV = ConstantExpr::getPointerCast(NewGV, GV->getType());
Justin Holewinski01f89f02013-05-20 12:13:32 +0000146 // 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.
Duncan P. N. Exon Smith7b859ff2014-08-19 00:20:02 +0000149 GV->replaceAllUsesWith(BitCastNewGV);
Justin Holewinski01f89f02013-05-20 12:13:32 +0000150 std::string Name = GV->getName();
Justin Holewinski01f89f02013-05-20 12:13:32 +0000151 GV->eraseFromParent();
152 NewGV->setName(Name);
153 }
Duncan P. N. Exon Smith7b859ff2014-08-19 00:20:02 +0000154 assert(GVMap.empty() && "Expected it to be empty by now");
Justin Holewinski01f89f02013-05-20 12:13:32 +0000155
156 return true;
157}
158
159Value *GenericToNVVM::getOrInsertCVTA(Module *M, Function *F,
160 GlobalVariable *GV,
161 IRBuilder<> &Builder) {
162 PointerType *GVType = GV->getType();
Craig Topper062a2ba2014-04-25 05:30:21 +0000163 Value *CVTA = nullptr;
Justin Holewinski01f89f02013-05-20 12:13:32 +0000164
165 // See if the address space conversion requires the operand to be bitcast
166 // to i8 addrspace(n)* first.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000167 EVT ExtendedGVType = EVT::getEVT(GV->getValueType(), true);
Justin Holewinski01f89f02013-05-20 12:13:32 +0000168 if (!ExtendedGVType.isInteger() && !ExtendedGVType.isFloatingPoint()) {
169 // A bitcast to i8 addrspace(n)* on the operand is needed.
170 LLVMContext &Context = M->getContext();
171 unsigned int AddrSpace = GVType->getAddressSpace();
172 Type *DestTy = PointerType::get(Type::getInt8Ty(Context), AddrSpace);
173 CVTA = Builder.CreateBitCast(GV, DestTy, "cvta");
174 // Insert the address space conversion.
175 Type *ResultType =
176 PointerType::get(Type::getInt8Ty(Context), llvm::ADDRESS_SPACE_GENERIC);
Justin Holewinski01f89f02013-05-20 12:13:32 +0000177 Function *CVTAFunction = Intrinsic::getDeclaration(
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +0000178 M, Intrinsic::nvvm_ptr_global_to_gen, {ResultType, DestTy});
Justin Holewinski01f89f02013-05-20 12:13:32 +0000179 CVTA = Builder.CreateCall(CVTAFunction, CVTA, "cvta");
180 // Another bitcast from i8 * to <the element type of GVType> * is
181 // required.
182 DestTy =
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000183 PointerType::get(GV->getValueType(), llvm::ADDRESS_SPACE_GENERIC);
Justin Holewinski01f89f02013-05-20 12:13:32 +0000184 CVTA = Builder.CreateBitCast(CVTA, DestTy, "cvta");
185 } else {
186 // A simple CVTA is enough.
187 SmallVector<Type *, 2> ParamTypes;
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000188 ParamTypes.push_back(PointerType::get(GV->getValueType(),
Justin Holewinski01f89f02013-05-20 12:13:32 +0000189 llvm::ADDRESS_SPACE_GENERIC));
190 ParamTypes.push_back(GVType);
191 Function *CVTAFunction = Intrinsic::getDeclaration(
192 M, Intrinsic::nvvm_ptr_global_to_gen, ParamTypes);
193 CVTA = Builder.CreateCall(CVTAFunction, GV, "cvta");
194 }
195
196 return CVTA;
197}
198
199Value *GenericToNVVM::remapConstant(Module *M, Function *F, Constant *C,
200 IRBuilder<> &Builder) {
201 // If the constant C has been converted already in the given function F, just
202 // return the converted value.
203 ConstantToValueMapTy::iterator CTII = ConstantToValueMap.find(C);
204 if (CTII != ConstantToValueMap.end()) {
205 return CTII->second;
206 }
207
208 Value *NewValue = C;
209 if (isa<GlobalVariable>(C)) {
210 // If the constant C is a global variable and is found in GVMap, generate a
211 // set set of instructions that convert the clone of C with the global
212 // address space specifier to a generic pointer.
213 // The constant C cannot be used here, as it will be erased from the
214 // module eventually. And the clone of C with the global address space
215 // specifier cannot be used here either, as it will affect the types of
216 // other instructions in the function. Hence, this address space conversion
217 // is required.
218 GVMapTy::iterator I = GVMap.find(cast<GlobalVariable>(C));
219 if (I != GVMap.end()) {
220 NewValue = getOrInsertCVTA(M, F, I->second, Builder);
221 }
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000222 } else if (isa<ConstantAggregate>(C)) {
Justin Holewinski01f89f02013-05-20 12:13:32 +0000223 // If any element in the constant vector or aggregate C is or uses a global
224 // variable in GVMap, the constant C needs to be reconstructed, using a set
225 // of instructions.
226 NewValue = remapConstantVectorOrConstantAggregate(M, F, C, Builder);
227 } else if (isa<ConstantExpr>(C)) {
228 // If any operand in the constant expression C is or uses a global variable
229 // in GVMap, the constant expression C needs to be reconstructed, using a
230 // set of instructions.
231 NewValue = remapConstantExpr(M, F, cast<ConstantExpr>(C), Builder);
232 }
233
234 ConstantToValueMap[C] = NewValue;
235 return NewValue;
236}
237
238Value *GenericToNVVM::remapConstantVectorOrConstantAggregate(
239 Module *M, Function *F, Constant *C, IRBuilder<> &Builder) {
240 bool OperandChanged = false;
241 SmallVector<Value *, 4> NewOperands;
242 unsigned NumOperands = C->getNumOperands();
243
244 // Check if any element is or uses a global variable in GVMap, and thus
245 // converted to another value.
246 for (unsigned i = 0; i < NumOperands; ++i) {
247 Value *Operand = C->getOperand(i);
248 Value *NewOperand = remapConstant(M, F, cast<Constant>(Operand), Builder);
249 OperandChanged |= Operand != NewOperand;
250 NewOperands.push_back(NewOperand);
251 }
252
253 // If none of the elements has been modified, return C as it is.
254 if (!OperandChanged) {
255 return C;
256 }
257
258 // If any of the elements has been modified, construct the equivalent
259 // vector or aggregate value with a set instructions and the converted
260 // elements.
261 Value *NewValue = UndefValue::get(C->getType());
262 if (isa<ConstantVector>(C)) {
263 for (unsigned i = 0; i < NumOperands; ++i) {
264 Value *Idx = ConstantInt::get(Type::getInt32Ty(M->getContext()), i);
265 NewValue = Builder.CreateInsertElement(NewValue, NewOperands[i], Idx);
266 }
267 } else {
268 for (unsigned i = 0; i < NumOperands; ++i) {
269 NewValue =
270 Builder.CreateInsertValue(NewValue, NewOperands[i], makeArrayRef(i));
271 }
272 }
273
274 return NewValue;
275}
276
277Value *GenericToNVVM::remapConstantExpr(Module *M, Function *F, ConstantExpr *C,
278 IRBuilder<> &Builder) {
279 bool OperandChanged = false;
280 SmallVector<Value *, 4> NewOperands;
281 unsigned NumOperands = C->getNumOperands();
282
283 // Check if any operand is or uses a global variable in GVMap, and thus
284 // converted to another value.
285 for (unsigned i = 0; i < NumOperands; ++i) {
286 Value *Operand = C->getOperand(i);
287 Value *NewOperand = remapConstant(M, F, cast<Constant>(Operand), Builder);
288 OperandChanged |= Operand != NewOperand;
289 NewOperands.push_back(NewOperand);
290 }
291
292 // If none of the operands has been modified, return C as it is.
293 if (!OperandChanged) {
294 return C;
295 }
296
297 // If any of the operands has been modified, construct the instruction with
298 // the converted operands.
299 unsigned Opcode = C->getOpcode();
300 switch (Opcode) {
301 case Instruction::ICmp:
302 // CompareConstantExpr (icmp)
303 return Builder.CreateICmp(CmpInst::Predicate(C->getPredicate()),
304 NewOperands[0], NewOperands[1]);
305 case Instruction::FCmp:
306 // CompareConstantExpr (fcmp)
Benjamin Kramer8ceb3232015-10-25 22:28:27 +0000307 llvm_unreachable("Address space conversion should have no effect "
308 "on float point CompareConstantExpr (fcmp)!");
Justin Holewinski01f89f02013-05-20 12:13:32 +0000309 case Instruction::ExtractElement:
310 // ExtractElementConstantExpr
311 return Builder.CreateExtractElement(NewOperands[0], NewOperands[1]);
312 case Instruction::InsertElement:
313 // InsertElementConstantExpr
314 return Builder.CreateInsertElement(NewOperands[0], NewOperands[1],
315 NewOperands[2]);
316 case Instruction::ShuffleVector:
317 // ShuffleVector
318 return Builder.CreateShuffleVector(NewOperands[0], NewOperands[1],
319 NewOperands[2]);
320 case Instruction::ExtractValue:
321 // ExtractValueConstantExpr
322 return Builder.CreateExtractValue(NewOperands[0], C->getIndices());
323 case Instruction::InsertValue:
324 // InsertValueConstantExpr
325 return Builder.CreateInsertValue(NewOperands[0], NewOperands[1],
326 C->getIndices());
327 case Instruction::GetElementPtr:
328 // GetElementPtrConstantExpr
329 return cast<GEPOperator>(C)->isInBounds()
330 ? Builder.CreateGEP(
David Blaikie156d46e2015-03-24 23:34:31 +0000331 cast<GEPOperator>(C)->getSourceElementType(),
Justin Holewinski01f89f02013-05-20 12:13:32 +0000332 NewOperands[0],
333 makeArrayRef(&NewOperands[1], NumOperands - 1))
334 : Builder.CreateInBoundsGEP(
David Blaikieaa41cd52015-04-03 21:33:42 +0000335 cast<GEPOperator>(C)->getSourceElementType(),
Justin Holewinski01f89f02013-05-20 12:13:32 +0000336 NewOperands[0],
337 makeArrayRef(&NewOperands[1], NumOperands - 1));
338 case Instruction::Select:
339 // SelectConstantExpr
340 return Builder.CreateSelect(NewOperands[0], NewOperands[1], NewOperands[2]);
341 default:
342 // BinaryConstantExpr
343 if (Instruction::isBinaryOp(Opcode)) {
344 return Builder.CreateBinOp(Instruction::BinaryOps(C->getOpcode()),
345 NewOperands[0], NewOperands[1]);
346 }
347 // UnaryConstantExpr
348 if (Instruction::isCast(Opcode)) {
349 return Builder.CreateCast(Instruction::CastOps(C->getOpcode()),
350 NewOperands[0], C->getType());
351 }
Benjamin Kramer8ceb3232015-10-25 22:28:27 +0000352 llvm_unreachable("GenericToNVVM encountered an unsupported ConstantExpr");
Justin Holewinski01f89f02013-05-20 12:13:32 +0000353 }
354}