blob: 8e2cf822246da20bda80640d8bb04f8bd506ab21 [file] [log] [blame]
Justin Holewinskiae556d32012-05-04 20:18:50 +00001//===-- NVPTXAsmPrinter.cpp - NVPTX LLVM assembly writer ------------------===//
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// This file contains a printer that converts from our internal representation
11// of machine-dependent LLVM code to NVPTX assembly language.
12//
13//===----------------------------------------------------------------------===//
14
Bill Wendlinge38859d2012-06-28 00:05:13 +000015#include "NVPTXAsmPrinter.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000016#include "InstPrinter/NVPTXInstPrinter.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "MCTargetDesc/NVPTXMCAsmInfo.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000018#include "NVPTX.h"
19#include "NVPTXInstrInfo.h"
Justin Holewinskia2a63d22013-08-06 14:13:27 +000020#include "NVPTXMCExpr.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "NVPTXRegisterInfo.h"
22#include "NVPTXTargetMachine.h"
23#include "NVPTXUtilities.h"
24#include "cl_common_defines.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000025#include "llvm/ADT/StringExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/Analysis/ConstantFolding.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000027#include "llvm/CodeGen/Analysis.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000028#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineModuleInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000031#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/DerivedTypes.h"
33#include "llvm/IR/Function.h"
34#include "llvm/IR/GlobalVariable.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000035#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/Module.h"
37#include "llvm/IR/Operator.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000038#include "llvm/MC/MCStreamer.h"
39#include "llvm/MC/MCSymbol.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000040#include "llvm/Support/CommandLine.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000041#include "llvm/Support/ErrorHandling.h"
42#include "llvm/Support/FormattedStream.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000043#include "llvm/Support/Path.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000044#include "llvm/Support/TargetRegistry.h"
45#include "llvm/Support/TimeValue.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000046#include "llvm/Target/TargetLoweringObjectFile.h"
Bill Wendlinge38859d2012-06-28 00:05:13 +000047#include <sstream>
Justin Holewinskiae556d32012-05-04 20:18:50 +000048using namespace llvm;
49
Justin Holewinskiae556d32012-05-04 20:18:50 +000050#define DEPOTNAME "__local_depot"
51
52static cl::opt<bool>
Nadav Rotem7f27e0b2013-10-18 23:38:13 +000053EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
Justin Holewinskiae556d32012-05-04 20:18:50 +000054 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
55 cl::init(true));
56
Benjamin Kramer7ad41002013-10-27 11:31:46 +000057static cl::opt<bool>
Nadav Rotem7f27e0b2013-10-18 23:38:13 +000058InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
Justin Holewinski0497ab12013-03-30 14:29:21 +000059 cl::desc("NVPTX Specific: Emit source line in ptx file"),
Benjamin Kramer7ad41002013-10-27 11:31:46 +000060 cl::init(false));
Justin Holewinskiae556d32012-05-04 20:18:50 +000061
Justin Holewinski2c5ac702012-11-16 21:03:51 +000062namespace {
63/// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
64/// depends.
Justin Holewinski01f89f02013-05-20 12:13:32 +000065void DiscoverDependentGlobals(const Value *V,
66 DenseSet<const GlobalVariable *> &Globals) {
67 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Justin Holewinski2c5ac702012-11-16 21:03:51 +000068 Globals.insert(GV);
69 else {
Justin Holewinski01f89f02013-05-20 12:13:32 +000070 if (const User *U = dyn_cast<User>(V)) {
Justin Holewinski2c5ac702012-11-16 21:03:51 +000071 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
72 DiscoverDependentGlobals(U->getOperand(i), Globals);
73 }
74 }
75 }
76}
Justin Holewinskiae556d32012-05-04 20:18:50 +000077
Justin Holewinski2c5ac702012-11-16 21:03:51 +000078/// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
79/// instances to be emitted, but only after any dependents have been added
80/// first.
Justin Holewinski0497ab12013-03-30 14:29:21 +000081void VisitGlobalVariableForEmission(
Justin Holewinski01f89f02013-05-20 12:13:32 +000082 const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
83 DenseSet<const GlobalVariable *> &Visited,
84 DenseSet<const GlobalVariable *> &Visiting) {
Justin Holewinski2c5ac702012-11-16 21:03:51 +000085 // Have we already visited this one?
Justin Holewinski0497ab12013-03-30 14:29:21 +000086 if (Visited.count(GV))
87 return;
Justin Holewinski2c5ac702012-11-16 21:03:51 +000088
89 // Do we have a circular dependency?
90 if (Visiting.count(GV))
91 report_fatal_error("Circular dependency found in global variable set");
92
93 // Start visiting this global
94 Visiting.insert(GV);
95
96 // Make sure we visit all dependents first
Justin Holewinski01f89f02013-05-20 12:13:32 +000097 DenseSet<const GlobalVariable *> Others;
Justin Holewinski2c5ac702012-11-16 21:03:51 +000098 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
99 DiscoverDependentGlobals(GV->getOperand(i), Others);
Justin Holewinski0497ab12013-03-30 14:29:21 +0000100
Justin Holewinski01f89f02013-05-20 12:13:32 +0000101 for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
102 E = Others.end();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000103 I != E; ++I)
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000104 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
105
106 // Now we can visit ourself
107 Order.push_back(GV);
108 Visited.insert(GV);
109 Visiting.erase(GV);
110}
111}
Justin Holewinskiae556d32012-05-04 20:18:50 +0000112
113// @TODO: This is a copy from AsmPrinter.cpp. The function is static, so we
114// cannot just link to the existing version.
115/// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
116///
117using namespace nvptx;
118const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
119 MCContext &Ctx = AP.OutContext;
120
121 if (CV->isNullValue() || isa<UndefValue>(CV))
122 return MCConstantExpr::Create(0, Ctx);
123
124 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
125 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
126
127 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
Rafael Espindola79858aa2013-10-29 17:07:16 +0000128 return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000129
130 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
131 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
132
133 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
134 if (CE == 0)
135 llvm_unreachable("Unknown constant value to lower!");
136
Justin Holewinskiae556d32012-05-04 20:18:50 +0000137 switch (CE->getOpcode()) {
138 default:
139 // If the code isn't optimized, there may be outstanding folding
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000140 // opportunities. Attempt to fold the expression using DataLayout as a
Justin Holewinskiae556d32012-05-04 20:18:50 +0000141 // last resort before giving up.
Justin Holewinski0497ab12013-03-30 14:29:21 +0000142 if (Constant *C = ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000143 if (C != CE)
144 return LowerConstant(C, AP);
145
146 // Otherwise report the problem to the user.
147 {
Justin Holewinski0497ab12013-03-30 14:29:21 +0000148 std::string S;
149 raw_string_ostream OS(S);
150 OS << "Unsupported expression in static initializer: ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000151 CE->printAsOperand(OS, /*PrintType=*/ false,
Justin Holewinski0497ab12013-03-30 14:29:21 +0000152 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
153 report_fatal_error(OS.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000154 }
155 case Instruction::GetElementPtr: {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000156 const DataLayout &TD = *AP.TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000157 // Generate a symbolic expression for the byte address
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000158 APInt OffsetAI(TD.getPointerSizeInBits(), 0);
159 cast<GEPOperator>(CE)->accumulateConstantOffset(TD, OffsetAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000160
161 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000162 if (!OffsetAI)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000163 return Base;
164
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000165 int64_t Offset = OffsetAI.getSExtValue();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000166 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
167 Ctx);
168 }
169
170 case Instruction::Trunc:
171 // We emit the value and depend on the assembler to truncate the generated
172 // expression properly. This is important for differences between
173 // blockaddress labels. Since the two labels are in the same function, it
174 // is reasonable to treat their delta as a 32-bit value.
Justin Holewinski0497ab12013-03-30 14:29:21 +0000175 // FALL THROUGH.
Justin Holewinskiae556d32012-05-04 20:18:50 +0000176 case Instruction::BitCast:
177 return LowerConstant(CE->getOperand(0), AP);
178
179 case Instruction::IntToPtr: {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000180 const DataLayout &TD = *AP.TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000181 // Handle casts to pointers by changing them into casts to the appropriate
182 // integer type. This promotes constant folding and simplifies this code.
183 Constant *Op = CE->getOperand(0);
Chandler Carruth7ec50852012-11-01 08:07:29 +0000184 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
Justin Holewinski0497ab12013-03-30 14:29:21 +0000185 false /*ZExt*/);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000186 return LowerConstant(Op, AP);
187 }
188
189 case Instruction::PtrToInt: {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000190 const DataLayout &TD = *AP.TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000191 // Support only foldable casts to/from pointers that can be eliminated by
192 // changing the pointer to the appropriately sized integer type.
193 Constant *Op = CE->getOperand(0);
194 Type *Ty = CE->getType();
195
196 const MCExpr *OpExpr = LowerConstant(Op, AP);
197
198 // We can emit the pointer value into this slot if the slot is an
199 // integer slot equal to the size of the pointer.
200 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
201 return OpExpr;
202
203 // Otherwise the pointer is smaller than the resultant integer, mask off
204 // the high bits so we are sure to get a proper truncation if the input is
205 // a constant expr.
206 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
Justin Holewinski0497ab12013-03-30 14:29:21 +0000207 const MCExpr *MaskExpr =
208 MCConstantExpr::Create(~0ULL >> (64 - InBits), Ctx);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000209 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
210 }
211
Justin Holewinski0497ab12013-03-30 14:29:21 +0000212 // The MC library also has a right-shift operator, but it isn't consistently
Justin Holewinskiae556d32012-05-04 20:18:50 +0000213 // signed or unsigned between different targets.
214 case Instruction::Add:
215 case Instruction::Sub:
216 case Instruction::Mul:
217 case Instruction::SDiv:
218 case Instruction::SRem:
219 case Instruction::Shl:
220 case Instruction::And:
221 case Instruction::Or:
222 case Instruction::Xor: {
223 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
224 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
225 switch (CE->getOpcode()) {
Justin Holewinski0497ab12013-03-30 14:29:21 +0000226 default:
227 llvm_unreachable("Unknown binary operator constant cast expr");
228 case Instruction::Add:
229 return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
230 case Instruction::Sub:
231 return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
232 case Instruction::Mul:
233 return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
234 case Instruction::SDiv:
235 return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
236 case Instruction::SRem:
237 return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
238 case Instruction::Shl:
239 return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
240 case Instruction::And:
241 return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
242 case Instruction::Or:
243 return MCBinaryExpr::CreateOr(LHS, RHS, Ctx);
244 case Instruction::Xor:
245 return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000246 }
247 }
248 }
249}
250
Justin Holewinski0497ab12013-03-30 14:29:21 +0000251void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000252 if (!EmitLineNumbers)
253 return;
254 if (ignoreLoc(MI))
255 return;
256
257 DebugLoc curLoc = MI.getDebugLoc();
258
259 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
260 return;
261
262 if (prevDebugLoc == curLoc)
263 return;
264
265 prevDebugLoc = curLoc;
266
267 if (curLoc.isUnknown())
268 return;
269
Justin Holewinskiae556d32012-05-04 20:18:50 +0000270 const MachineFunction *MF = MI.getParent()->getParent();
271 //const TargetMachine &TM = MF->getTarget();
272
273 const LLVMContext &ctx = MF->getFunction()->getContext();
274 DIScope Scope(curLoc.getScope(ctx));
275
Manman Ren983a16c2013-06-28 05:43:10 +0000276 assert((!Scope || Scope.isScope()) &&
277 "Scope of a DebugLoc should be null or a DIScope.");
278 if (!Scope)
279 return;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000280
281 StringRef fileName(Scope.getFilename());
282 StringRef dirName(Scope.getDirectory());
283 SmallString<128> FullPathName = dirName;
284 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
285 sys::path::append(FullPathName, fileName);
286 fileName = FullPathName.str();
287 }
288
289 if (filenameMap.find(fileName.str()) == filenameMap.end())
290 return;
291
Justin Holewinskiae556d32012-05-04 20:18:50 +0000292 // Emit the line from the source file.
Benjamin Kramer7ad41002013-10-27 11:31:46 +0000293 if (InterleaveSrc)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000294 this->emitSrcInText(fileName.str(), curLoc.getLine());
295
296 std::stringstream temp;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000297 temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
298 << " " << curLoc.getCol();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000299 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
300}
301
302void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
303 SmallString<128> Str;
304 raw_svector_ostream OS(Str);
305 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
306 emitLineNumberAsDotLoc(*MI);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000307
308 MCInst Inst;
309 lowerToMCInst(MI, Inst);
David Woodhousee6c13e42014-01-28 23:12:42 +0000310 EmitToStreamer(OutStreamer, Inst);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000311}
312
313void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
314 OutMI.setOpcode(MI->getOpcode());
315
Justin Holewinski3d49e5c2013-11-15 12:30:04 +0000316 // Special: Do not mangle symbol operand of CALL_PROTOTYPE
317 if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
318 const MachineOperand &MO = MI->getOperand(0);
319 OutMI.addOperand(GetSymbolRef(MO,
320 OutContext.GetOrCreateSymbol(Twine(MO.getSymbolName()))));
321 return;
322 }
323
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000324 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
325 const MachineOperand &MO = MI->getOperand(i);
326
327 MCOperand MCOp;
328 if (lowerOperand(MO, MCOp))
329 OutMI.addOperand(MCOp);
330 }
331}
332
333bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
334 MCOperand &MCOp) {
335 switch (MO.getType()) {
336 default: llvm_unreachable("unknown operand type");
337 case MachineOperand::MO_Register:
338 MCOp = MCOperand::CreateReg(encodeVirtualRegister(MO.getReg()));
339 break;
340 case MachineOperand::MO_Immediate:
341 MCOp = MCOperand::CreateImm(MO.getImm());
342 break;
343 case MachineOperand::MO_MachineBasicBlock:
344 MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
345 MO.getMBB()->getSymbol(), OutContext));
346 break;
347 case MachineOperand::MO_ExternalSymbol:
348 MCOp = GetSymbolRef(MO, GetExternalSymbolSymbol(MO.getSymbolName()));
349 break;
350 case MachineOperand::MO_GlobalAddress:
Rafael Espindola79858aa2013-10-29 17:07:16 +0000351 MCOp = GetSymbolRef(MO, getSymbol(MO.getGlobal()));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000352 break;
353 case MachineOperand::MO_FPImmediate: {
354 const ConstantFP *Cnt = MO.getFPImm();
355 APFloat Val = Cnt->getValueAPF();
356
357 switch (Cnt->getType()->getTypeID()) {
358 default: report_fatal_error("Unsupported FP type"); break;
359 case Type::FloatTyID:
360 MCOp = MCOperand::CreateExpr(
361 NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
362 break;
363 case Type::DoubleTyID:
364 MCOp = MCOperand::CreateExpr(
365 NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
366 break;
367 }
368 break;
369 }
370 }
371 return true;
372}
373
374unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
Justin Holewinski871ec932013-08-06 14:13:31 +0000375 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
376 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000377
Justin Holewinski871ec932013-08-06 14:13:31 +0000378 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
379 unsigned RegNum = RegMap[Reg];
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000380
Justin Holewinski871ec932013-08-06 14:13:31 +0000381 // Encode the register class in the upper 4 bits
382 // Must be kept in sync with NVPTXInstPrinter::printRegName
383 unsigned Ret = 0;
384 if (RC == &NVPTX::Int1RegsRegClass) {
385 Ret = (1 << 28);
386 } else if (RC == &NVPTX::Int16RegsRegClass) {
387 Ret = (2 << 28);
388 } else if (RC == &NVPTX::Int32RegsRegClass) {
389 Ret = (3 << 28);
390 } else if (RC == &NVPTX::Int64RegsRegClass) {
391 Ret = (4 << 28);
392 } else if (RC == &NVPTX::Float32RegsRegClass) {
393 Ret = (5 << 28);
394 } else if (RC == &NVPTX::Float64RegsRegClass) {
395 Ret = (6 << 28);
396 } else {
397 report_fatal_error("Bad register class");
398 }
399
400 // Insert the vreg number
401 Ret |= (RegNum & 0x0FFFFFFF);
402 return Ret;
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000403 } else {
Justin Holewinski871ec932013-08-06 14:13:31 +0000404 // Some special-use registers are actually physical registers.
405 // Encode this as the register class ID of 0 and the real register ID.
406 return Reg & 0x0FFFFFFF;
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000407 }
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000408}
409
410MCOperand NVPTXAsmPrinter::GetSymbolRef(const MachineOperand &MO,
411 const MCSymbol *Symbol) {
412 const MCExpr *Expr;
Justin Holewinski8b24e1e2013-08-06 23:06:42 +0000413 Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
414 OutContext);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000415 return MCOperand::CreateExpr(Expr);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000416}
417
Justin Holewinski0497ab12013-03-30 14:29:21 +0000418void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000419 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000420 const TargetLowering *TLI = TM.getTargetLowering();
421
422 Type *Ty = F->getReturnType();
423
424 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
425
426 if (Ty->getTypeID() == Type::VoidTyID)
427 return;
428
429 O << " (";
430
431 if (isABI) {
Rafael Espindola08013342013-12-07 19:34:20 +0000432 if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000433 unsigned size = 0;
434 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
435 size = ITy->getBitWidth();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000436 if (size < 32)
437 size = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000438 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +0000439 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000440 size = Ty->getPrimitiveSizeInBits();
441 }
442
443 O << ".param .b" << size << " func_retval0";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000444 } else if (isa<PointerType>(Ty)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000445 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
Justin Holewinski0497ab12013-03-30 14:29:21 +0000446 << " func_retval0";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000447 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +0000448 if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000449 SmallVector<EVT, 16> vtparts;
450 ComputeValueVTs(*TLI, Ty, vtparts);
451 unsigned totalsz = 0;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000452 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000453 unsigned elems = 1;
454 EVT elemtype = vtparts[i];
455 if (vtparts[i].isVector()) {
456 elems = vtparts[i].getVectorNumElements();
457 elemtype = vtparts[i].getVectorElementType();
458 }
Justin Holewinski0497ab12013-03-30 14:29:21 +0000459 for (unsigned j = 0, je = elems; j != je; ++j) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000460 unsigned sz = elemtype.getSizeInBits();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000461 if (elemtype.isInteger() && (sz < 8))
462 sz = 8;
463 totalsz += sz / 8;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000464 }
465 }
466 unsigned retAlignment = 0;
467 if (!llvm::getAlign(*F, 0, retAlignment))
468 retAlignment = TD->getABITypeAlignment(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +0000469 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
470 << "]";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000471 } else
Justin Holewinski0497ab12013-03-30 14:29:21 +0000472 assert(false && "Unknown return type");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000473 }
474 } else {
475 SmallVector<EVT, 16> vtparts;
476 ComputeValueVTs(*TLI, Ty, vtparts);
477 unsigned idx = 0;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000478 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000479 unsigned elems = 1;
480 EVT elemtype = vtparts[i];
481 if (vtparts[i].isVector()) {
482 elems = vtparts[i].getVectorNumElements();
483 elemtype = vtparts[i].getVectorElementType();
484 }
485
Justin Holewinski0497ab12013-03-30 14:29:21 +0000486 for (unsigned j = 0, je = elems; j != je; ++j) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000487 unsigned sz = elemtype.getSizeInBits();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000488 if (elemtype.isInteger() && (sz < 32))
489 sz = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000490 O << ".reg .b" << sz << " func_retval" << idx;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000491 if (j < je - 1)
492 O << ", ";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000493 ++idx;
494 }
Justin Holewinski0497ab12013-03-30 14:29:21 +0000495 if (i < e - 1)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000496 O << ", ";
497 }
498 }
499 O << ") ";
500 return;
501}
502
503void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
504 raw_ostream &O) {
505 const Function *F = MF.getFunction();
506 printReturnValStr(F, O);
507}
508
509void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
510 SmallString<128> Str;
511 raw_svector_ostream O(Str);
512
Justin Holewinski01f89f02013-05-20 12:13:32 +0000513 if (!GlobalsEmitted) {
514 emitGlobals(*MF->getFunction()->getParent());
515 GlobalsEmitted = true;
516 }
517
Justin Holewinskiae556d32012-05-04 20:18:50 +0000518 // Set up
519 MRI = &MF->getRegInfo();
520 F = MF->getFunction();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000521 emitLinkageDirective(F, O);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000522 if (llvm::isKernelFunction(*F))
523 O << ".entry ";
524 else {
525 O << ".func ";
526 printReturnValStr(*MF, O);
527 }
528
529 O << *CurrentFnSym;
530
531 emitFunctionParamList(*MF, O);
532
533 if (llvm::isKernelFunction(*F))
534 emitKernelFunctionDirectives(*F, O);
535
536 OutStreamer.EmitRawText(O.str());
537
538 prevDebugLoc = DebugLoc();
539}
540
541void NVPTXAsmPrinter::EmitFunctionBodyStart() {
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +0000542 VRegMapping.clear();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000543 OutStreamer.EmitRawText(StringRef("{\n"));
544 setAndEmitFunctionVirtualRegisters(*MF);
545
546 SmallString<128> Str;
547 raw_svector_ostream O(Str);
548 emitDemotedVars(MF->getFunction(), O);
549 OutStreamer.EmitRawText(O.str());
550}
551
552void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
553 OutStreamer.EmitRawText(StringRef("}\n"));
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +0000554 VRegMapping.clear();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000555}
556
Justin Holewinski660597d2013-10-11 12:39:36 +0000557void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
558 unsigned RegNo = MI->getOperand(0).getReg();
559 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
560 if (TRI->isVirtualRegister(RegNo)) {
561 OutStreamer.AddComment(Twine("implicit-def: ") +
562 getVirtualRegisterName(RegNo));
563 } else {
564 OutStreamer.AddComment(Twine("implicit-def: ") +
565 TM.getRegisterInfo()->getName(RegNo));
566 }
567 OutStreamer.AddBlankLine();
568}
569
Justin Holewinski0497ab12013-03-30 14:29:21 +0000570void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
571 raw_ostream &O) const {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000572 // If the NVVM IR has some of reqntid* specified, then output
573 // the reqntid directive, and set the unspecified ones to 1.
574 // If none of reqntid* is specified, don't output reqntid directive.
575 unsigned reqntidx, reqntidy, reqntidz;
576 bool specified = false;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000577 if (llvm::getReqNTIDx(F, reqntidx) == false)
578 reqntidx = 1;
579 else
580 specified = true;
581 if (llvm::getReqNTIDy(F, reqntidy) == false)
582 reqntidy = 1;
583 else
584 specified = true;
585 if (llvm::getReqNTIDz(F, reqntidz) == false)
586 reqntidz = 1;
587 else
588 specified = true;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000589
590 if (specified)
Justin Holewinski0497ab12013-03-30 14:29:21 +0000591 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
592 << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000593
594 // If the NVVM IR has some of maxntid* specified, then output
595 // the maxntid directive, and set the unspecified ones to 1.
596 // If none of maxntid* is specified, don't output maxntid directive.
597 unsigned maxntidx, maxntidy, maxntidz;
598 specified = false;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000599 if (llvm::getMaxNTIDx(F, maxntidx) == false)
600 maxntidx = 1;
601 else
602 specified = true;
603 if (llvm::getMaxNTIDy(F, maxntidy) == false)
604 maxntidy = 1;
605 else
606 specified = true;
607 if (llvm::getMaxNTIDz(F, maxntidz) == false)
608 maxntidz = 1;
609 else
610 specified = true;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000611
612 if (specified)
Justin Holewinski0497ab12013-03-30 14:29:21 +0000613 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
614 << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000615
616 unsigned mincta;
617 if (llvm::getMinCTASm(F, mincta))
618 O << ".minnctapersm " << mincta << "\n";
619}
620
Justin Holewinski660597d2013-10-11 12:39:36 +0000621std::string
622NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
623 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000624
Justin Holewinski660597d2013-10-11 12:39:36 +0000625 std::string Name;
626 raw_string_ostream NameStr(Name);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000627
Justin Holewinski660597d2013-10-11 12:39:36 +0000628 VRegRCMap::const_iterator I = VRegMapping.find(RC);
629 assert(I != VRegMapping.end() && "Bad register class");
630 const DenseMap<unsigned, unsigned> &RegMap = I->second;
631
632 VRegMap::const_iterator VI = RegMap.find(Reg);
633 assert(VI != RegMap.end() && "Bad virtual register");
634 unsigned MappedVR = VI->second;
635
636 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
637
638 NameStr.flush();
639 return Name;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000640}
641
Justin Holewinski660597d2013-10-11 12:39:36 +0000642void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
Justin Holewinski0497ab12013-03-30 14:29:21 +0000643 raw_ostream &O) {
Justin Holewinski660597d2013-10-11 12:39:36 +0000644 O << getVirtualRegisterName(vr);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000645}
646
Justin Holewinski0497ab12013-03-30 14:29:21 +0000647void NVPTXAsmPrinter::printVecModifiedImmediate(
648 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
649 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
650 int Imm = (int) MO.getImm();
651 if (0 == strcmp(Modifier, "vecelem"))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000652 O << "_" << vecelem[Imm];
Justin Holewinski0497ab12013-03-30 14:29:21 +0000653 else if (0 == strcmp(Modifier, "vecv4comm1")) {
654 if ((Imm < 0) || (Imm > 3))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000655 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000656 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
657 if ((Imm < 4) || (Imm > 7))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000658 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000659 } else if (0 == strcmp(Modifier, "vecv4pos")) {
660 if (Imm < 0)
661 Imm = 0;
662 O << "_" << vecelem[Imm % 4];
663 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
664 if ((Imm < 0) || (Imm > 1))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000665 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000666 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
667 if ((Imm < 2) || (Imm > 3))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000668 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000669 } else if (0 == strcmp(Modifier, "vecv2pos")) {
670 if (Imm < 0)
671 Imm = 0;
672 O << "_" << vecelem[Imm % 2];
673 } else
Craig Topperbdf39a42012-05-24 07:02:50 +0000674 llvm_unreachable("Unknown Modifier on immediate operand");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000675}
676
Justin Holewinskidc5e3b62013-06-28 17:58:04 +0000677
678
Justin Holewinski0497ab12013-03-30 14:29:21 +0000679void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000680
Justin Holewinski0497ab12013-03-30 14:29:21 +0000681 emitLinkageDirective(F, O);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000682 if (llvm::isKernelFunction(*F))
683 O << ".entry ";
684 else
685 O << ".func ";
686 printReturnValStr(F, O);
Rafael Espindola79858aa2013-10-29 17:07:16 +0000687 O << *getSymbol(F) << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000688 emitFunctionParamList(F, O);
689 O << ";\n";
690}
691
Justin Holewinski0497ab12013-03-30 14:29:21 +0000692static bool usedInGlobalVarDef(const Constant *C) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000693 if (!C)
694 return false;
695
696 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
697 if (GV->getName().str() == "llvm.used")
698 return false;
699 return true;
700 }
701
Justin Holewinski0497ab12013-03-30 14:29:21 +0000702 for (Value::const_use_iterator ui = C->use_begin(), ue = C->use_end();
703 ui != ue; ++ui) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000704 const Constant *C = dyn_cast<Constant>(*ui);
705 if (usedInGlobalVarDef(C))
706 return true;
707 }
708 return false;
709}
710
Justin Holewinski0497ab12013-03-30 14:29:21 +0000711static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000712 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
713 if (othergv->getName().str() == "llvm.used")
714 return true;
715 }
716
717 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
718 if (instr->getParent() && instr->getParent()->getParent()) {
719 const Function *curFunc = instr->getParent()->getParent();
720 if (oneFunc && (curFunc != oneFunc))
721 return false;
722 oneFunc = curFunc;
723 return true;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000724 } else
Justin Holewinskiae556d32012-05-04 20:18:50 +0000725 return false;
726 }
727
728 if (const MDNode *md = dyn_cast<MDNode>(U))
729 if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
Justin Holewinski0497ab12013-03-30 14:29:21 +0000730 (md->getName().str() == "llvm.dbg.sp")))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000731 return true;
732
Justin Holewinski0497ab12013-03-30 14:29:21 +0000733 for (User::const_use_iterator ui = U->use_begin(), ue = U->use_end();
734 ui != ue; ++ui) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000735 if (usedInOneFunc(*ui, oneFunc) == false)
736 return false;
737 }
738 return true;
739}
740
741/* Find out if a global variable can be demoted to local scope.
742 * Currently, this is valid for CUDA shared variables, which have local
743 * scope and global lifetime. So the conditions to check are :
744 * 1. Is the global variable in shared address space?
745 * 2. Does it have internal linkage?
746 * 3. Is the global variable referenced only in one function?
747 */
748static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
749 if (gv->hasInternalLinkage() == false)
750 return false;
751 const PointerType *Pty = gv->getType();
752 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
753 return false;
754
755 const Function *oneFunc = 0;
756
757 bool flag = usedInOneFunc(gv, oneFunc);
758 if (flag == false)
759 return false;
760 if (!oneFunc)
761 return false;
762 f = oneFunc;
763 return true;
764}
765
766static bool useFuncSeen(const Constant *C,
767 llvm::DenseMap<const Function *, bool> &seenMap) {
Justin Holewinski0497ab12013-03-30 14:29:21 +0000768 for (Value::const_use_iterator ui = C->use_begin(), ue = C->use_end();
769 ui != ue; ++ui) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000770 if (const Constant *cu = dyn_cast<Constant>(*ui)) {
771 if (useFuncSeen(cu, seenMap))
772 return true;
773 } else if (const Instruction *I = dyn_cast<Instruction>(*ui)) {
774 const BasicBlock *bb = I->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000775 if (!bb)
776 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000777 const Function *caller = bb->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000778 if (!caller)
779 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000780 if (seenMap.find(caller) != seenMap.end())
781 return true;
782 }
783 }
784 return false;
785}
786
Justin Holewinski01f89f02013-05-20 12:13:32 +0000787void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000788 llvm::DenseMap<const Function *, bool> seenMap;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000789 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000790 const Function *F = FI;
791
792 if (F->isDeclaration()) {
793 if (F->use_empty())
794 continue;
795 if (F->getIntrinsicID())
796 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000797 emitDeclaration(F, O);
798 continue;
799 }
Justin Holewinski0497ab12013-03-30 14:29:21 +0000800 for (Value::const_use_iterator iter = F->use_begin(),
801 iterEnd = F->use_end();
802 iter != iterEnd; ++iter) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000803 if (const Constant *C = dyn_cast<Constant>(*iter)) {
804 if (usedInGlobalVarDef(C)) {
805 // The use is in the initialization of a global variable
806 // that is a function pointer, so print a declaration
807 // for the original function
Justin Holewinskiae556d32012-05-04 20:18:50 +0000808 emitDeclaration(F, O);
809 break;
810 }
811 // Emit a declaration of this function if the function that
812 // uses this constant expr has already been seen.
813 if (useFuncSeen(C, seenMap)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000814 emitDeclaration(F, O);
815 break;
816 }
817 }
818
Justin Holewinski0497ab12013-03-30 14:29:21 +0000819 if (!isa<Instruction>(*iter))
820 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000821 const Instruction *instr = cast<Instruction>(*iter);
822 const BasicBlock *bb = instr->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000823 if (!bb)
824 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000825 const Function *caller = bb->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000826 if (!caller)
827 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000828
829 // If a caller has already been seen, then the caller is
830 // appearing in the module before the callee. so print out
831 // a declaration for the callee.
832 if (seenMap.find(caller) != seenMap.end()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000833 emitDeclaration(F, O);
834 break;
835 }
836 }
837 seenMap[F] = true;
838 }
839}
840
841void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
842 DebugInfoFinder DbgFinder;
843 DbgFinder.processModule(M);
844
Justin Holewinski0497ab12013-03-30 14:29:21 +0000845 unsigned i = 1;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000846 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
Justin Holewinski0497ab12013-03-30 14:29:21 +0000847 E = DbgFinder.compile_unit_end();
848 I != E; ++I) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000849 DICompileUnit DIUnit(*I);
850 StringRef Filename(DIUnit.getFilename());
851 StringRef Dirname(DIUnit.getDirectory());
852 SmallString<128> FullPathName = Dirname;
853 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
854 sys::path::append(FullPathName, Filename);
855 Filename = FullPathName.str();
856 }
857 if (filenameMap.find(Filename.str()) != filenameMap.end())
858 continue;
859 filenameMap[Filename.str()] = i;
860 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
861 ++i;
862 }
863
864 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
Justin Holewinski0497ab12013-03-30 14:29:21 +0000865 E = DbgFinder.subprogram_end();
866 I != E; ++I) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000867 DISubprogram SP(*I);
868 StringRef Filename(SP.getFilename());
869 StringRef Dirname(SP.getDirectory());
870 SmallString<128> FullPathName = Dirname;
871 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
872 sys::path::append(FullPathName, Filename);
873 Filename = FullPathName.str();
874 }
875 if (filenameMap.find(Filename.str()) != filenameMap.end())
876 continue;
877 filenameMap[Filename.str()] = i;
878 ++i;
879 }
880}
881
Justin Holewinski0497ab12013-03-30 14:29:21 +0000882bool NVPTXAsmPrinter::doInitialization(Module &M) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000883
884 SmallString<128> Str1;
885 raw_svector_ostream OS1(Str1);
886
887 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
888 MMI->AnalyzeModule(M);
889
890 // We need to call the parent's one explicitly.
891 //bool Result = AsmPrinter::doInitialization(M);
892
893 // Initialize TargetLoweringObjectFile.
Justin Holewinski0497ab12013-03-30 14:29:21 +0000894 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
895 .Initialize(OutContext, TM);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000896
Rafael Espindola58873562014-01-03 19:21:54 +0000897 Mang = new Mangler(TM.getDataLayout());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000898
899 // Emit header before any dwarf directives are emitted below.
900 emitHeader(M, OS1);
901 OutStreamer.EmitRawText(OS1.str());
902
Justin Holewinskiae556d32012-05-04 20:18:50 +0000903 // Already commented out
904 //bool Result = AsmPrinter::doInitialization(M);
905
Justin Holewinskid2bbdf02013-07-01 13:00:14 +0000906 // Emit module-level inline asm if it exists.
907 if (!M.getModuleInlineAsm().empty()) {
908 OutStreamer.AddComment("Start of file scope inline assembly");
909 OutStreamer.AddBlankLine();
910 OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
911 OutStreamer.AddBlankLine();
912 OutStreamer.AddComment("End of file scope inline assembly");
913 OutStreamer.AddBlankLine();
914 }
915
Justin Holewinskiae556d32012-05-04 20:18:50 +0000916 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
917 recordAndEmitFilenames(M);
918
Justin Holewinski01f89f02013-05-20 12:13:32 +0000919 GlobalsEmitted = false;
920
921 return false; // success
922}
923
924void NVPTXAsmPrinter::emitGlobals(const Module &M) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000925 SmallString<128> Str2;
926 raw_svector_ostream OS2(Str2);
927
928 emitDeclarations(M, OS2);
929
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000930 // As ptxas does not support forward references of globals, we need to first
931 // sort the list of module-level globals in def-use order. We visit each
932 // global variable in order, and ensure that we emit it *after* its dependent
933 // globals. We use a little extra memory maintaining both a set and a list to
934 // have fast searches while maintaining a strict ordering.
Justin Holewinski01f89f02013-05-20 12:13:32 +0000935 SmallVector<const GlobalVariable *, 8> Globals;
936 DenseSet<const GlobalVariable *> GVVisited;
937 DenseSet<const GlobalVariable *> GVVisiting;
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000938
939 // Visit each global variable, in order
Justin Holewinski01f89f02013-05-20 12:13:32 +0000940 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
941 I != E; ++I)
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000942 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
943
Justin Holewinski0497ab12013-03-30 14:29:21 +0000944 assert(GVVisited.size() == M.getGlobalList().size() &&
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000945 "Missed a global variable");
946 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
947
948 // Print out module-level global variables in proper order
949 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
950 printModuleLevelGV(Globals[i], OS2);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000951
952 OS2 << '\n';
953
954 OutStreamer.EmitRawText(OS2.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000955}
956
Justin Holewinski0497ab12013-03-30 14:29:21 +0000957void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000958 O << "//\n";
959 O << "// Generated by LLVM NVPTX Back-End\n";
960 O << "//\n";
961 O << "\n";
962
Justin Holewinski1812ee92012-11-12 03:16:43 +0000963 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
964 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000965
966 O << ".target ";
967 O << nvptxSubtarget.getTargetName();
968
969 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
970 O << ", texmode_independent";
971 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
972 if (!nvptxSubtarget.hasDouble())
973 O << ", map_f64_to_f32";
974 }
975
976 if (MAI->doesSupportDebugInformation())
977 O << ", debug";
978
979 O << "\n";
980
981 O << ".address_size ";
982 if (nvptxSubtarget.is64Bit())
983 O << "64";
984 else
985 O << "32";
986 O << "\n";
987
988 O << "\n";
989}
990
991bool NVPTXAsmPrinter::doFinalization(Module &M) {
Justin Holewinski01f89f02013-05-20 12:13:32 +0000992
993 // If we did not emit any functions, then the global declarations have not
994 // yet been emitted.
995 if (!GlobalsEmitted) {
996 emitGlobals(M);
997 GlobalsEmitted = true;
998 }
999
Justin Holewinskiae556d32012-05-04 20:18:50 +00001000 // XXX Temproarily remove global variables so that doFinalization() will not
1001 // emit them again (global variables are emitted at beginning).
1002
1003 Module::GlobalListType &global_list = M.getGlobalList();
1004 int i, n = global_list.size();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001005 GlobalVariable **gv_array = new GlobalVariable *[n];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001006
1007 // first, back-up GlobalVariable in gv_array
1008 i = 0;
1009 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001010 I != E; ++I)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001011 gv_array[i++] = &*I;
1012
1013 // second, empty global_list
1014 while (!global_list.empty())
1015 global_list.remove(global_list.begin());
1016
1017 // call doFinalization
1018 bool ret = AsmPrinter::doFinalization(M);
1019
1020 // now we restore global variables
Justin Holewinski0497ab12013-03-30 14:29:21 +00001021 for (i = 0; i < n; i++)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001022 global_list.insert(global_list.end(), gv_array[i]);
1023
1024 delete[] gv_array;
1025 return ret;
1026
Justin Holewinskiae556d32012-05-04 20:18:50 +00001027 //bool Result = AsmPrinter::doFinalization(M);
1028 // Instead of calling the parents doFinalization, we may
1029 // clone parents doFinalization and customize here.
1030 // Currently, we if NVISA out the EmitGlobals() in
1031 // parent's doFinalization, which is too intrusive.
1032 //
1033 // Same for the doInitialization.
1034 //return Result;
1035}
1036
1037// This function emits appropriate linkage directives for
1038// functions and global variables.
1039//
1040// extern function declaration -> .extern
1041// extern function definition -> .visible
1042// external global variable with init -> .visible
1043// external without init -> .extern
1044// appending -> not allowed, assert.
1045
Justin Holewinski0497ab12013-03-30 14:29:21 +00001046void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1047 raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001048 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1049 if (V->hasExternalLinkage()) {
1050 if (isa<GlobalVariable>(V)) {
1051 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1052 if (GVar) {
1053 if (GVar->hasInitializer())
1054 O << ".visible ";
1055 else
1056 O << ".extern ";
1057 }
1058 } else if (V->isDeclaration())
1059 O << ".extern ";
1060 else
1061 O << ".visible ";
1062 } else if (V->hasAppendingLinkage()) {
1063 std::string msg;
1064 msg.append("Error: ");
1065 msg.append("Symbol ");
1066 if (V->hasName())
1067 msg.append(V->getName().str());
1068 msg.append("has unsupported appending linkage type");
1069 llvm_unreachable(msg.c_str());
1070 }
1071 }
1072}
1073
Justin Holewinski01f89f02013-05-20 12:13:32 +00001074void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1075 raw_ostream &O,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001076 bool processDemoted) {
1077
1078 // Skip meta data
1079 if (GVar->hasSection()) {
1080 if (GVar->getSection() == "llvm.metadata")
1081 return;
1082 }
1083
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001084 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001085
1086 // GlobalVariables are always constant pointers themselves.
1087 const PointerType *PTy = GVar->getType();
1088 Type *ETy = PTy->getElementType();
1089
1090 if (GVar->hasExternalLinkage()) {
1091 if (GVar->hasInitializer())
1092 O << ".visible ";
1093 else
1094 O << ".extern ";
1095 }
1096
1097 if (llvm::isTexture(*GVar)) {
1098 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1099 return;
1100 }
1101
1102 if (llvm::isSurface(*GVar)) {
1103 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1104 return;
1105 }
1106
1107 if (GVar->isDeclaration()) {
1108 // (extern) declarations, no definition or initializer
1109 // Currently the only known declaration is for an automatic __local
1110 // (.shared) promoted to global.
1111 emitPTXGlobalVariable(GVar, O);
1112 O << ";\n";
1113 return;
1114 }
1115
1116 if (llvm::isSampler(*GVar)) {
1117 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1118
Justin Holewinski01f89f02013-05-20 12:13:32 +00001119 const Constant *Initializer = NULL;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001120 if (GVar->hasInitializer())
1121 Initializer = GVar->getInitializer();
Justin Holewinski01f89f02013-05-20 12:13:32 +00001122 const ConstantInt *CI = NULL;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001123 if (Initializer)
1124 CI = dyn_cast<ConstantInt>(Initializer);
1125 if (CI) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001126 unsigned sample = CI->getZExtValue();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001127
1128 O << " = { ";
1129
Justin Holewinski0497ab12013-03-30 14:29:21 +00001130 for (int i = 0,
1131 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1132 i < 3; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001133 O << "addr_mode_" << i << " = ";
1134 switch (addr) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001135 case 0:
1136 O << "wrap";
1137 break;
1138 case 1:
1139 O << "clamp_to_border";
1140 break;
1141 case 2:
1142 O << "clamp_to_edge";
1143 break;
1144 case 3:
1145 O << "wrap";
1146 break;
1147 case 4:
1148 O << "mirror";
1149 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001150 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001151 O << ", ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001152 }
1153 O << "filter_mode = ";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001154 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1155 case 0:
1156 O << "nearest";
1157 break;
1158 case 1:
1159 O << "linear";
1160 break;
1161 case 2:
1162 assert(0 && "Anisotropic filtering is not supported");
1163 default:
1164 O << "nearest";
1165 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001166 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001167 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001168 O << ", force_unnormalized_coords = 1";
1169 }
1170 O << " }";
1171 }
1172
1173 O << ";\n";
1174 return;
1175 }
1176
1177 if (GVar->hasPrivateLinkage()) {
1178
1179 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1180 return;
1181
1182 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1183 if (!strncmp(GVar->getName().data(), "filename", 8))
1184 return;
1185 if (GVar->use_empty())
1186 return;
1187 }
1188
1189 const Function *demotedFunc = 0;
1190 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1191 O << "// " << GVar->getName().str() << " has been demoted\n";
1192 if (localDecls.find(demotedFunc) != localDecls.end())
1193 localDecls[demotedFunc].push_back(GVar);
1194 else {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001195 std::vector<const GlobalVariable *> temp;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001196 temp.push_back(GVar);
1197 localDecls[demotedFunc] = temp;
1198 }
1199 return;
1200 }
1201
1202 O << ".";
1203 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1204 if (GVar->getAlignment() == 0)
1205 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1206 else
1207 O << " .align " << GVar->getAlignment();
1208
Rafael Espindola08013342013-12-07 19:34:20 +00001209 if (ETy->isSingleValueType()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001210 O << " .";
Justin Holewinski700b6fa2013-05-20 12:13:28 +00001211 // Special case: ABI requires that we use .u8 for predicates
1212 if (ETy->isIntegerTy(1))
1213 O << "u8";
1214 else
1215 O << getPTXFundamentalTypeStr(ETy, false);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001216 O << " ";
Rafael Espindola79858aa2013-10-29 17:07:16 +00001217 O << *getSymbol(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001218
1219 // Ptx allows variable initilization only for constant and global state
1220 // spaces.
1221 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
Justin Holewinski0497ab12013-03-30 14:29:21 +00001222 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1223 GVar->hasInitializer()) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001224 const Constant *Initializer = GVar->getInitializer();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001225 if (!Initializer->isNullValue()) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001226 O << " = ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001227 printScalarConstant(Initializer, O);
1228 }
1229 }
1230 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001231 unsigned int ElementSize = 0;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001232
1233 // Although PTX has direct support for struct type and array type and
1234 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1235 // targets that support these high level field accesses. Structs, arrays
1236 // and vectors are lowered into arrays of bytes.
1237 switch (ETy->getTypeID()) {
1238 case Type::StructTyID:
1239 case Type::ArrayTyID:
1240 case Type::VectorTyID:
1241 ElementSize = TD->getTypeStoreSize(ETy);
1242 // Ptx allows variable initilization only for constant and
1243 // global state spaces.
1244 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
Justin Holewinski0497ab12013-03-30 14:29:21 +00001245 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1246 GVar->hasInitializer()) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001247 const Constant *Initializer = GVar->getInitializer();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001248 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001249 AggBuffer aggBuffer(ElementSize, O, *this);
1250 bufferAggregateConstant(Initializer, &aggBuffer);
1251 if (aggBuffer.numSymbols) {
1252 if (nvptxSubtarget.is64Bit()) {
Rafael Espindola79858aa2013-10-29 17:07:16 +00001253 O << " .u64 " << *getSymbol(GVar) << "[";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001254 O << ElementSize / 8;
1255 } else {
Rafael Espindola79858aa2013-10-29 17:07:16 +00001256 O << " .u32 " << *getSymbol(GVar) << "[";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001257 O << ElementSize / 4;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001258 }
1259 O << "]";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001260 } else {
Rafael Espindola79858aa2013-10-29 17:07:16 +00001261 O << " .b8 " << *getSymbol(GVar) << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001262 O << ElementSize;
1263 O << "]";
1264 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001265 O << " = {";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001266 aggBuffer.print();
1267 O << "}";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001268 } else {
Rafael Espindola79858aa2013-10-29 17:07:16 +00001269 O << " .b8 " << *getSymbol(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001270 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001271 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001272 O << ElementSize;
1273 O << "]";
1274 }
1275 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001276 } else {
Rafael Espindola79858aa2013-10-29 17:07:16 +00001277 O << " .b8 " << *getSymbol(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001278 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001279 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001280 O << ElementSize;
1281 O << "]";
1282 }
1283 }
1284 break;
1285 default:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001286 assert(0 && "type not supported yet");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001287 }
1288
1289 }
1290 O << ";\n";
1291}
1292
1293void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1294 if (localDecls.find(f) == localDecls.end())
1295 return;
1296
Justin Holewinski01f89f02013-05-20 12:13:32 +00001297 std::vector<const GlobalVariable *> &gvars = localDecls[f];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001298
Justin Holewinski0497ab12013-03-30 14:29:21 +00001299 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001300 O << "\t// demoted variable\n\t";
1301 printModuleLevelGV(gvars[i], O, true);
1302 }
1303}
1304
1305void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1306 raw_ostream &O) const {
1307 switch (AddressSpace) {
1308 case llvm::ADDRESS_SPACE_LOCAL:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001309 O << "local";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001310 break;
1311 case llvm::ADDRESS_SPACE_GLOBAL:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001312 O << "global";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001313 break;
1314 case llvm::ADDRESS_SPACE_CONST:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001315 O << "const";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001316 break;
1317 case llvm::ADDRESS_SPACE_SHARED:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001318 O << "shared";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001319 break;
1320 default:
Justin Holewinski36a50992013-02-09 13:34:15 +00001321 report_fatal_error("Bad address space found while emitting PTX");
1322 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001323 }
1324}
1325
Justin Holewinski0497ab12013-03-30 14:29:21 +00001326std::string
1327NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001328 switch (Ty->getTypeID()) {
1329 default:
1330 llvm_unreachable("unexpected type");
1331 break;
1332 case Type::IntegerTyID: {
1333 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1334 if (NumBits == 1)
1335 return "pred";
1336 else if (NumBits <= 64) {
1337 std::string name = "u";
1338 return name + utostr(NumBits);
1339 } else {
1340 llvm_unreachable("Integer too large");
1341 break;
1342 }
1343 break;
1344 }
1345 case Type::FloatTyID:
1346 return "f32";
1347 case Type::DoubleTyID:
1348 return "f64";
1349 case Type::PointerTyID:
1350 if (nvptxSubtarget.is64Bit())
Justin Holewinski0497ab12013-03-30 14:29:21 +00001351 if (useB4PTR)
1352 return "b64";
1353 else
1354 return "u64";
1355 else if (useB4PTR)
1356 return "b32";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001357 else
Justin Holewinski0497ab12013-03-30 14:29:21 +00001358 return "u32";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001359 }
1360 llvm_unreachable("unexpected type");
1361 return NULL;
1362}
1363
Justin Holewinski0497ab12013-03-30 14:29:21 +00001364void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001365 raw_ostream &O) {
1366
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001367 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001368
1369 // GlobalVariables are always constant pointers themselves.
1370 const PointerType *PTy = GVar->getType();
1371 Type *ETy = PTy->getElementType();
1372
1373 O << ".";
1374 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1375 if (GVar->getAlignment() == 0)
1376 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1377 else
1378 O << " .align " << GVar->getAlignment();
1379
Rafael Espindola08013342013-12-07 19:34:20 +00001380 if (ETy->isSingleValueType()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001381 O << " .";
1382 O << getPTXFundamentalTypeStr(ETy);
1383 O << " ";
Rafael Espindola79858aa2013-10-29 17:07:16 +00001384 O << *getSymbol(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001385 return;
1386 }
1387
Justin Holewinski0497ab12013-03-30 14:29:21 +00001388 int64_t ElementSize = 0;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001389
1390 // Although PTX has direct support for struct type and array type and LLVM IR
1391 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1392 // support these high level field accesses. Structs and arrays are lowered
1393 // into arrays of bytes.
1394 switch (ETy->getTypeID()) {
1395 case Type::StructTyID:
1396 case Type::ArrayTyID:
1397 case Type::VectorTyID:
1398 ElementSize = TD->getTypeStoreSize(ETy);
Rafael Espindola79858aa2013-10-29 17:07:16 +00001399 O << " .b8 " << *getSymbol(GVar) << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001400 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001401 O << itostr(ElementSize);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001402 }
1403 O << "]";
1404 break;
1405 default:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001406 assert(0 && "type not supported yet");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001407 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001408 return;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001409}
1410
Justin Holewinski0497ab12013-03-30 14:29:21 +00001411static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
Rafael Espindola08013342013-12-07 19:34:20 +00001412 if (Ty->isSingleValueType())
Justin Holewinskiae556d32012-05-04 20:18:50 +00001413 return TD->getPrefTypeAlignment(Ty);
1414
1415 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1416 if (ATy)
1417 return getOpenCLAlignment(TD, ATy->getElementType());
1418
1419 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1420 if (VTy) {
1421 Type *ETy = VTy->getElementType();
1422 unsigned int numE = VTy->getNumElements();
1423 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1424 if (numE == 3)
Justin Holewinski0497ab12013-03-30 14:29:21 +00001425 return 4 * alignE;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001426 else
Justin Holewinski0497ab12013-03-30 14:29:21 +00001427 return numE * alignE;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001428 }
1429
1430 const StructType *STy = dyn_cast<StructType>(Ty);
1431 if (STy) {
1432 unsigned int alignStruct = 1;
1433 // Go through each element of the struct and find the
1434 // largest alignment.
Justin Holewinski0497ab12013-03-30 14:29:21 +00001435 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001436 Type *ETy = STy->getElementType(i);
1437 unsigned int align = getOpenCLAlignment(TD, ETy);
1438 if (align > alignStruct)
1439 alignStruct = align;
1440 }
1441 return alignStruct;
1442 }
1443
1444 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1445 if (FTy)
Chandler Carruth5da3f052012-11-01 09:14:31 +00001446 return TD->getPointerPrefAlignment();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001447 return TD->getPrefTypeAlignment(Ty);
1448}
1449
1450void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1451 int paramIndex, raw_ostream &O) {
1452 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1453 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
Rafael Espindola79858aa2013-10-29 17:07:16 +00001454 O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001455 else {
1456 std::string argName = I->getName();
1457 const char *p = argName.c_str();
1458 while (*p) {
1459 if (*p == '.')
1460 O << "_";
1461 else
1462 O << *p;
1463 p++;
1464 }
1465 }
1466}
1467
1468void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1469 Function::const_arg_iterator I, E;
1470 int i = 0;
1471
1472 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1473 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1474 O << *CurrentFnSym << "_param_" << paramIndex;
1475 return;
1476 }
1477
1478 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001479 if (i == paramIndex) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001480 printParamName(I, paramIndex, O);
1481 return;
1482 }
1483 }
1484 llvm_unreachable("paramIndex out of bound");
1485}
1486
Justin Holewinski0497ab12013-03-30 14:29:21 +00001487void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001488 const DataLayout *TD = TM.getDataLayout();
Bill Wendlinge94d8432012-12-07 23:16:57 +00001489 const AttributeSet &PAL = F->getAttributes();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001490 const TargetLowering *TLI = TM.getTargetLowering();
1491 Function::const_arg_iterator I, E;
1492 unsigned paramIndex = 0;
1493 bool first = true;
1494 bool isKernelFunc = llvm::isKernelFunction(*F);
1495 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1496 MVT thePointerTy = TLI->getPointerTy();
1497
1498 O << "(\n";
1499
1500 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
Justin Holewinskie9884092013-03-24 21:17:47 +00001501 Type *Ty = I->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001502
1503 if (!first)
1504 O << ",\n";
1505
1506 first = false;
1507
1508 // Handle image/sampler parameters
1509 if (llvm::isSampler(*I) || llvm::isImage(*I)) {
1510 if (llvm::isImage(*I)) {
1511 std::string sname = I->getName();
1512 if (llvm::isImageWriteOnly(*I))
Rafael Espindola79858aa2013-10-29 17:07:16 +00001513 O << "\t.param .surfref " << *getSymbol(F) << "_param_"
Justin Holewinski4c47d872013-05-20 16:42:18 +00001514 << paramIndex;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001515 else // Default image is read_only
Rafael Espindola79858aa2013-10-29 17:07:16 +00001516 O << "\t.param .texref " << *getSymbol(F) << "_param_"
Justin Holewinski4c47d872013-05-20 16:42:18 +00001517 << paramIndex;
Justin Holewinski0497ab12013-03-30 14:29:21 +00001518 } else // Should be llvm::isSampler(*I)
Rafael Espindola79858aa2013-10-29 17:07:16 +00001519 O << "\t.param .samplerref " << *getSymbol(F) << "_param_"
Justin Holewinski0497ab12013-03-30 14:29:21 +00001520 << paramIndex;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001521 continue;
1522 }
1523
Justin Holewinski0497ab12013-03-30 14:29:21 +00001524 if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
Gautam Chakrabarti2c283402014-01-28 18:35:29 +00001525 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1526 // Just print .param .align <a> .b8 .param[size];
Justin Holewinskie9884092013-03-24 21:17:47 +00001527 // <a> = PAL.getparamalignment
1528 // size = typeallocsize of element type
Justin Holewinski0497ab12013-03-30 14:29:21 +00001529 unsigned align = PAL.getParamAlignment(paramIndex + 1);
Justin Holewinskie9884092013-03-24 21:17:47 +00001530 if (align == 0)
1531 align = TD->getABITypeAlignment(Ty);
1532
1533 unsigned sz = TD->getTypeAllocSize(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001534 O << "\t.param .align " << align << " .b8 ";
Justin Holewinskie9884092013-03-24 21:17:47 +00001535 printParamName(I, paramIndex, O);
1536 O << "[" << sz << "]";
1537
1538 continue;
1539 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001540 // Just a scalar
1541 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1542 if (isKernelFunc) {
1543 if (PTy) {
1544 // Special handling for pointer arguments to kernel
1545 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1546
1547 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1548 Type *ETy = PTy->getElementType();
1549 int addrSpace = PTy->getAddressSpace();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001550 switch (addrSpace) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001551 default:
1552 O << ".ptr ";
1553 break;
Justin Holewinskib96d1392013-06-10 13:29:47 +00001554 case llvm::ADDRESS_SPACE_CONST:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001555 O << ".ptr .const ";
1556 break;
1557 case llvm::ADDRESS_SPACE_SHARED:
1558 O << ".ptr .shared ";
1559 break;
1560 case llvm::ADDRESS_SPACE_GLOBAL:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001561 O << ".ptr .global ";
1562 break;
1563 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001564 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001565 }
1566 printParamName(I, paramIndex, O);
1567 continue;
1568 }
1569
1570 // non-pointer scalar to kernel func
Justin Holewinski700b6fa2013-05-20 12:13:28 +00001571 O << "\t.param .";
1572 // Special case: predicate operands become .u8 types
1573 if (Ty->isIntegerTy(1))
1574 O << "u8";
1575 else
1576 O << getPTXFundamentalTypeStr(Ty);
1577 O << " ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001578 printParamName(I, paramIndex, O);
1579 continue;
1580 }
1581 // Non-kernel function, just print .param .b<size> for ABI
Alp Tokerf907b892013-12-05 05:44:44 +00001582 // and .reg .b<size> for non-ABI
Justin Holewinskiae556d32012-05-04 20:18:50 +00001583 unsigned sz = 0;
1584 if (isa<IntegerType>(Ty)) {
1585 sz = cast<IntegerType>(Ty)->getBitWidth();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001586 if (sz < 32)
1587 sz = 32;
1588 } else if (isa<PointerType>(Ty))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001589 sz = thePointerTy.getSizeInBits();
1590 else
1591 sz = Ty->getPrimitiveSizeInBits();
1592 if (isABI)
1593 O << "\t.param .b" << sz << " ";
1594 else
1595 O << "\t.reg .b" << sz << " ";
1596 printParamName(I, paramIndex, O);
1597 continue;
1598 }
1599
1600 // param has byVal attribute. So should be a pointer
1601 const PointerType *PTy = dyn_cast<PointerType>(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001602 assert(PTy && "Param with byval attribute should be a pointer type");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001603 Type *ETy = PTy->getElementType();
1604
1605 if (isABI || isKernelFunc) {
Gautam Chakrabarti2c283402014-01-28 18:35:29 +00001606 // Just print .param .align <a> .b8 .param[size];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001607 // <a> = PAL.getparamalignment
1608 // size = typeallocsize of element type
Justin Holewinski0497ab12013-03-30 14:29:21 +00001609 unsigned align = PAL.getParamAlignment(paramIndex + 1);
Justin Holewinski2dc9d072012-11-09 23:50:24 +00001610 if (align == 0)
1611 align = TD->getABITypeAlignment(ETy);
1612
Justin Holewinskiae556d32012-05-04 20:18:50 +00001613 unsigned sz = TD->getTypeAllocSize(ETy);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001614 O << "\t.param .align " << align << " .b8 ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001615 printParamName(I, paramIndex, O);
1616 O << "[" << sz << "]";
1617 continue;
1618 } else {
1619 // Split the ETy into constituent parts and
1620 // print .param .b<size> <name> for each part.
1621 // Further, if a part is vector, print the above for
1622 // each vector element.
1623 SmallVector<EVT, 16> vtparts;
1624 ComputeValueVTs(*TLI, ETy, vtparts);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001625 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001626 unsigned elems = 1;
1627 EVT elemtype = vtparts[i];
1628 if (vtparts[i].isVector()) {
1629 elems = vtparts[i].getVectorNumElements();
1630 elemtype = vtparts[i].getVectorElementType();
1631 }
1632
Justin Holewinski0497ab12013-03-30 14:29:21 +00001633 for (unsigned j = 0, je = elems; j != je; ++j) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001634 unsigned sz = elemtype.getSizeInBits();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001635 if (elemtype.isInteger() && (sz < 32))
1636 sz = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001637 O << "\t.reg .b" << sz << " ";
1638 printParamName(I, paramIndex, O);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001639 if (j < je - 1)
1640 O << ",\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001641 ++paramIndex;
1642 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001643 if (i < e - 1)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001644 O << ",\n";
1645 }
1646 --paramIndex;
1647 continue;
1648 }
1649 }
1650
1651 O << "\n)\n";
1652}
1653
1654void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1655 raw_ostream &O) {
1656 const Function *F = MF.getFunction();
1657 emitFunctionParamList(F, O);
1658}
1659
Justin Holewinski0497ab12013-03-30 14:29:21 +00001660void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1661 const MachineFunction &MF) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001662 SmallString<128> Str;
1663 raw_svector_ostream O(Str);
1664
1665 // Map the global virtual register number to a register class specific
1666 // virtual register number starting from 1 with that class.
1667 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1668 //unsigned numRegClasses = TRI->getNumRegClasses();
1669
1670 // Emit the Fake Stack Object
1671 const MachineFrameInfo *MFI = MF.getFrameInfo();
1672 int NumBytes = (int) MFI->getStackSize();
1673 if (NumBytes) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001674 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1675 << getFunctionNumber() << "[" << NumBytes << "];\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001676 if (nvptxSubtarget.is64Bit()) {
1677 O << "\t.reg .b64 \t%SP;\n";
1678 O << "\t.reg .b64 \t%SPL;\n";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001679 } else {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001680 O << "\t.reg .b32 \t%SP;\n";
1681 O << "\t.reg .b32 \t%SPL;\n";
1682 }
1683 }
1684
1685 // Go through all virtual registers to establish the mapping between the
1686 // global virtual
1687 // register number and the per class virtual register number.
1688 // We use the per class virtual register number in the ptx output.
1689 unsigned int numVRs = MRI->getNumVirtRegs();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001690 for (unsigned i = 0; i < numVRs; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001691 unsigned int vr = TRI->index2VirtReg(i);
1692 const TargetRegisterClass *RC = MRI->getRegClass(vr);
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001693 DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001694 int n = regmap.size();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001695 regmap.insert(std::make_pair(vr, n + 1));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001696 }
1697
1698 // Emit register declarations
1699 // @TODO: Extract out the real register usage
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001700 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1701 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1702 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1703 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1704 // O << "\t.reg .s64 %rl<" << NVPTXNumRegisters << ">;\n";
1705 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1706 // O << "\t.reg .f64 %fl<" << NVPTXNumRegisters << ">;\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001707
1708 // Emit declaration of the virtual registers or 'physical' registers for
1709 // each register class
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001710 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1711 const TargetRegisterClass *RC = TRI->getRegClass(i);
1712 DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
1713 std::string rcname = getNVPTXRegClassName(RC);
1714 std::string rcStr = getNVPTXRegClassStr(RC);
1715 int n = regmap.size();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001716
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001717 // Only declare those registers that may be used.
1718 if (n) {
1719 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1720 << ">;\n";
1721 }
1722 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001723
1724 OutStreamer.EmitRawText(O.str());
1725}
1726
Justin Holewinskiae556d32012-05-04 20:18:50 +00001727void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001728 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
Justin Holewinskiae556d32012-05-04 20:18:50 +00001729 bool ignored;
1730 unsigned int numHex;
1731 const char *lead;
1732
Justin Holewinski0497ab12013-03-30 14:29:21 +00001733 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001734 numHex = 8;
1735 lead = "0f";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001736 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001737 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1738 numHex = 16;
1739 lead = "0d";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001740 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001741 } else
1742 llvm_unreachable("unsupported fp type");
1743
1744 APInt API = APF.bitcastToAPInt();
1745 std::string hexstr(utohexstr(API.getZExtValue()));
1746 O << lead;
1747 if (hexstr.length() < numHex)
1748 O << std::string(numHex - hexstr.length(), '0');
1749 O << utohexstr(API.getZExtValue());
1750}
1751
Justin Holewinski01f89f02013-05-20 12:13:32 +00001752void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1753 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001754 O << CI->getValue();
1755 return;
1756 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001757 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001758 printFPConstant(CFP, O);
1759 return;
1760 }
1761 if (isa<ConstantPointerNull>(CPV)) {
1762 O << "0";
1763 return;
1764 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001765 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
Rafael Espindola79858aa2013-10-29 17:07:16 +00001766 O << *getSymbol(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001767 return;
1768 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001769 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1770 const Value *v = Cexpr->stripPointerCasts();
1771 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
Rafael Espindola79858aa2013-10-29 17:07:16 +00001772 O << *getSymbol(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001773 return;
1774 } else {
1775 O << *LowerConstant(CPV, *this);
1776 return;
1777 }
1778 }
1779 llvm_unreachable("Not scalar type found in printScalarConstant()");
1780}
1781
Justin Holewinski01f89f02013-05-20 12:13:32 +00001782void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001783 AggBuffer *aggBuffer) {
1784
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001785 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001786
1787 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1788 int s = TD->getTypeAllocSize(CPV->getType());
Justin Holewinski0497ab12013-03-30 14:29:21 +00001789 if (s < Bytes)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001790 s = Bytes;
1791 aggBuffer->addZeros(s);
1792 return;
1793 }
1794
1795 unsigned char *ptr;
1796 switch (CPV->getType()->getTypeID()) {
1797
1798 case Type::IntegerTyID: {
1799 const Type *ETy = CPV->getType();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001800 if (ETy == Type::getInt8Ty(CPV->getContext())) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001801 unsigned char c =
1802 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1803 ptr = &c;
1804 aggBuffer->addBytes(ptr, 1, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001805 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1806 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1807 ptr = (unsigned char *)&int16;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001808 aggBuffer->addBytes(ptr, 2, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001809 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001810 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001811 int int32 = (int)(constInt->getZExtValue());
1812 ptr = (unsigned char *)&int32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001813 aggBuffer->addBytes(ptr, 4, Bytes);
1814 break;
Justin Holewinski01f89f02013-05-20 12:13:32 +00001815 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1816 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
Justin Holewinski0497ab12013-03-30 14:29:21 +00001817 ConstantFoldConstantExpression(Cexpr, TD))) {
1818 int int32 = (int)(constInt->getZExtValue());
1819 ptr = (unsigned char *)&int32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001820 aggBuffer->addBytes(ptr, 4, Bytes);
1821 break;
1822 }
1823 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1824 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1825 aggBuffer->addSymbol(v);
1826 aggBuffer->addZeros(4);
1827 break;
1828 }
1829 }
Craig Topperbdf39a42012-05-24 07:02:50 +00001830 llvm_unreachable("unsupported integer const type");
Justin Holewinski0497ab12013-03-30 14:29:21 +00001831 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001832 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001833 long long int64 = (long long)(constInt->getZExtValue());
1834 ptr = (unsigned char *)&int64;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001835 aggBuffer->addBytes(ptr, 8, Bytes);
1836 break;
Justin Holewinski01f89f02013-05-20 12:13:32 +00001837 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1838 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
Justin Holewinski0497ab12013-03-30 14:29:21 +00001839 ConstantFoldConstantExpression(Cexpr, TD))) {
1840 long long int64 = (long long)(constInt->getZExtValue());
1841 ptr = (unsigned char *)&int64;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001842 aggBuffer->addBytes(ptr, 8, Bytes);
1843 break;
1844 }
1845 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1846 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1847 aggBuffer->addSymbol(v);
1848 aggBuffer->addZeros(8);
1849 break;
1850 }
1851 }
1852 llvm_unreachable("unsupported integer const type");
Craig Topperbdf39a42012-05-24 07:02:50 +00001853 } else
Justin Holewinskiae556d32012-05-04 20:18:50 +00001854 llvm_unreachable("unsupported integer const type");
1855 break;
1856 }
1857 case Type::FloatTyID:
1858 case Type::DoubleTyID: {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001859 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001860 const Type *Ty = CFP->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001861 if (Ty == Type::getFloatTy(CPV->getContext())) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001862 float float32 = (float) CFP->getValueAPF().convertToFloat();
1863 ptr = (unsigned char *)&float32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001864 aggBuffer->addBytes(ptr, 4, Bytes);
1865 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1866 double float64 = CFP->getValueAPF().convertToDouble();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001867 ptr = (unsigned char *)&float64;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001868 aggBuffer->addBytes(ptr, 8, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001869 } else {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001870 llvm_unreachable("unsupported fp const type");
1871 }
1872 break;
1873 }
1874 case Type::PointerTyID: {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001875 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001876 aggBuffer->addSymbol(GVar);
Justin Holewinski01f89f02013-05-20 12:13:32 +00001877 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1878 const Value *v = Cexpr->stripPointerCasts();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001879 aggBuffer->addSymbol(v);
1880 }
1881 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1882 aggBuffer->addZeros(s);
1883 break;
1884 }
1885
1886 case Type::ArrayTyID:
1887 case Type::VectorTyID:
1888 case Type::StructTyID: {
1889 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
Justin Holewinski95564bd2013-09-19 12:51:46 +00001890 isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001891 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1892 bufferAggregateConstant(CPV, aggBuffer);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001893 if (Bytes > ElementSize)
1894 aggBuffer->addZeros(Bytes - ElementSize);
1895 } else if (isa<ConstantAggregateZero>(CPV))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001896 aggBuffer->addZeros(Bytes);
1897 else
1898 llvm_unreachable("Unexpected Constant type");
1899 break;
1900 }
1901
1902 default:
1903 llvm_unreachable("unsupported type");
1904 }
1905}
1906
Justin Holewinski01f89f02013-05-20 12:13:32 +00001907void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001908 AggBuffer *aggBuffer) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001909 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001910 int Bytes;
1911
1912 // Old constants
1913 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1914 if (CPV->getNumOperands())
1915 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1916 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1917 return;
1918 }
1919
1920 if (const ConstantDataSequential *CDS =
Justin Holewinski0497ab12013-03-30 14:29:21 +00001921 dyn_cast<ConstantDataSequential>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001922 if (CDS->getNumElements())
1923 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1924 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1925 aggBuffer);
1926 return;
1927 }
1928
Justin Holewinskiae556d32012-05-04 20:18:50 +00001929 if (isa<ConstantStruct>(CPV)) {
1930 if (CPV->getNumOperands()) {
1931 StructType *ST = cast<StructType>(CPV->getType());
1932 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001933 if (i == (e - 1))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001934 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
Justin Holewinski0497ab12013-03-30 14:29:21 +00001935 TD->getTypeAllocSize(ST) -
1936 TD->getStructLayout(ST)->getElementOffset(i);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001937 else
Justin Holewinski0497ab12013-03-30 14:29:21 +00001938 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1939 TD->getStructLayout(ST)->getElementOffset(i);
1940 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001941 }
1942 }
1943 return;
1944 }
Craig Topperbdf39a42012-05-24 07:02:50 +00001945 llvm_unreachable("unsupported constant type in printAggregateConstant()");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001946}
1947
1948// buildTypeNameMap - Run through symbol table looking for type names.
1949//
1950
Justin Holewinskiae556d32012-05-04 20:18:50 +00001951bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1952
1953 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1954
Justin Holewinski0497ab12013-03-30 14:29:21 +00001955 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1956 !PI->second.compare("struct._image2d_t") ||
1957 !PI->second.compare("struct._image3d_t")))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001958 return true;
1959
1960 return false;
1961}
1962
Justin Holewinskiae556d32012-05-04 20:18:50 +00001963
Justin Holewinski0497ab12013-03-30 14:29:21 +00001964bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1965 switch (MI.getOpcode()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001966 default:
1967 return false;
Justin Holewinski0497ab12013-03-30 14:29:21 +00001968 case NVPTX::CallArgBeginInst:
1969 case NVPTX::CallArgEndInst0:
1970 case NVPTX::CallArgEndInst1:
1971 case NVPTX::CallArgF32:
1972 case NVPTX::CallArgF64:
1973 case NVPTX::CallArgI16:
1974 case NVPTX::CallArgI32:
1975 case NVPTX::CallArgI32imm:
1976 case NVPTX::CallArgI64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001977 case NVPTX::CallArgParam:
1978 case NVPTX::CallVoidInst:
1979 case NVPTX::CallVoidInstReg:
1980 case NVPTX::Callseq_End:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001981 case NVPTX::CallVoidInstReg64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001982 case NVPTX::DeclareParamInst:
1983 case NVPTX::DeclareRetMemInst:
1984 case NVPTX::DeclareRetRegInst:
1985 case NVPTX::DeclareRetScalarInst:
1986 case NVPTX::DeclareScalarParamInst:
1987 case NVPTX::DeclareScalarRegInst:
1988 case NVPTX::StoreParamF32:
1989 case NVPTX::StoreParamF64:
1990 case NVPTX::StoreParamI16:
1991 case NVPTX::StoreParamI32:
1992 case NVPTX::StoreParamI64:
1993 case NVPTX::StoreParamI8:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001994 case NVPTX::StoreRetvalF32:
1995 case NVPTX::StoreRetvalF64:
1996 case NVPTX::StoreRetvalI16:
1997 case NVPTX::StoreRetvalI32:
1998 case NVPTX::StoreRetvalI64:
1999 case NVPTX::StoreRetvalI8:
2000 case NVPTX::LastCallArgF32:
2001 case NVPTX::LastCallArgF64:
2002 case NVPTX::LastCallArgI16:
2003 case NVPTX::LastCallArgI32:
2004 case NVPTX::LastCallArgI32imm:
2005 case NVPTX::LastCallArgI64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002006 case NVPTX::LastCallArgParam:
2007 case NVPTX::LoadParamMemF32:
2008 case NVPTX::LoadParamMemF64:
2009 case NVPTX::LoadParamMemI16:
2010 case NVPTX::LoadParamMemI32:
2011 case NVPTX::LoadParamMemI64:
2012 case NVPTX::LoadParamMemI8:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002013 case NVPTX::PrototypeInst:
2014 case NVPTX::DBG_VALUE:
Justin Holewinskiae556d32012-05-04 20:18:50 +00002015 return true;
2016 }
2017 return false;
2018}
2019
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002020/// PrintAsmOperand - Print out an operand for an inline asm expression.
2021///
2022bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2023 unsigned AsmVariant,
2024 const char *ExtraCode, raw_ostream &O) {
2025 if (ExtraCode && ExtraCode[0]) {
2026 if (ExtraCode[1] != 0)
2027 return true; // Unknown modifier.
2028
2029 switch (ExtraCode[0]) {
2030 default:
2031 // See if this is a generic print operand
2032 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2033 case 'r':
2034 break;
2035 }
2036 }
2037
2038 printOperand(MI, OpNo, O);
2039
2040 return false;
2041}
2042
2043bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2044 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2045 const char *ExtraCode, raw_ostream &O) {
2046 if (ExtraCode && ExtraCode[0])
2047 return true; // Unknown modifier
2048
2049 O << '[';
2050 printMemOperand(MI, OpNo, O);
2051 O << ']';
2052
2053 return false;
2054}
2055
2056void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2057 raw_ostream &O, const char *Modifier) {
2058 const MachineOperand &MO = MI->getOperand(opNum);
2059 switch (MO.getType()) {
2060 case MachineOperand::MO_Register:
2061 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2062 if (MO.getReg() == NVPTX::VRDepot)
2063 O << DEPOTNAME << getFunctionNumber();
2064 else
2065 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2066 } else {
Justin Holewinski660597d2013-10-11 12:39:36 +00002067 emitVirtualRegister(MO.getReg(), O);
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002068 }
2069 return;
2070
2071 case MachineOperand::MO_Immediate:
2072 if (!Modifier)
2073 O << MO.getImm();
2074 else if (strstr(Modifier, "vec") == Modifier)
2075 printVecModifiedImmediate(MO, Modifier, O);
2076 else
2077 llvm_unreachable(
2078 "Don't know how to handle modifier on immediate operand");
2079 return;
2080
2081 case MachineOperand::MO_FPImmediate:
2082 printFPConstant(MO.getFPImm(), O);
2083 break;
2084
2085 case MachineOperand::MO_GlobalAddress:
Rafael Espindola79858aa2013-10-29 17:07:16 +00002086 O << *getSymbol(MO.getGlobal());
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002087 break;
2088
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002089 case MachineOperand::MO_MachineBasicBlock:
2090 O << *MO.getMBB()->getSymbol();
2091 return;
2092
2093 default:
2094 llvm_unreachable("Operand type not supported.");
2095 }
2096}
2097
2098void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2099 raw_ostream &O, const char *Modifier) {
2100 printOperand(MI, opNum, O);
2101
2102 if (Modifier && !strcmp(Modifier, "add")) {
2103 O << ", ";
2104 printOperand(MI, opNum + 1, O);
2105 } else {
2106 if (MI->getOperand(opNum + 1).isImm() &&
2107 MI->getOperand(opNum + 1).getImm() == 0)
2108 return; // don't print ',0' or '+0'
2109 O << "+";
2110 printOperand(MI, opNum + 1, O);
2111 }
2112}
2113
2114
Justin Holewinskiae556d32012-05-04 20:18:50 +00002115// Force static initialization.
2116extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2117 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2118 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2119}
2120
Justin Holewinskiae556d32012-05-04 20:18:50 +00002121void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2122 std::stringstream temp;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002123 LineReader *reader = this->getReader(filename.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +00002124 temp << "\n//";
2125 temp << filename.str();
2126 temp << ":";
2127 temp << line;
2128 temp << " ";
2129 temp << reader->readLine(line);
2130 temp << "\n";
2131 this->OutStreamer.EmitRawText(Twine(temp.str()));
2132}
2133
Justin Holewinskiae556d32012-05-04 20:18:50 +00002134LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002135 if (reader == NULL) {
2136 reader = new LineReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002137 }
2138
2139 if (reader->fileName() != filename) {
2140 delete reader;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002141 reader = new LineReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002142 }
2143
2144 return reader;
2145}
2146
Justin Holewinski0497ab12013-03-30 14:29:21 +00002147std::string LineReader::readLine(unsigned lineNum) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00002148 if (lineNum < theCurLine) {
2149 theCurLine = 0;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002150 fstr.seekg(0, std::ios::beg);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002151 }
2152 while (theCurLine < lineNum) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002153 fstr.getline(buff, 500);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002154 theCurLine++;
2155 }
2156 return buff;
2157}
2158
2159// Force static initialization.
2160extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2161 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2162 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2163}