blob: ec53f0f1b6d6703e440c386a4c7204c988d00616 [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 Carruthd9903882015-01-14 11:23:27 +000021#include "NVPTXMachineFunctionInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "NVPTXRegisterInfo.h"
23#include "NVPTXTargetMachine.h"
24#include "NVPTXUtilities.h"
25#include "cl_common_defines.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000026#include "llvm/ADT/StringExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/ConstantFolding.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000028#include "llvm/CodeGen/Analysis.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000029#include "llvm/CodeGen/MachineFrameInfo.h"
Jingyue Wu0220df02015-02-01 02:27:45 +000030#include "llvm/CodeGen/MachineLoopInfo.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000031#include "llvm/CodeGen/MachineModuleInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000033#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/Function.h"
36#include "llvm/IR/GlobalVariable.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000037#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Module.h"
39#include "llvm/IR/Operator.h"
Pete Cooper81902a32015-05-15 22:19:42 +000040#include "llvm/MC/MCInst.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000041#include "llvm/MC/MCStreamer.h"
42#include "llvm/MC/MCSymbol.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000043#include "llvm/Support/CommandLine.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000044#include "llvm/Support/ErrorHandling.h"
45#include "llvm/Support/FormattedStream.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000046#include "llvm/Support/Path.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000047#include "llvm/Support/TargetRegistry.h"
48#include "llvm/Support/TimeValue.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000049#include "llvm/Target/TargetLoweringObjectFile.h"
Jingyue Wu0220df02015-02-01 02:27:45 +000050#include "llvm/Transforms/Utils/UnrollLoop.h"
Bill Wendlinge38859d2012-06-28 00:05:13 +000051#include <sstream>
Justin Holewinskiae556d32012-05-04 20:18:50 +000052using namespace llvm;
53
Justin Holewinskiae556d32012-05-04 20:18:50 +000054#define DEPOTNAME "__local_depot"
55
56static cl::opt<bool>
Nadav Rotem7f27e0b2013-10-18 23:38:13 +000057EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
Justin Holewinskiae556d32012-05-04 20:18:50 +000058 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
59 cl::init(true));
60
Benjamin Kramer7ad41002013-10-27 11:31:46 +000061static cl::opt<bool>
Nadav Rotem7f27e0b2013-10-18 23:38:13 +000062InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
Justin Holewinski0497ab12013-03-30 14:29:21 +000063 cl::desc("NVPTX Specific: Emit source line in ptx file"),
Benjamin Kramer7ad41002013-10-27 11:31:46 +000064 cl::init(false));
Justin Holewinskiae556d32012-05-04 20:18:50 +000065
Justin Holewinski2c5ac702012-11-16 21:03:51 +000066namespace {
67/// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
68/// depends.
Justin Holewinski01f89f02013-05-20 12:13:32 +000069void DiscoverDependentGlobals(const Value *V,
70 DenseSet<const GlobalVariable *> &Globals) {
71 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Justin Holewinski2c5ac702012-11-16 21:03:51 +000072 Globals.insert(GV);
73 else {
Justin Holewinski01f89f02013-05-20 12:13:32 +000074 if (const User *U = dyn_cast<User>(V)) {
Justin Holewinski2c5ac702012-11-16 21:03:51 +000075 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
76 DiscoverDependentGlobals(U->getOperand(i), Globals);
77 }
78 }
79 }
80}
Justin Holewinskiae556d32012-05-04 20:18:50 +000081
Justin Holewinski2c5ac702012-11-16 21:03:51 +000082/// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
83/// instances to be emitted, but only after any dependents have been added
84/// first.
Justin Holewinski0497ab12013-03-30 14:29:21 +000085void VisitGlobalVariableForEmission(
Justin Holewinski01f89f02013-05-20 12:13:32 +000086 const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
87 DenseSet<const GlobalVariable *> &Visited,
88 DenseSet<const GlobalVariable *> &Visiting) {
Justin Holewinski2c5ac702012-11-16 21:03:51 +000089 // Have we already visited this one?
Justin Holewinski0497ab12013-03-30 14:29:21 +000090 if (Visited.count(GV))
91 return;
Justin Holewinski2c5ac702012-11-16 21:03:51 +000092
93 // Do we have a circular dependency?
Benjamin Kramer2c99e412014-10-10 15:32:50 +000094 if (!Visiting.insert(GV).second)
Justin Holewinski2c5ac702012-11-16 21:03:51 +000095 report_fatal_error("Circular dependency found in global variable set");
96
Justin Holewinski2c5ac702012-11-16 21:03:51 +000097 // Make sure we visit all dependents first
Justin Holewinski01f89f02013-05-20 12:13:32 +000098 DenseSet<const GlobalVariable *> Others;
Justin Holewinski2c5ac702012-11-16 21:03:51 +000099 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
100 DiscoverDependentGlobals(GV->getOperand(i), Others);
Justin Holewinski0497ab12013-03-30 14:29:21 +0000101
Justin Holewinski01f89f02013-05-20 12:13:32 +0000102 for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
103 E = Others.end();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000104 I != E; ++I)
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000105 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
106
107 // Now we can visit ourself
108 Order.push_back(GV);
109 Visited.insert(GV);
110 Visiting.erase(GV);
111}
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000112}
Justin Holewinskiae556d32012-05-04 20:18:50 +0000113
Justin Holewinski0497ab12013-03-30 14:29:21 +0000114void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000115 if (!EmitLineNumbers)
116 return;
117 if (ignoreLoc(MI))
118 return;
119
Benjamin Kramer4fed9282016-05-27 12:30:51 +0000120 const DebugLoc &curLoc = MI.getDebugLoc();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000121
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000122 if (!prevDebugLoc && !curLoc)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000123 return;
124
125 if (prevDebugLoc == curLoc)
126 return;
127
128 prevDebugLoc = curLoc;
129
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000130 if (!curLoc)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000131 return;
132
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000133 auto *Scope = cast_or_null<DIScope>(curLoc.getScope());
Manman Ren983a16c2013-06-28 05:43:10 +0000134 if (!Scope)
135 return;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000136
Duncan P. N. Exon Smithb273d062015-04-16 01:37:00 +0000137 StringRef fileName(Scope->getFilename());
138 StringRef dirName(Scope->getDirectory());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000139 SmallString<128> FullPathName = dirName;
140 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
141 sys::path::append(FullPathName, fileName);
Yaron Keren075759a2015-03-30 15:42:36 +0000142 fileName = FullPathName;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000143 }
144
Yaron Keren075759a2015-03-30 15:42:36 +0000145 if (filenameMap.find(fileName) == filenameMap.end())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000146 return;
147
Justin Holewinskiae556d32012-05-04 20:18:50 +0000148 // Emit the line from the source file.
Benjamin Kramer7ad41002013-10-27 11:31:46 +0000149 if (InterleaveSrc)
Yaron Keren075759a2015-03-30 15:42:36 +0000150 this->emitSrcInText(fileName, curLoc.getLine());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000151
152 std::stringstream temp;
Yaron Keren075759a2015-03-30 15:42:36 +0000153 temp << "\t.loc " << filenameMap[fileName] << " " << curLoc.getLine()
Justin Holewinski0497ab12013-03-30 14:29:21 +0000154 << " " << curLoc.getCol();
Lang Hames9ff69c82015-04-24 19:11:51 +0000155 OutStreamer->EmitRawText(temp.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000156}
157
158void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
159 SmallString<128> Str;
160 raw_svector_ostream OS(Str);
Eric Christopherbeffc4e2015-02-19 00:08:23 +0000161 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000162 emitLineNumberAsDotLoc(*MI);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000163
164 MCInst Inst;
165 lowerToMCInst(MI, Inst);
Lang Hames9ff69c82015-04-24 19:11:51 +0000166 EmitToStreamer(*OutStreamer, Inst);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000167}
168
Justin Holewinski30d56a72014-04-09 15:39:15 +0000169// Handle symbol backtracking for targets that do not support image handles
170bool NVPTXAsmPrinter::lowerImageHandleOperand(const MachineInstr *MI,
171 unsigned OpNo, MCOperand &MCOp) {
172 const MachineOperand &MO = MI->getOperand(OpNo);
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000173 const MCInstrDesc &MCID = MI->getDesc();
Justin Holewinski30d56a72014-04-09 15:39:15 +0000174
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000175 if (MCID.TSFlags & NVPTXII::IsTexFlag) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000176 // This is a texture fetch, so operand 4 is a texref and operand 5 is
177 // a samplerref
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000178 if (OpNo == 4 && MO.isImm()) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000179 lowerImageHandleSymbol(MO.getImm(), MCOp);
180 return true;
181 }
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000182 if (OpNo == 5 && MO.isImm() && !(MCID.TSFlags & NVPTXII::IsTexModeUnifiedFlag)) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000183 lowerImageHandleSymbol(MO.getImm(), MCOp);
184 return true;
185 }
186
187 return false;
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000188 } else if (MCID.TSFlags & NVPTXII::IsSuldMask) {
189 unsigned VecSize =
190 1 << (((MCID.TSFlags & NVPTXII::IsSuldMask) >> NVPTXII::IsSuldShift) - 1);
191
192 // For a surface load of vector size N, the Nth operand will be the surfref
193 if (OpNo == VecSize && MO.isImm()) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000194 lowerImageHandleSymbol(MO.getImm(), MCOp);
195 return true;
196 }
197
198 return false;
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000199 } else if (MCID.TSFlags & NVPTXII::IsSustFlag) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000200 // This is a surface store, so operand 0 is a surfref
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000201 if (OpNo == 0 && MO.isImm()) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000202 lowerImageHandleSymbol(MO.getImm(), MCOp);
203 return true;
204 }
205
206 return false;
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000207 } else if (MCID.TSFlags & NVPTXII::IsSurfTexQueryFlag) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000208 // This is a query, so operand 1 is a surfref/texref
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000209 if (OpNo == 1 && MO.isImm()) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000210 lowerImageHandleSymbol(MO.getImm(), MCOp);
211 return true;
212 }
213
214 return false;
215 }
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000216
217 return false;
Justin Holewinski30d56a72014-04-09 15:39:15 +0000218}
219
220void NVPTXAsmPrinter::lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp) {
221 // Ewwww
222 TargetMachine &TM = const_cast<TargetMachine&>(MF->getTarget());
223 NVPTXTargetMachine &nvTM = static_cast<NVPTXTargetMachine&>(TM);
224 const NVPTXMachineFunctionInfo *MFI = MF->getInfo<NVPTXMachineFunctionInfo>();
225 const char *Sym = MFI->getImageHandleSymbol(Index);
226 std::string *SymNamePtr =
227 nvTM.getManagedStrPool()->getManagedString(Sym);
Jim Grosbach6f482002015-05-18 18:43:14 +0000228 MCOp = GetSymbolRef(OutContext.getOrCreateSymbol(
Justin Holewinski30d56a72014-04-09 15:39:15 +0000229 StringRef(SymNamePtr->c_str())));
230}
231
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000232void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
233 OutMI.setOpcode(MI->getOpcode());
Justin Holewinski3d49e5c2013-11-15 12:30:04 +0000234 // Special: Do not mangle symbol operand of CALL_PROTOTYPE
235 if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
236 const MachineOperand &MO = MI->getOperand(0);
Justin Holewinski30d56a72014-04-09 15:39:15 +0000237 OutMI.addOperand(GetSymbolRef(
Jim Grosbach6f482002015-05-18 18:43:14 +0000238 OutContext.getOrCreateSymbol(Twine(MO.getSymbolName()))));
Justin Holewinski3d49e5c2013-11-15 12:30:04 +0000239 return;
240 }
241
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000242 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
243 const MachineOperand &MO = MI->getOperand(i);
244
245 MCOperand MCOp;
Eric Christopher6aad8b12015-02-19 00:08:14 +0000246 if (!nvptxSubtarget->hasImageHandles()) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000247 if (lowerImageHandleOperand(MI, i, MCOp)) {
248 OutMI.addOperand(MCOp);
249 continue;
250 }
251 }
252
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000253 if (lowerOperand(MO, MCOp))
254 OutMI.addOperand(MCOp);
255 }
256}
257
258bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
259 MCOperand &MCOp) {
260 switch (MO.getType()) {
261 default: llvm_unreachable("unknown operand type");
262 case MachineOperand::MO_Register:
Jim Grosbache9119e42015-05-13 18:37:00 +0000263 MCOp = MCOperand::createReg(encodeVirtualRegister(MO.getReg()));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000264 break;
265 case MachineOperand::MO_Immediate:
Jim Grosbache9119e42015-05-13 18:37:00 +0000266 MCOp = MCOperand::createImm(MO.getImm());
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000267 break;
268 case MachineOperand::MO_MachineBasicBlock:
Jim Grosbach13760bd2015-05-30 01:25:56 +0000269 MCOp = MCOperand::createExpr(MCSymbolRefExpr::create(
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000270 MO.getMBB()->getSymbol(), OutContext));
271 break;
272 case MachineOperand::MO_ExternalSymbol:
Justin Holewinski30d56a72014-04-09 15:39:15 +0000273 MCOp = GetSymbolRef(GetExternalSymbolSymbol(MO.getSymbolName()));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000274 break;
275 case MachineOperand::MO_GlobalAddress:
Justin Holewinski30d56a72014-04-09 15:39:15 +0000276 MCOp = GetSymbolRef(getSymbol(MO.getGlobal()));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000277 break;
278 case MachineOperand::MO_FPImmediate: {
279 const ConstantFP *Cnt = MO.getFPImm();
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000280 const APFloat &Val = Cnt->getValueAPF();
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000281
282 switch (Cnt->getType()->getTypeID()) {
283 default: report_fatal_error("Unsupported FP type"); break;
284 case Type::FloatTyID:
Jim Grosbache9119e42015-05-13 18:37:00 +0000285 MCOp = MCOperand::createExpr(
Jim Grosbach13760bd2015-05-30 01:25:56 +0000286 NVPTXFloatMCExpr::createConstantFPSingle(Val, OutContext));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000287 break;
288 case Type::DoubleTyID:
Jim Grosbache9119e42015-05-13 18:37:00 +0000289 MCOp = MCOperand::createExpr(
Jim Grosbach13760bd2015-05-30 01:25:56 +0000290 NVPTXFloatMCExpr::createConstantFPDouble(Val, OutContext));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000291 break;
292 }
293 break;
294 }
295 }
296 return true;
297}
298
299unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
Justin Holewinski871ec932013-08-06 14:13:31 +0000300 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
301 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000302
Justin Holewinski871ec932013-08-06 14:13:31 +0000303 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
304 unsigned RegNum = RegMap[Reg];
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000305
Justin Holewinski871ec932013-08-06 14:13:31 +0000306 // Encode the register class in the upper 4 bits
307 // Must be kept in sync with NVPTXInstPrinter::printRegName
308 unsigned Ret = 0;
309 if (RC == &NVPTX::Int1RegsRegClass) {
310 Ret = (1 << 28);
311 } else if (RC == &NVPTX::Int16RegsRegClass) {
312 Ret = (2 << 28);
313 } else if (RC == &NVPTX::Int32RegsRegClass) {
314 Ret = (3 << 28);
315 } else if (RC == &NVPTX::Int64RegsRegClass) {
316 Ret = (4 << 28);
317 } else if (RC == &NVPTX::Float32RegsRegClass) {
318 Ret = (5 << 28);
319 } else if (RC == &NVPTX::Float64RegsRegClass) {
320 Ret = (6 << 28);
321 } else {
322 report_fatal_error("Bad register class");
323 }
324
325 // Insert the vreg number
326 Ret |= (RegNum & 0x0FFFFFFF);
327 return Ret;
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000328 } else {
Justin Holewinski871ec932013-08-06 14:13:31 +0000329 // Some special-use registers are actually physical registers.
330 // Encode this as the register class ID of 0 and the real register ID.
331 return Reg & 0x0FFFFFFF;
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000332 }
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000333}
334
Justin Holewinski30d56a72014-04-09 15:39:15 +0000335MCOperand NVPTXAsmPrinter::GetSymbolRef(const MCSymbol *Symbol) {
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000336 const MCExpr *Expr;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000337 Expr = MCSymbolRefExpr::create(Symbol, MCSymbolRefExpr::VK_None,
Justin Holewinski8b24e1e2013-08-06 23:06:42 +0000338 OutContext);
Jim Grosbache9119e42015-05-13 18:37:00 +0000339 return MCOperand::createExpr(Expr);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000340}
341
Justin Holewinski0497ab12013-03-30 14:29:21 +0000342void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
Mehdi Amini56228da2015-07-09 01:57:34 +0000343 const DataLayout &DL = getDataLayout();
Eric Christopher6aad8b12015-02-19 00:08:14 +0000344 const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000345
346 Type *Ty = F->getReturnType();
347
Eric Christopher6aad8b12015-02-19 00:08:14 +0000348 bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000349
350 if (Ty->getTypeID() == Type::VoidTyID)
351 return;
352
353 O << " (";
354
355 if (isABI) {
Rafael Espindola08013342013-12-07 19:34:20 +0000356 if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000357 unsigned size = 0;
Craig Toppere3dcce92015-08-01 22:20:21 +0000358 if (auto *ITy = dyn_cast<IntegerType>(Ty)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000359 size = ITy->getBitWidth();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000360 if (size < 32)
361 size = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000362 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +0000363 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000364 size = Ty->getPrimitiveSizeInBits();
365 }
366
367 O << ".param .b" << size << " func_retval0";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000368 } else if (isa<PointerType>(Ty)) {
Mehdi Amini44ede332015-07-09 02:09:04 +0000369 O << ".param .b" << TLI->getPointerTy(DL).getSizeInBits()
Justin Holewinski0497ab12013-03-30 14:29:21 +0000370 << " func_retval0";
Craig Topperd3c02f12015-01-05 10:15:49 +0000371 } else if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
Mehdi Amini56228da2015-07-09 01:57:34 +0000372 unsigned totalsz = DL.getTypeAllocSize(Ty);
Craig Topperd3c02f12015-01-05 10:15:49 +0000373 unsigned retAlignment = 0;
374 if (!llvm::getAlign(*F, 0, retAlignment))
Mehdi Amini56228da2015-07-09 01:57:34 +0000375 retAlignment = DL.getABITypeAlignment(Ty);
Craig Topperd3c02f12015-01-05 10:15:49 +0000376 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
377 << "]";
378 } else
379 llvm_unreachable("Unknown return type");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000380 } else {
381 SmallVector<EVT, 16> vtparts;
Mehdi Amini56228da2015-07-09 01:57:34 +0000382 ComputeValueVTs(*TLI, DL, Ty, vtparts);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000383 unsigned idx = 0;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000384 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000385 unsigned elems = 1;
386 EVT elemtype = vtparts[i];
387 if (vtparts[i].isVector()) {
388 elems = vtparts[i].getVectorNumElements();
389 elemtype = vtparts[i].getVectorElementType();
390 }
391
Justin Holewinski0497ab12013-03-30 14:29:21 +0000392 for (unsigned j = 0, je = elems; j != je; ++j) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000393 unsigned sz = elemtype.getSizeInBits();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000394 if (elemtype.isInteger() && (sz < 32))
395 sz = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000396 O << ".reg .b" << sz << " func_retval" << idx;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000397 if (j < je - 1)
398 O << ", ";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000399 ++idx;
400 }
Justin Holewinski0497ab12013-03-30 14:29:21 +0000401 if (i < e - 1)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000402 O << ", ";
403 }
404 }
405 O << ") ";
406 return;
407}
408
409void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
410 raw_ostream &O) {
411 const Function *F = MF.getFunction();
412 printReturnValStr(F, O);
413}
414
Jingyue Wu0220df02015-02-01 02:27:45 +0000415// Return true if MBB is the header of a loop marked with
416// llvm.loop.unroll.disable.
Jingyue Wu5bbcdaa2015-02-03 17:57:38 +0000417// TODO: consider "#pragma unroll 1" which is equivalent to "#pragma nounroll".
Jingyue Wu0220df02015-02-01 02:27:45 +0000418bool NVPTXAsmPrinter::isLoopHeaderOfNoUnroll(
419 const MachineBasicBlock &MBB) const {
420 MachineLoopInfo &LI = getAnalysis<MachineLoopInfo>();
Jingyue Wu0220df02015-02-01 02:27:45 +0000421 // We insert .pragma "nounroll" only to the loop header.
Benjamin Kramerdb220db2015-06-02 15:28:27 +0000422 if (!LI.isLoopHeader(&MBB))
Jingyue Wu0220df02015-02-01 02:27:45 +0000423 return false;
424
425 // llvm.loop.unroll.disable is marked on the back edges of a loop. Therefore,
426 // we iterate through each back edge of the loop with header MBB, and check
427 // whether its metadata contains llvm.loop.unroll.disable.
428 for (auto I = MBB.pred_begin(); I != MBB.pred_end(); ++I) {
429 const MachineBasicBlock *PMBB = *I;
430 if (LI.getLoopFor(PMBB) != LI.getLoopFor(&MBB)) {
431 // Edges from other loops to MBB are not back edges.
432 continue;
433 }
434 if (const BasicBlock *PBB = PMBB->getBasicBlock()) {
Duncan P. N. Exon Smith1d15a9f2016-03-25 00:35:38 +0000435 if (MDNode *LoopID =
436 PBB->getTerminator()->getMetadata(LLVMContext::MD_loop)) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000437 if (GetUnrollMetadata(LoopID, "llvm.loop.unroll.disable"))
438 return true;
439 }
440 }
441 }
442 return false;
443}
444
445void NVPTXAsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
446 AsmPrinter::EmitBasicBlockStart(MBB);
447 if (isLoopHeaderOfNoUnroll(MBB))
Lang Hames9ff69c82015-04-24 19:11:51 +0000448 OutStreamer->EmitRawText(StringRef("\t.pragma \"nounroll\";\n"));
Jingyue Wu0220df02015-02-01 02:27:45 +0000449}
450
Justin Holewinskiae556d32012-05-04 20:18:50 +0000451void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
452 SmallString<128> Str;
453 raw_svector_ostream O(Str);
454
Justin Holewinski01f89f02013-05-20 12:13:32 +0000455 if (!GlobalsEmitted) {
456 emitGlobals(*MF->getFunction()->getParent());
457 GlobalsEmitted = true;
458 }
459
Justin Holewinskiae556d32012-05-04 20:18:50 +0000460 // Set up
461 MRI = &MF->getRegInfo();
462 F = MF->getFunction();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000463 emitLinkageDirective(F, O);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000464 if (llvm::isKernelFunction(*F))
465 O << ".entry ";
466 else {
467 O << ".func ";
468 printReturnValStr(*MF, O);
469 }
470
Matt Arsenault8b643552015-06-09 00:31:39 +0000471 CurrentFnSym->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000472
473 emitFunctionParamList(*MF, O);
474
475 if (llvm::isKernelFunction(*F))
476 emitKernelFunctionDirectives(*F, O);
477
Lang Hames9ff69c82015-04-24 19:11:51 +0000478 OutStreamer->EmitRawText(O.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000479
480 prevDebugLoc = DebugLoc();
481}
482
483void NVPTXAsmPrinter::EmitFunctionBodyStart() {
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +0000484 VRegMapping.clear();
Lang Hames9ff69c82015-04-24 19:11:51 +0000485 OutStreamer->EmitRawText(StringRef("{\n"));
Justin Holewinskiae556d32012-05-04 20:18:50 +0000486 setAndEmitFunctionVirtualRegisters(*MF);
487
488 SmallString<128> Str;
489 raw_svector_ostream O(Str);
490 emitDemotedVars(MF->getFunction(), O);
Lang Hames9ff69c82015-04-24 19:11:51 +0000491 OutStreamer->EmitRawText(O.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000492}
493
494void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
Lang Hames9ff69c82015-04-24 19:11:51 +0000495 OutStreamer->EmitRawText(StringRef("}\n"));
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +0000496 VRegMapping.clear();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000497}
498
Justin Holewinski660597d2013-10-11 12:39:36 +0000499void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
500 unsigned RegNo = MI->getOperand(0).getReg();
Andrew Kaylor5c73e1f2015-03-24 23:37:10 +0000501 if (TargetRegisterInfo::isVirtualRegister(RegNo)) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000502 OutStreamer->AddComment(Twine("implicit-def: ") +
503 getVirtualRegisterName(RegNo));
Justin Holewinski660597d2013-10-11 12:39:36 +0000504 } else {
Lang Hames9ff69c82015-04-24 19:11:51 +0000505 OutStreamer->AddComment(Twine("implicit-def: ") +
506 nvptxSubtarget->getRegisterInfo()->getName(RegNo));
Justin Holewinski660597d2013-10-11 12:39:36 +0000507 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000508 OutStreamer->AddBlankLine();
Justin Holewinski660597d2013-10-11 12:39:36 +0000509}
510
Justin Holewinski0497ab12013-03-30 14:29:21 +0000511void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
512 raw_ostream &O) const {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000513 // If the NVVM IR has some of reqntid* specified, then output
514 // the reqntid directive, and set the unspecified ones to 1.
515 // If none of reqntid* is specified, don't output reqntid directive.
516 unsigned reqntidx, reqntidy, reqntidz;
517 bool specified = false;
Eli Bendersky3e840192015-03-23 16:26:23 +0000518 if (!llvm::getReqNTIDx(F, reqntidx))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000519 reqntidx = 1;
520 else
521 specified = true;
Eli Bendersky3e840192015-03-23 16:26:23 +0000522 if (!llvm::getReqNTIDy(F, reqntidy))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000523 reqntidy = 1;
524 else
525 specified = true;
Eli Bendersky3e840192015-03-23 16:26:23 +0000526 if (!llvm::getReqNTIDz(F, reqntidz))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000527 reqntidz = 1;
528 else
529 specified = true;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000530
531 if (specified)
Justin Holewinski0497ab12013-03-30 14:29:21 +0000532 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
533 << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000534
535 // If the NVVM IR has some of maxntid* specified, then output
536 // the maxntid directive, and set the unspecified ones to 1.
537 // If none of maxntid* is specified, don't output maxntid directive.
538 unsigned maxntidx, maxntidy, maxntidz;
539 specified = false;
Eli Bendersky3e840192015-03-23 16:26:23 +0000540 if (!llvm::getMaxNTIDx(F, maxntidx))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000541 maxntidx = 1;
542 else
543 specified = true;
Eli Bendersky3e840192015-03-23 16:26:23 +0000544 if (!llvm::getMaxNTIDy(F, maxntidy))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000545 maxntidy = 1;
546 else
547 specified = true;
Eli Bendersky3e840192015-03-23 16:26:23 +0000548 if (!llvm::getMaxNTIDz(F, maxntidz))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000549 maxntidz = 1;
550 else
551 specified = true;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000552
553 if (specified)
Justin Holewinski0497ab12013-03-30 14:29:21 +0000554 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
555 << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000556
557 unsigned mincta;
558 if (llvm::getMinCTASm(F, mincta))
559 O << ".minnctapersm " << mincta << "\n";
560}
561
Justin Holewinski660597d2013-10-11 12:39:36 +0000562std::string
563NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
564 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000565
Justin Holewinski660597d2013-10-11 12:39:36 +0000566 std::string Name;
567 raw_string_ostream NameStr(Name);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000568
Justin Holewinski660597d2013-10-11 12:39:36 +0000569 VRegRCMap::const_iterator I = VRegMapping.find(RC);
570 assert(I != VRegMapping.end() && "Bad register class");
571 const DenseMap<unsigned, unsigned> &RegMap = I->second;
572
573 VRegMap::const_iterator VI = RegMap.find(Reg);
574 assert(VI != RegMap.end() && "Bad virtual register");
575 unsigned MappedVR = VI->second;
576
577 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
578
579 NameStr.flush();
580 return Name;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000581}
582
Justin Holewinski660597d2013-10-11 12:39:36 +0000583void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
Justin Holewinski0497ab12013-03-30 14:29:21 +0000584 raw_ostream &O) {
Justin Holewinski660597d2013-10-11 12:39:36 +0000585 O << getVirtualRegisterName(vr);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000586}
587
Justin Holewinski0497ab12013-03-30 14:29:21 +0000588void NVPTXAsmPrinter::printVecModifiedImmediate(
589 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
590 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
591 int Imm = (int) MO.getImm();
592 if (0 == strcmp(Modifier, "vecelem"))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000593 O << "_" << vecelem[Imm];
Justin Holewinski0497ab12013-03-30 14:29:21 +0000594 else if (0 == strcmp(Modifier, "vecv4comm1")) {
595 if ((Imm < 0) || (Imm > 3))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000596 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000597 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
598 if ((Imm < 4) || (Imm > 7))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000599 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000600 } else if (0 == strcmp(Modifier, "vecv4pos")) {
601 if (Imm < 0)
602 Imm = 0;
603 O << "_" << vecelem[Imm % 4];
604 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
605 if ((Imm < 0) || (Imm > 1))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000606 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000607 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
608 if ((Imm < 2) || (Imm > 3))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000609 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000610 } else if (0 == strcmp(Modifier, "vecv2pos")) {
611 if (Imm < 0)
612 Imm = 0;
613 O << "_" << vecelem[Imm % 2];
614 } else
Craig Topperbdf39a42012-05-24 07:02:50 +0000615 llvm_unreachable("Unknown Modifier on immediate operand");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000616}
617
Justin Holewinskidc5e3b62013-06-28 17:58:04 +0000618
619
Justin Holewinski0497ab12013-03-30 14:29:21 +0000620void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000621
Justin Holewinski0497ab12013-03-30 14:29:21 +0000622 emitLinkageDirective(F, O);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000623 if (llvm::isKernelFunction(*F))
624 O << ".entry ";
625 else
626 O << ".func ";
627 printReturnValStr(F, O);
Matt Arsenault8b643552015-06-09 00:31:39 +0000628 getSymbol(F)->print(O, MAI);
629 O << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000630 emitFunctionParamList(F, O);
631 O << ";\n";
632}
633
Justin Holewinski0497ab12013-03-30 14:29:21 +0000634static bool usedInGlobalVarDef(const Constant *C) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000635 if (!C)
636 return false;
637
638 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
Jingyue Wu4be014a2015-07-31 05:09:47 +0000639 return GV->getName() != "llvm.used";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000640 }
641
Chandler Carruthcdf47882014-03-09 03:16:01 +0000642 for (const User *U : C->users())
643 if (const Constant *C = dyn_cast<Constant>(U))
644 if (usedInGlobalVarDef(C))
645 return true;
646
Justin Holewinskiae556d32012-05-04 20:18:50 +0000647 return false;
648}
649
Justin Holewinski0497ab12013-03-30 14:29:21 +0000650static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000651 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
Yaron Keren075759a2015-03-30 15:42:36 +0000652 if (othergv->getName() == "llvm.used")
Justin Holewinskiae556d32012-05-04 20:18:50 +0000653 return true;
654 }
655
656 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
657 if (instr->getParent() && instr->getParent()->getParent()) {
658 const Function *curFunc = instr->getParent()->getParent();
659 if (oneFunc && (curFunc != oneFunc))
660 return false;
661 oneFunc = curFunc;
662 return true;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000663 } else
Justin Holewinskiae556d32012-05-04 20:18:50 +0000664 return false;
665 }
666
Chandler Carruthcdf47882014-03-09 03:16:01 +0000667 for (const User *UU : U->users())
Eli Bendersky3e840192015-03-23 16:26:23 +0000668 if (!usedInOneFunc(UU, oneFunc))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000669 return false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000670
Justin Holewinskiae556d32012-05-04 20:18:50 +0000671 return true;
672}
673
674/* Find out if a global variable can be demoted to local scope.
675 * Currently, this is valid for CUDA shared variables, which have local
676 * scope and global lifetime. So the conditions to check are :
677 * 1. Is the global variable in shared address space?
678 * 2. Does it have internal linkage?
679 * 3. Is the global variable referenced only in one function?
680 */
681static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
Eli Bendersky3e840192015-03-23 16:26:23 +0000682 if (!gv->hasInternalLinkage())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000683 return false;
Craig Toppere3dcce92015-08-01 22:20:21 +0000684 PointerType *Pty = gv->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000685 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
686 return false;
687
Craig Topper062a2ba2014-04-25 05:30:21 +0000688 const Function *oneFunc = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000689
690 bool flag = usedInOneFunc(gv, oneFunc);
Eli Bendersky3e840192015-03-23 16:26:23 +0000691 if (!flag)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000692 return false;
693 if (!oneFunc)
694 return false;
695 f = oneFunc;
696 return true;
697}
698
699static bool useFuncSeen(const Constant *C,
700 llvm::DenseMap<const Function *, bool> &seenMap) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000701 for (const User *U : C->users()) {
702 if (const Constant *cu = dyn_cast<Constant>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000703 if (useFuncSeen(cu, seenMap))
704 return true;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000705 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000706 const BasicBlock *bb = I->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000707 if (!bb)
708 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000709 const Function *caller = bb->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000710 if (!caller)
711 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000712 if (seenMap.find(caller) != seenMap.end())
713 return true;
714 }
715 }
716 return false;
717}
718
Justin Holewinski01f89f02013-05-20 12:13:32 +0000719void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000720 llvm::DenseMap<const Function *, bool> seenMap;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000721 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
Duncan P. N. Exon Smith61149b82015-10-20 00:54:09 +0000722 const Function *F = &*FI;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000723
724 if (F->isDeclaration()) {
725 if (F->use_empty())
726 continue;
727 if (F->getIntrinsicID())
728 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000729 emitDeclaration(F, O);
730 continue;
731 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000732 for (const User *U : F->users()) {
733 if (const Constant *C = dyn_cast<Constant>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000734 if (usedInGlobalVarDef(C)) {
735 // The use is in the initialization of a global variable
736 // that is a function pointer, so print a declaration
737 // for the original function
Justin Holewinskiae556d32012-05-04 20:18:50 +0000738 emitDeclaration(F, O);
739 break;
740 }
741 // Emit a declaration of this function if the function that
742 // uses this constant expr has already been seen.
743 if (useFuncSeen(C, seenMap)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000744 emitDeclaration(F, O);
745 break;
746 }
747 }
748
Chandler Carruthcdf47882014-03-09 03:16:01 +0000749 if (!isa<Instruction>(U))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000750 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000751 const Instruction *instr = cast<Instruction>(U);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000752 const BasicBlock *bb = instr->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000753 if (!bb)
754 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000755 const Function *caller = bb->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000756 if (!caller)
757 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000758
759 // If a caller has already been seen, then the caller is
760 // appearing in the module before the callee. so print out
761 // a declaration for the callee.
762 if (seenMap.find(caller) != seenMap.end()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000763 emitDeclaration(F, O);
764 break;
765 }
766 }
767 seenMap[F] = true;
768 }
769}
770
771void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
772 DebugInfoFinder DbgFinder;
773 DbgFinder.processModule(M);
774
Justin Holewinski0497ab12013-03-30 14:29:21 +0000775 unsigned i = 1;
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000776 for (const DICompileUnit *DIUnit : DbgFinder.compile_units()) {
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +0000777 StringRef Filename = DIUnit->getFilename();
778 StringRef Dirname = DIUnit->getDirectory();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000779 SmallString<128> FullPathName = Dirname;
780 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
781 sys::path::append(FullPathName, Filename);
Yaron Keren075759a2015-03-30 15:42:36 +0000782 Filename = FullPathName;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000783 }
Yaron Keren075759a2015-03-30 15:42:36 +0000784 if (filenameMap.find(Filename) != filenameMap.end())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000785 continue;
Yaron Keren075759a2015-03-30 15:42:36 +0000786 filenameMap[Filename] = i;
Lang Hames9ff69c82015-04-24 19:11:51 +0000787 OutStreamer->EmitDwarfFileDirective(i, "", Filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000788 ++i;
789 }
790
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000791 for (DISubprogram *SP : DbgFinder.subprograms()) {
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000792 StringRef Filename = SP->getFilename();
793 StringRef Dirname = SP->getDirectory();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000794 SmallString<128> FullPathName = Dirname;
795 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
796 sys::path::append(FullPathName, Filename);
Yaron Keren075759a2015-03-30 15:42:36 +0000797 Filename = FullPathName;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000798 }
Yaron Keren075759a2015-03-30 15:42:36 +0000799 if (filenameMap.find(Filename) != filenameMap.end())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000800 continue;
Yaron Keren075759a2015-03-30 15:42:36 +0000801 filenameMap[Filename] = i;
Artem Belevicha8455f22016-02-11 18:21:47 +0000802 OutStreamer->EmitDwarfFileDirective(i, "", Filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000803 ++i;
804 }
805}
806
Justin Lebaread59f42016-01-30 01:07:38 +0000807static bool isEmptyXXStructor(GlobalVariable *GV) {
808 if (!GV) return true;
809 const ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
810 if (!InitList) return true; // Not an array; we don't know how to parse.
811 return InitList->getNumOperands() == 0;
812}
813
Justin Holewinski0497ab12013-03-30 14:29:21 +0000814bool NVPTXAsmPrinter::doInitialization(Module &M) {
Eric Christopher6aad8b12015-02-19 00:08:14 +0000815 // Construct a default subtarget off of the TargetMachine defaults. The
816 // rest of NVPTX isn't friendly to change subtargets per function and
817 // so the default TargetMachine will have all of the options.
Daniel Sandersc81f4502015-06-16 15:44:21 +0000818 const Triple &TT = TM.getTargetTriple();
Eric Christopher6aad8b12015-02-19 00:08:14 +0000819 StringRef CPU = TM.getTargetCPU();
820 StringRef FS = TM.getTargetFeatureString();
821 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
Eric Christopher02389e32015-02-19 00:08:27 +0000822 const NVPTXSubtarget STI(TT, CPU, FS, NTM);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000823
Justin Lebar3a5f5792016-01-23 21:12:20 +0000824 if (M.alias_size()) {
825 report_fatal_error("Module has aliases, which NVPTX does not support.");
826 return true; // error
827 }
Justin Lebaread59f42016-01-30 01:07:38 +0000828 if (!isEmptyXXStructor(M.getNamedGlobal("llvm.global_ctors"))) {
829 report_fatal_error(
830 "Module has a nontrivial global ctor, which NVPTX does not support.");
831 return true; // error
832 }
833 if (!isEmptyXXStructor(M.getNamedGlobal("llvm.global_dtors"))) {
834 report_fatal_error(
835 "Module has a nontrivial global dtor, which NVPTX does not support.");
836 return true; // error
837 }
Justin Lebar3a5f5792016-01-23 21:12:20 +0000838
Justin Holewinskiae556d32012-05-04 20:18:50 +0000839 SmallString<128> Str1;
840 raw_svector_ostream OS1(Str1);
841
842 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000843
844 // We need to call the parent's one explicitly.
845 //bool Result = AsmPrinter::doInitialization(M);
846
847 // Initialize TargetLoweringObjectFile.
Justin Holewinski0497ab12013-03-30 14:29:21 +0000848 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
849 .Initialize(OutContext, TM);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000850
Rafael Espindolac233f742015-06-23 13:59:29 +0000851 Mang = new Mangler();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000852
853 // Emit header before any dwarf directives are emitted below.
Eric Christopher6aad8b12015-02-19 00:08:14 +0000854 emitHeader(M, OS1, STI);
Lang Hames9ff69c82015-04-24 19:11:51 +0000855 OutStreamer->EmitRawText(OS1.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000856
Justin Holewinskiae556d32012-05-04 20:18:50 +0000857 // Already commented out
858 //bool Result = AsmPrinter::doInitialization(M);
859
Justin Holewinskid2bbdf02013-07-01 13:00:14 +0000860 // Emit module-level inline asm if it exists.
861 if (!M.getModuleInlineAsm().empty()) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000862 OutStreamer->AddComment("Start of file scope inline assembly");
863 OutStreamer->AddBlankLine();
864 OutStreamer->EmitRawText(StringRef(M.getModuleInlineAsm()));
865 OutStreamer->AddBlankLine();
866 OutStreamer->AddComment("End of file scope inline assembly");
867 OutStreamer->AddBlankLine();
Justin Holewinskid2bbdf02013-07-01 13:00:14 +0000868 }
869
Eric Christopher6aad8b12015-02-19 00:08:14 +0000870 // If we're not NVCL we're CUDA, go ahead and emit filenames.
Daniel Sandersc81f4502015-06-16 15:44:21 +0000871 if (TM.getTargetTriple().getOS() != Triple::NVCL)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000872 recordAndEmitFilenames(M);
873
Justin Holewinski01f89f02013-05-20 12:13:32 +0000874 GlobalsEmitted = false;
875
876 return false; // success
877}
878
879void NVPTXAsmPrinter::emitGlobals(const Module &M) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000880 SmallString<128> Str2;
881 raw_svector_ostream OS2(Str2);
882
883 emitDeclarations(M, OS2);
884
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000885 // As ptxas does not support forward references of globals, we need to first
886 // sort the list of module-level globals in def-use order. We visit each
887 // global variable in order, and ensure that we emit it *after* its dependent
888 // globals. We use a little extra memory maintaining both a set and a list to
889 // have fast searches while maintaining a strict ordering.
Justin Holewinski01f89f02013-05-20 12:13:32 +0000890 SmallVector<const GlobalVariable *, 8> Globals;
891 DenseSet<const GlobalVariable *> GVVisited;
892 DenseSet<const GlobalVariable *> GVVisiting;
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000893
894 // Visit each global variable, in order
Duncan P. N. Exon Smith61149b82015-10-20 00:54:09 +0000895 for (const GlobalVariable &I : M.globals())
896 VisitGlobalVariableForEmission(&I, Globals, GVVisited, GVVisiting);
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000897
Justin Holewinski0497ab12013-03-30 14:29:21 +0000898 assert(GVVisited.size() == M.getGlobalList().size() &&
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000899 "Missed a global variable");
900 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
901
902 // Print out module-level global variables in proper order
903 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
904 printModuleLevelGV(Globals[i], OS2);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000905
906 OS2 << '\n';
907
Lang Hames9ff69c82015-04-24 19:11:51 +0000908 OutStreamer->EmitRawText(OS2.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000909}
910
Eric Christopher6aad8b12015-02-19 00:08:14 +0000911void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O,
912 const NVPTXSubtarget &STI) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000913 O << "//\n";
914 O << "// Generated by LLVM NVPTX Back-End\n";
915 O << "//\n";
916 O << "\n";
917
Eric Christopher6aad8b12015-02-19 00:08:14 +0000918 unsigned PTXVersion = STI.getPTXVersion();
Justin Holewinski1812ee92012-11-12 03:16:43 +0000919 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000920
921 O << ".target ";
Eric Christopher6aad8b12015-02-19 00:08:14 +0000922 O << STI.getTargetName();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000923
Eric Christopherca929f22015-02-19 00:22:47 +0000924 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
925 if (NTM.getDrvInterface() == NVPTX::NVCL)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000926 O << ", texmode_independent";
Eric Christopherbeffc4e2015-02-19 00:08:23 +0000927 else {
Eric Christopher6aad8b12015-02-19 00:08:14 +0000928 if (!STI.hasDouble())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000929 O << ", map_f64_to_f32";
930 }
931
932 if (MAI->doesSupportDebugInformation())
933 O << ", debug";
934
935 O << "\n";
936
937 O << ".address_size ";
Eric Christopherca929f22015-02-19 00:22:47 +0000938 if (NTM.is64Bit())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000939 O << "64";
940 else
941 O << "32";
942 O << "\n";
943
944 O << "\n";
945}
946
947bool NVPTXAsmPrinter::doFinalization(Module &M) {
Justin Holewinski01f89f02013-05-20 12:13:32 +0000948 // If we did not emit any functions, then the global declarations have not
949 // yet been emitted.
950 if (!GlobalsEmitted) {
951 emitGlobals(M);
952 GlobalsEmitted = true;
953 }
954
Justin Holewinskiae556d32012-05-04 20:18:50 +0000955 // XXX Temproarily remove global variables so that doFinalization() will not
956 // emit them again (global variables are emitted at beginning).
957
958 Module::GlobalListType &global_list = M.getGlobalList();
959 int i, n = global_list.size();
Dylan Noblesmithc9e2a272014-08-26 02:03:35 +0000960 GlobalVariable **gv_array = new GlobalVariable *[n];
Justin Holewinskiae556d32012-05-04 20:18:50 +0000961
962 // first, back-up GlobalVariable in gv_array
963 i = 0;
964 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000965 I != E; ++I)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000966 gv_array[i++] = &*I;
967
968 // second, empty global_list
969 while (!global_list.empty())
970 global_list.remove(global_list.begin());
971
972 // call doFinalization
973 bool ret = AsmPrinter::doFinalization(M);
974
975 // now we restore global variables
Justin Holewinski0497ab12013-03-30 14:29:21 +0000976 for (i = 0; i < n; i++)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000977 global_list.insert(global_list.end(), gv_array[i]);
978
Justin Holewinski59596952014-04-09 15:38:52 +0000979 clearAnnotationCache(&M);
Dylan Noblesmithc9e2a272014-08-26 02:03:35 +0000980
981 delete[] gv_array;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000982 return ret;
983
Justin Holewinskiae556d32012-05-04 20:18:50 +0000984 //bool Result = AsmPrinter::doFinalization(M);
985 // Instead of calling the parents doFinalization, we may
986 // clone parents doFinalization and customize here.
987 // Currently, we if NVISA out the EmitGlobals() in
988 // parent's doFinalization, which is too intrusive.
989 //
990 // Same for the doInitialization.
991 //return Result;
992}
993
994// This function emits appropriate linkage directives for
995// functions and global variables.
996//
997// extern function declaration -> .extern
998// extern function definition -> .visible
999// external global variable with init -> .visible
1000// external without init -> .extern
1001// appending -> not allowed, assert.
Justin Holewinski7d5bf662014-06-27 18:35:10 +00001002// for any linkage other than
1003// internal, private, linker_private,
1004// linker_private_weak, linker_private_weak_def_auto,
1005// we emit -> .weak.
Justin Holewinskiae556d32012-05-04 20:18:50 +00001006
Justin Holewinski0497ab12013-03-30 14:29:21 +00001007void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1008 raw_ostream &O) {
Eric Christopherbeffc4e2015-02-19 00:08:23 +00001009 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001010 if (V->hasExternalLinkage()) {
1011 if (isa<GlobalVariable>(V)) {
1012 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1013 if (GVar) {
1014 if (GVar->hasInitializer())
1015 O << ".visible ";
1016 else
1017 O << ".extern ";
1018 }
1019 } else if (V->isDeclaration())
1020 O << ".extern ";
1021 else
1022 O << ".visible ";
1023 } else if (V->hasAppendingLinkage()) {
1024 std::string msg;
1025 msg.append("Error: ");
1026 msg.append("Symbol ");
1027 if (V->hasName())
Yaron Keren075759a2015-03-30 15:42:36 +00001028 msg.append(V->getName());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001029 msg.append("has unsupported appending linkage type");
1030 llvm_unreachable(msg.c_str());
Justin Holewinski7d5bf662014-06-27 18:35:10 +00001031 } else if (!V->hasInternalLinkage() &&
1032 !V->hasPrivateLinkage()) {
1033 O << ".weak ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001034 }
1035 }
1036}
1037
Justin Holewinski01f89f02013-05-20 12:13:32 +00001038void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1039 raw_ostream &O,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001040 bool processDemoted) {
1041
1042 // Skip meta data
1043 if (GVar->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001044 if (GVar->getSection() == "llvm.metadata")
Justin Holewinskiae556d32012-05-04 20:18:50 +00001045 return;
1046 }
1047
Justin Holewinski73cb5de2014-06-27 18:35:53 +00001048 // Skip LLVM intrinsic global variables
1049 if (GVar->getName().startswith("llvm.") ||
1050 GVar->getName().startswith("nvvm."))
1051 return;
1052
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001053 const DataLayout &DL = getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001054
1055 // GlobalVariables are always constant pointers themselves.
Craig Toppere3dcce92015-08-01 22:20:21 +00001056 PointerType *PTy = GVar->getType();
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001057 Type *ETy = GVar->getValueType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001058
1059 if (GVar->hasExternalLinkage()) {
1060 if (GVar->hasInitializer())
1061 O << ".visible ";
1062 else
1063 O << ".extern ";
Justin Holewinskid73767a2014-06-27 18:35:56 +00001064 } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1065 GVar->hasAvailableExternallyLinkage() ||
1066 GVar->hasCommonLinkage()) {
1067 O << ".weak ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001068 }
1069
1070 if (llvm::isTexture(*GVar)) {
1071 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1072 return;
1073 }
1074
1075 if (llvm::isSurface(*GVar)) {
1076 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1077 return;
1078 }
1079
1080 if (GVar->isDeclaration()) {
1081 // (extern) declarations, no definition or initializer
1082 // Currently the only known declaration is for an automatic __local
1083 // (.shared) promoted to global.
1084 emitPTXGlobalVariable(GVar, O);
1085 O << ";\n";
1086 return;
1087 }
1088
1089 if (llvm::isSampler(*GVar)) {
1090 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1091
Craig Topper062a2ba2014-04-25 05:30:21 +00001092 const Constant *Initializer = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001093 if (GVar->hasInitializer())
1094 Initializer = GVar->getInitializer();
Craig Topper062a2ba2014-04-25 05:30:21 +00001095 const ConstantInt *CI = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001096 if (Initializer)
1097 CI = dyn_cast<ConstantInt>(Initializer);
1098 if (CI) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001099 unsigned sample = CI->getZExtValue();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001100
1101 O << " = { ";
1102
Justin Holewinski0497ab12013-03-30 14:29:21 +00001103 for (int i = 0,
1104 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1105 i < 3; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001106 O << "addr_mode_" << i << " = ";
1107 switch (addr) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001108 case 0:
1109 O << "wrap";
1110 break;
1111 case 1:
1112 O << "clamp_to_border";
1113 break;
1114 case 2:
1115 O << "clamp_to_edge";
1116 break;
1117 case 3:
1118 O << "wrap";
1119 break;
1120 case 4:
1121 O << "mirror";
1122 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001123 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001124 O << ", ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001125 }
1126 O << "filter_mode = ";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001127 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1128 case 0:
1129 O << "nearest";
1130 break;
1131 case 1:
1132 O << "linear";
1133 break;
1134 case 2:
Craig Topper2a30d782014-06-18 05:05:13 +00001135 llvm_unreachable("Anisotropic filtering is not supported");
Justin Holewinski0497ab12013-03-30 14:29:21 +00001136 default:
1137 O << "nearest";
1138 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001139 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001140 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001141 O << ", force_unnormalized_coords = 1";
1142 }
1143 O << " }";
1144 }
1145
1146 O << ";\n";
1147 return;
1148 }
1149
1150 if (GVar->hasPrivateLinkage()) {
1151
1152 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1153 return;
1154
1155 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1156 if (!strncmp(GVar->getName().data(), "filename", 8))
1157 return;
1158 if (GVar->use_empty())
1159 return;
1160 }
1161
Craig Topper062a2ba2014-04-25 05:30:21 +00001162 const Function *demotedFunc = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001163 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
Yaron Keren075759a2015-03-30 15:42:36 +00001164 O << "// " << GVar->getName() << " has been demoted\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001165 if (localDecls.find(demotedFunc) != localDecls.end())
1166 localDecls[demotedFunc].push_back(GVar);
1167 else {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001168 std::vector<const GlobalVariable *> temp;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001169 temp.push_back(GVar);
1170 localDecls[demotedFunc] = temp;
1171 }
1172 return;
1173 }
1174
1175 O << ".";
1176 emitPTXAddressSpace(PTy->getAddressSpace(), O);
Justin Holewinski773ca402014-06-27 18:35:58 +00001177
1178 if (isManaged(*GVar)) {
1179 O << " .attribute(.managed)";
1180 }
1181
Justin Holewinskiae556d32012-05-04 20:18:50 +00001182 if (GVar->getAlignment() == 0)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001183 O << " .align " << (int)DL.getPrefTypeAlignment(ETy);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001184 else
1185 O << " .align " << GVar->getAlignment();
1186
Jingyue Wue4c9cf02014-12-17 17:59:04 +00001187 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001188 O << " .";
Justin Holewinski700b6fa2013-05-20 12:13:28 +00001189 // Special case: ABI requires that we use .u8 for predicates
1190 if (ETy->isIntegerTy(1))
1191 O << "u8";
1192 else
1193 O << getPTXFundamentalTypeStr(ETy, false);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001194 O << " ";
Matt Arsenault8b643552015-06-09 00:31:39 +00001195 getSymbol(GVar)->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001196
1197 // Ptx allows variable initilization only for constant and global state
1198 // spaces.
Justin Holewinski549c7732014-06-27 18:36:01 +00001199 if (GVar->hasInitializer()) {
1200 if ((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1201 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) {
1202 const Constant *Initializer = GVar->getInitializer();
Jingyue Wu312fd022015-04-24 02:57:30 +00001203 // 'undef' is treated as there is no value specified.
Justin Holewinski549c7732014-06-27 18:36:01 +00001204 if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1205 O << " = ";
1206 printScalarConstant(Initializer, O);
1207 }
1208 } else {
Jingyue Wufcec0982015-08-22 05:40:26 +00001209 // The frontend adds zero-initializer to device and constant variables
1210 // that don't have an initial value, and UndefValue to shared
1211 // variables, so skip warning for this case.
1212 if (!GVar->getInitializer()->isNullValue() &&
1213 !isa<UndefValue>(GVar->getInitializer())) {
Benjamin Kramerdba7ee92015-05-28 11:24:24 +00001214 report_fatal_error("initial value of '" + GVar->getName() +
1215 "' is not allowed in addrspace(" +
1216 Twine(PTy->getAddressSpace()) + ")");
Justin Holewinski549c7732014-06-27 18:36:01 +00001217 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001218 }
1219 }
1220 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001221 unsigned int ElementSize = 0;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001222
1223 // Although PTX has direct support for struct type and array type and
1224 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1225 // targets that support these high level field accesses. Structs, arrays
1226 // and vectors are lowered into arrays of bytes.
1227 switch (ETy->getTypeID()) {
1228 case Type::StructTyID:
1229 case Type::ArrayTyID:
1230 case Type::VectorTyID:
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001231 ElementSize = DL.getTypeStoreSize(ETy);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001232 // Ptx allows variable initilization only for constant and
1233 // global state spaces.
1234 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
Justin Holewinski0497ab12013-03-30 14:29:21 +00001235 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1236 GVar->hasInitializer()) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001237 const Constant *Initializer = GVar->getInitializer();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001238 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001239 AggBuffer aggBuffer(ElementSize, O, *this);
1240 bufferAggregateConstant(Initializer, &aggBuffer);
1241 if (aggBuffer.numSymbols) {
Eric Christopher6aad8b12015-02-19 00:08:14 +00001242 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit()) {
Matt Arsenault8b643552015-06-09 00:31:39 +00001243 O << " .u64 ";
1244 getSymbol(GVar)->print(O, MAI);
1245 O << "[";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001246 O << ElementSize / 8;
1247 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001248 O << " .u32 ";
1249 getSymbol(GVar)->print(O, MAI);
1250 O << "[";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001251 O << ElementSize / 4;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001252 }
1253 O << "]";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001254 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001255 O << " .b8 ";
1256 getSymbol(GVar)->print(O, MAI);
1257 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001258 O << ElementSize;
1259 O << "]";
1260 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001261 O << " = {";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001262 aggBuffer.print();
1263 O << "}";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001264 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001265 O << " .b8 ";
1266 getSymbol(GVar)->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001267 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001268 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001269 O << ElementSize;
1270 O << "]";
1271 }
1272 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001273 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001274 O << " .b8 ";
1275 getSymbol(GVar)->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001276 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001277 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001278 O << ElementSize;
1279 O << "]";
1280 }
1281 }
1282 break;
1283 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001284 llvm_unreachable("type not supported yet");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001285 }
1286
1287 }
1288 O << ";\n";
1289}
1290
1291void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1292 if (localDecls.find(f) == localDecls.end())
1293 return;
1294
Justin Holewinski01f89f02013-05-20 12:13:32 +00001295 std::vector<const GlobalVariable *> &gvars = localDecls[f];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001296
Justin Holewinski0497ab12013-03-30 14:29:21 +00001297 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001298 O << "\t// demoted variable\n\t";
1299 printModuleLevelGV(gvars[i], O, true);
1300 }
1301}
1302
1303void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1304 raw_ostream &O) const {
1305 switch (AddressSpace) {
1306 case llvm::ADDRESS_SPACE_LOCAL:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001307 O << "local";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001308 break;
1309 case llvm::ADDRESS_SPACE_GLOBAL:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001310 O << "global";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001311 break;
1312 case llvm::ADDRESS_SPACE_CONST:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001313 O << "const";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001314 break;
1315 case llvm::ADDRESS_SPACE_SHARED:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001316 O << "shared";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001317 break;
1318 default:
Justin Holewinski36a50992013-02-09 13:34:15 +00001319 report_fatal_error("Bad address space found while emitting PTX");
1320 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001321 }
1322}
1323
Justin Holewinski0497ab12013-03-30 14:29:21 +00001324std::string
Craig Toppere3dcce92015-08-01 22:20:21 +00001325NVPTXAsmPrinter::getPTXFundamentalTypeStr(Type *Ty, bool useB4PTR) const {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001326 switch (Ty->getTypeID()) {
1327 default:
1328 llvm_unreachable("unexpected type");
1329 break;
1330 case Type::IntegerTyID: {
1331 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1332 if (NumBits == 1)
1333 return "pred";
1334 else if (NumBits <= 64) {
1335 std::string name = "u";
1336 return name + utostr(NumBits);
1337 } else {
1338 llvm_unreachable("Integer too large");
1339 break;
1340 }
1341 break;
1342 }
1343 case Type::FloatTyID:
1344 return "f32";
1345 case Type::DoubleTyID:
1346 return "f64";
1347 case Type::PointerTyID:
Eric Christopher6aad8b12015-02-19 00:08:14 +00001348 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit())
Justin Holewinski0497ab12013-03-30 14:29:21 +00001349 if (useB4PTR)
1350 return "b64";
1351 else
1352 return "u64";
1353 else if (useB4PTR)
1354 return "b32";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001355 else
Justin Holewinski0497ab12013-03-30 14:29:21 +00001356 return "u32";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001357 }
1358 llvm_unreachable("unexpected type");
Craig Topper062a2ba2014-04-25 05:30:21 +00001359 return nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001360}
1361
Justin Holewinski0497ab12013-03-30 14:29:21 +00001362void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001363 raw_ostream &O) {
1364
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001365 const DataLayout &DL = getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001366
1367 // GlobalVariables are always constant pointers themselves.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001368 Type *ETy = GVar->getValueType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001369
1370 O << ".";
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001371 emitPTXAddressSpace(GVar->getType()->getAddressSpace(), O);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001372 if (GVar->getAlignment() == 0)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001373 O << " .align " << (int)DL.getPrefTypeAlignment(ETy);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001374 else
1375 O << " .align " << GVar->getAlignment();
1376
Jingyue Wue4c9cf02014-12-17 17:59:04 +00001377 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001378 O << " .";
1379 O << getPTXFundamentalTypeStr(ETy);
1380 O << " ";
Matt Arsenault8b643552015-06-09 00:31:39 +00001381 getSymbol(GVar)->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001382 return;
1383 }
1384
Justin Holewinski0497ab12013-03-30 14:29:21 +00001385 int64_t ElementSize = 0;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001386
1387 // Although PTX has direct support for struct type and array type and LLVM IR
1388 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1389 // support these high level field accesses. Structs and arrays are lowered
1390 // into arrays of bytes.
1391 switch (ETy->getTypeID()) {
1392 case Type::StructTyID:
1393 case Type::ArrayTyID:
1394 case Type::VectorTyID:
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001395 ElementSize = DL.getTypeStoreSize(ETy);
Matt Arsenault8b643552015-06-09 00:31:39 +00001396 O << " .b8 ";
1397 getSymbol(GVar)->print(O, MAI);
1398 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001399 if (ElementSize) {
Benjamin Kramerdba7ee92015-05-28 11:24:24 +00001400 O << ElementSize;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001401 }
1402 O << "]";
1403 break;
1404 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001405 llvm_unreachable("type not supported yet");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001406 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001407 return;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001408}
1409
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001410static unsigned int getOpenCLAlignment(const DataLayout &DL, Type *Ty) {
Rafael Espindola08013342013-12-07 19:34:20 +00001411 if (Ty->isSingleValueType())
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001412 return DL.getPrefTypeAlignment(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001413
Craig Toppere3dcce92015-08-01 22:20:21 +00001414 auto *ATy = dyn_cast<ArrayType>(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001415 if (ATy)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001416 return getOpenCLAlignment(DL, ATy->getElementType());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001417
Craig Toppere3dcce92015-08-01 22:20:21 +00001418 auto *STy = dyn_cast<StructType>(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001419 if (STy) {
1420 unsigned int alignStruct = 1;
1421 // Go through each element of the struct and find the
1422 // largest alignment.
Justin Holewinski0497ab12013-03-30 14:29:21 +00001423 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001424 Type *ETy = STy->getElementType(i);
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001425 unsigned int align = getOpenCLAlignment(DL, ETy);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001426 if (align > alignStruct)
1427 alignStruct = align;
1428 }
1429 return alignStruct;
1430 }
1431
Craig Toppere3dcce92015-08-01 22:20:21 +00001432 auto *FTy = dyn_cast<FunctionType>(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001433 if (FTy)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001434 return DL.getPointerPrefAlignment();
1435 return DL.getPrefTypeAlignment(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001436}
1437
1438void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1439 int paramIndex, raw_ostream &O) {
Matt Arsenault8b643552015-06-09 00:31:39 +00001440 getSymbol(I->getParent())->print(O, MAI);
1441 O << "_param_" << paramIndex;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001442}
1443
Justin Holewinski0497ab12013-03-30 14:29:21 +00001444void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001445 const DataLayout &DL = getDataLayout();
Bill Wendlinge94d8432012-12-07 23:16:57 +00001446 const AttributeSet &PAL = F->getAttributes();
Eric Christopher6aad8b12015-02-19 00:08:14 +00001447 const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001448 Function::const_arg_iterator I, E;
1449 unsigned paramIndex = 0;
1450 bool first = true;
1451 bool isKernelFunc = llvm::isKernelFunction(*F);
Eric Christopher6aad8b12015-02-19 00:08:14 +00001452 bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001453 MVT thePointerTy = TLI->getPointerTy(DL);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001454
Justin Lebar2a161f92016-01-23 21:12:17 +00001455 if (F->arg_empty()) {
1456 O << "()\n";
1457 return;
1458 }
1459
Justin Holewinskiae556d32012-05-04 20:18:50 +00001460 O << "(\n";
1461
1462 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
Justin Holewinskie9884092013-03-24 21:17:47 +00001463 Type *Ty = I->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001464
1465 if (!first)
1466 O << ",\n";
1467
1468 first = false;
1469
1470 // Handle image/sampler parameters
Justin Holewinski30d56a72014-04-09 15:39:15 +00001471 if (isKernelFunction(*F)) {
1472 if (isSampler(*I) || isImage(*I)) {
1473 if (isImage(*I)) {
1474 std::string sname = I->getName();
1475 if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
Eric Christopher6aad8b12015-02-19 00:08:14 +00001476 if (nvptxSubtarget->hasImageHandles())
Justin Holewinski30d56a72014-04-09 15:39:15 +00001477 O << "\t.param .u64 .ptr .surfref ";
1478 else
1479 O << "\t.param .surfref ";
Matt Arsenault8b643552015-06-09 00:31:39 +00001480 CurrentFnSym->print(O, MAI);
1481 O << "_param_" << paramIndex;
Justin Holewinski30d56a72014-04-09 15:39:15 +00001482 }
1483 else { // Default image is read_only
Eric Christopher6aad8b12015-02-19 00:08:14 +00001484 if (nvptxSubtarget->hasImageHandles())
Justin Holewinski30d56a72014-04-09 15:39:15 +00001485 O << "\t.param .u64 .ptr .texref ";
1486 else
1487 O << "\t.param .texref ";
Matt Arsenault8b643552015-06-09 00:31:39 +00001488 CurrentFnSym->print(O, MAI);
1489 O << "_param_" << paramIndex;
Justin Holewinski30d56a72014-04-09 15:39:15 +00001490 }
1491 } else {
Eric Christopher6aad8b12015-02-19 00:08:14 +00001492 if (nvptxSubtarget->hasImageHandles())
Justin Holewinski30d56a72014-04-09 15:39:15 +00001493 O << "\t.param .u64 .ptr .samplerref ";
1494 else
1495 O << "\t.param .samplerref ";
Matt Arsenault8b643552015-06-09 00:31:39 +00001496 CurrentFnSym->print(O, MAI);
1497 O << "_param_" << paramIndex;
Justin Holewinski30d56a72014-04-09 15:39:15 +00001498 }
1499 continue;
1500 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001501 }
1502
Eli Bendersky3e840192015-03-23 16:26:23 +00001503 if (!PAL.hasAttribute(paramIndex + 1, Attribute::ByVal)) {
Gautam Chakrabarti2c283402014-01-28 18:35:29 +00001504 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1505 // Just print .param .align <a> .b8 .param[size];
Justin Holewinskie9884092013-03-24 21:17:47 +00001506 // <a> = PAL.getparamalignment
1507 // size = typeallocsize of element type
Justin Holewinski0497ab12013-03-30 14:29:21 +00001508 unsigned align = PAL.getParamAlignment(paramIndex + 1);
Justin Holewinskie9884092013-03-24 21:17:47 +00001509 if (align == 0)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001510 align = DL.getABITypeAlignment(Ty);
Justin Holewinskie9884092013-03-24 21:17:47 +00001511
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001512 unsigned sz = DL.getTypeAllocSize(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001513 O << "\t.param .align " << align << " .b8 ";
Justin Holewinskie9884092013-03-24 21:17:47 +00001514 printParamName(I, paramIndex, O);
1515 O << "[" << sz << "]";
1516
1517 continue;
1518 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001519 // Just a scalar
Craig Toppere3dcce92015-08-01 22:20:21 +00001520 auto *PTy = dyn_cast<PointerType>(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001521 if (isKernelFunc) {
1522 if (PTy) {
1523 // Special handling for pointer arguments to kernel
1524 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1525
Eric Christopherbeffc4e2015-02-19 00:08:23 +00001526 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() !=
1527 NVPTX::CUDA) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001528 Type *ETy = PTy->getElementType();
1529 int addrSpace = PTy->getAddressSpace();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001530 switch (addrSpace) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001531 default:
1532 O << ".ptr ";
1533 break;
Justin Holewinskib96d1392013-06-10 13:29:47 +00001534 case llvm::ADDRESS_SPACE_CONST:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001535 O << ".ptr .const ";
1536 break;
1537 case llvm::ADDRESS_SPACE_SHARED:
1538 O << ".ptr .shared ";
1539 break;
1540 case llvm::ADDRESS_SPACE_GLOBAL:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001541 O << ".ptr .global ";
1542 break;
1543 }
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001544 O << ".align " << (int)getOpenCLAlignment(DL, ETy) << " ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001545 }
1546 printParamName(I, paramIndex, O);
1547 continue;
1548 }
1549
1550 // non-pointer scalar to kernel func
Justin Holewinski700b6fa2013-05-20 12:13:28 +00001551 O << "\t.param .";
1552 // Special case: predicate operands become .u8 types
1553 if (Ty->isIntegerTy(1))
1554 O << "u8";
1555 else
1556 O << getPTXFundamentalTypeStr(Ty);
1557 O << " ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001558 printParamName(I, paramIndex, O);
1559 continue;
1560 }
1561 // Non-kernel function, just print .param .b<size> for ABI
Alp Tokerf907b892013-12-05 05:44:44 +00001562 // and .reg .b<size> for non-ABI
Justin Holewinskiae556d32012-05-04 20:18:50 +00001563 unsigned sz = 0;
1564 if (isa<IntegerType>(Ty)) {
1565 sz = cast<IntegerType>(Ty)->getBitWidth();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001566 if (sz < 32)
1567 sz = 32;
1568 } else if (isa<PointerType>(Ty))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001569 sz = thePointerTy.getSizeInBits();
1570 else
1571 sz = Ty->getPrimitiveSizeInBits();
1572 if (isABI)
1573 O << "\t.param .b" << sz << " ";
1574 else
1575 O << "\t.reg .b" << sz << " ";
1576 printParamName(I, paramIndex, O);
1577 continue;
1578 }
1579
1580 // param has byVal attribute. So should be a pointer
Craig Toppere3dcce92015-08-01 22:20:21 +00001581 auto *PTy = dyn_cast<PointerType>(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001582 assert(PTy && "Param with byval attribute should be a pointer type");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001583 Type *ETy = PTy->getElementType();
1584
1585 if (isABI || isKernelFunc) {
Gautam Chakrabarti2c283402014-01-28 18:35:29 +00001586 // Just print .param .align <a> .b8 .param[size];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001587 // <a> = PAL.getparamalignment
1588 // size = typeallocsize of element type
Justin Holewinski0497ab12013-03-30 14:29:21 +00001589 unsigned align = PAL.getParamAlignment(paramIndex + 1);
Justin Holewinski2dc9d072012-11-09 23:50:24 +00001590 if (align == 0)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001591 align = DL.getABITypeAlignment(ETy);
Justin Holewinski2dc9d072012-11-09 23:50:24 +00001592
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001593 unsigned sz = DL.getTypeAllocSize(ETy);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001594 O << "\t.param .align " << align << " .b8 ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001595 printParamName(I, paramIndex, O);
1596 O << "[" << sz << "]";
1597 continue;
1598 } else {
1599 // Split the ETy into constituent parts and
1600 // print .param .b<size> <name> for each part.
1601 // Further, if a part is vector, print the above for
1602 // each vector element.
1603 SmallVector<EVT, 16> vtparts;
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001604 ComputeValueVTs(*TLI, DL, ETy, vtparts);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001605 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001606 unsigned elems = 1;
1607 EVT elemtype = vtparts[i];
1608 if (vtparts[i].isVector()) {
1609 elems = vtparts[i].getVectorNumElements();
1610 elemtype = vtparts[i].getVectorElementType();
1611 }
1612
Justin Holewinski0497ab12013-03-30 14:29:21 +00001613 for (unsigned j = 0, je = elems; j != je; ++j) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001614 unsigned sz = elemtype.getSizeInBits();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001615 if (elemtype.isInteger() && (sz < 32))
1616 sz = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001617 O << "\t.reg .b" << sz << " ";
1618 printParamName(I, paramIndex, O);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001619 if (j < je - 1)
1620 O << ",\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001621 ++paramIndex;
1622 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001623 if (i < e - 1)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001624 O << ",\n";
1625 }
1626 --paramIndex;
1627 continue;
1628 }
1629 }
1630
1631 O << "\n)\n";
1632}
1633
1634void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1635 raw_ostream &O) {
1636 const Function *F = MF.getFunction();
1637 emitFunctionParamList(F, O);
1638}
1639
Justin Holewinski0497ab12013-03-30 14:29:21 +00001640void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1641 const MachineFunction &MF) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001642 SmallString<128> Str;
1643 raw_svector_ostream O(Str);
1644
1645 // Map the global virtual register number to a register class specific
1646 // virtual register number starting from 1 with that class.
Eric Christopherfc6de422014-08-05 02:39:49 +00001647 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001648 //unsigned numRegClasses = TRI->getNumRegClasses();
1649
1650 // Emit the Fake Stack Object
1651 const MachineFrameInfo *MFI = MF.getFrameInfo();
1652 int NumBytes = (int) MFI->getStackSize();
1653 if (NumBytes) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001654 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1655 << getFunctionNumber() << "[" << NumBytes << "];\n";
Eric Christopher02389e32015-02-19 00:08:27 +00001656 if (static_cast<const NVPTXTargetMachine &>(MF.getTarget()).is64Bit()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001657 O << "\t.reg .b64 \t%SP;\n";
1658 O << "\t.reg .b64 \t%SPL;\n";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001659 } else {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001660 O << "\t.reg .b32 \t%SP;\n";
1661 O << "\t.reg .b32 \t%SPL;\n";
1662 }
1663 }
1664
1665 // Go through all virtual registers to establish the mapping between the
1666 // global virtual
1667 // register number and the per class virtual register number.
1668 // We use the per class virtual register number in the ptx output.
1669 unsigned int numVRs = MRI->getNumVirtRegs();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001670 for (unsigned i = 0; i < numVRs; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001671 unsigned int vr = TRI->index2VirtReg(i);
1672 const TargetRegisterClass *RC = MRI->getRegClass(vr);
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001673 DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001674 int n = regmap.size();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001675 regmap.insert(std::make_pair(vr, n + 1));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001676 }
1677
1678 // Emit register declarations
1679 // @TODO: Extract out the real register usage
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001680 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1681 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1682 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1683 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
Justin Holewinski3e037d92014-07-16 16:26:58 +00001684 // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001685 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
Justin Holewinski3e037d92014-07-16 16:26:58 +00001686 // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001687
1688 // Emit declaration of the virtual registers or 'physical' registers for
1689 // each register class
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001690 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1691 const TargetRegisterClass *RC = TRI->getRegClass(i);
1692 DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
1693 std::string rcname = getNVPTXRegClassName(RC);
1694 std::string rcStr = getNVPTXRegClassStr(RC);
1695 int n = regmap.size();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001696
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001697 // Only declare those registers that may be used.
1698 if (n) {
1699 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1700 << ">;\n";
1701 }
1702 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001703
Lang Hames9ff69c82015-04-24 19:11:51 +00001704 OutStreamer->EmitRawText(O.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001705}
1706
Justin Holewinskiae556d32012-05-04 20:18:50 +00001707void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001708 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
Justin Holewinskiae556d32012-05-04 20:18:50 +00001709 bool ignored;
1710 unsigned int numHex;
1711 const char *lead;
1712
Justin Holewinski0497ab12013-03-30 14:29:21 +00001713 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001714 numHex = 8;
1715 lead = "0f";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001716 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001717 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1718 numHex = 16;
1719 lead = "0d";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001720 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001721 } else
1722 llvm_unreachable("unsupported fp type");
1723
1724 APInt API = APF.bitcastToAPInt();
1725 std::string hexstr(utohexstr(API.getZExtValue()));
1726 O << lead;
1727 if (hexstr.length() < numHex)
1728 O << std::string(numHex - hexstr.length(), '0');
1729 O << utohexstr(API.getZExtValue());
1730}
1731
Justin Holewinski01f89f02013-05-20 12:13:32 +00001732void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1733 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001734 O << CI->getValue();
1735 return;
1736 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001737 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001738 printFPConstant(CFP, O);
1739 return;
1740 }
1741 if (isa<ConstantPointerNull>(CPV)) {
1742 O << "0";
1743 return;
1744 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001745 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
Justin Holewinski9d852a82014-04-09 15:39:11 +00001746 bool IsNonGenericPointer = false;
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001747 if (GVar->getType()->getAddressSpace() != 0) {
Justin Holewinski9d852a82014-04-09 15:39:11 +00001748 IsNonGenericPointer = true;
1749 }
1750 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1751 O << "generic(";
Matt Arsenault8b643552015-06-09 00:31:39 +00001752 getSymbol(GVar)->print(O, MAI);
Justin Holewinski9d852a82014-04-09 15:39:11 +00001753 O << ")";
1754 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001755 getSymbol(GVar)->print(O, MAI);
Justin Holewinski9d852a82014-04-09 15:39:11 +00001756 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001757 return;
1758 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001759 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1760 const Value *v = Cexpr->stripPointerCasts();
Justin Holewinski9d852a82014-04-09 15:39:11 +00001761 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1762 bool IsNonGenericPointer = false;
1763 if (PTy && PTy->getAddressSpace() != 0) {
1764 IsNonGenericPointer = true;
1765 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001766 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
Justin Holewinski9d852a82014-04-09 15:39:11 +00001767 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1768 O << "generic(";
Matt Arsenault8b643552015-06-09 00:31:39 +00001769 getSymbol(GVar)->print(O, MAI);
Justin Holewinski9d852a82014-04-09 15:39:11 +00001770 O << ")";
1771 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001772 getSymbol(GVar)->print(O, MAI);
Justin Holewinski9d852a82014-04-09 15:39:11 +00001773 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001774 return;
1775 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001776 lowerConstant(CPV)->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001777 return;
1778 }
1779 }
1780 llvm_unreachable("Not scalar type found in printScalarConstant()");
1781}
1782
Samuel Antaocd501352015-06-09 16:29:34 +00001783// These utility functions assure we get the right sequence of bytes for a given
1784// type even for big-endian machines
1785template <typename T> static void ConvertIntToBytes(unsigned char *p, T val) {
1786 int64_t vp = (int64_t)val;
1787 for (unsigned i = 0; i < sizeof(T); ++i) {
1788 p[i] = (unsigned char)vp;
1789 vp >>= 8;
1790 }
1791}
1792static void ConvertFloatToBytes(unsigned char *p, float val) {
1793 int32_t *vp = (int32_t *)&val;
1794 for (unsigned i = 0; i < sizeof(int32_t); ++i) {
1795 p[i] = (unsigned char)*vp;
1796 *vp >>= 8;
1797 }
1798}
1799static void ConvertDoubleToBytes(unsigned char *p, double val) {
1800 int64_t *vp = (int64_t *)&val;
1801 for (unsigned i = 0; i < sizeof(int64_t); ++i) {
1802 p[i] = (unsigned char)*vp;
1803 *vp >>= 8;
1804 }
1805}
1806
Justin Holewinski01f89f02013-05-20 12:13:32 +00001807void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001808 AggBuffer *aggBuffer) {
1809
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001810 const DataLayout &DL = getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001811
1812 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001813 int s = DL.getTypeAllocSize(CPV->getType());
Justin Holewinski0497ab12013-03-30 14:29:21 +00001814 if (s < Bytes)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001815 s = Bytes;
1816 aggBuffer->addZeros(s);
1817 return;
1818 }
1819
Samuel Antaocd501352015-06-09 16:29:34 +00001820 unsigned char ptr[8];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001821 switch (CPV->getType()->getTypeID()) {
1822
1823 case Type::IntegerTyID: {
Craig Toppere3dcce92015-08-01 22:20:21 +00001824 Type *ETy = CPV->getType();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001825 if (ETy == Type::getInt8Ty(CPV->getContext())) {
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001826 unsigned char c = (unsigned char)cast<ConstantInt>(CPV)->getZExtValue();
Samuel Antaocd501352015-06-09 16:29:34 +00001827 ConvertIntToBytes<>(ptr, c);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001828 aggBuffer->addBytes(ptr, 1, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001829 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001830 short int16 = (short)cast<ConstantInt>(CPV)->getZExtValue();
Samuel Antaocd501352015-06-09 16:29:34 +00001831 ConvertIntToBytes<>(ptr, int16);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001832 aggBuffer->addBytes(ptr, 2, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001833 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001834 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001835 int int32 = (int)(constInt->getZExtValue());
Samuel Antaocd501352015-06-09 16:29:34 +00001836 ConvertIntToBytes<>(ptr, int32);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001837 aggBuffer->addBytes(ptr, 4, Bytes);
1838 break;
Justin Holewinski01f89f02013-05-20 12:13:32 +00001839 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1840 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001841 ConstantFoldConstantExpression(Cexpr, DL))) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001842 int int32 = (int)(constInt->getZExtValue());
Samuel Antaocd501352015-06-09 16:29:34 +00001843 ConvertIntToBytes<>(ptr, int32);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001844 aggBuffer->addBytes(ptr, 4, Bytes);
1845 break;
1846 }
1847 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1848 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
Jingyue Wu312fd022015-04-24 02:57:30 +00001849 aggBuffer->addSymbol(v, Cexpr->getOperand(0));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001850 aggBuffer->addZeros(4);
1851 break;
1852 }
1853 }
Craig Topperbdf39a42012-05-24 07:02:50 +00001854 llvm_unreachable("unsupported integer const type");
Justin Holewinski0497ab12013-03-30 14:29:21 +00001855 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001856 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001857 long long int64 = (long long)(constInt->getZExtValue());
Samuel Antaocd501352015-06-09 16:29:34 +00001858 ConvertIntToBytes<>(ptr, int64);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001859 aggBuffer->addBytes(ptr, 8, Bytes);
1860 break;
Justin Holewinski01f89f02013-05-20 12:13:32 +00001861 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1862 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001863 ConstantFoldConstantExpression(Cexpr, DL))) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001864 long long int64 = (long long)(constInt->getZExtValue());
Samuel Antaocd501352015-06-09 16:29:34 +00001865 ConvertIntToBytes<>(ptr, int64);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001866 aggBuffer->addBytes(ptr, 8, Bytes);
1867 break;
1868 }
1869 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1870 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
Jingyue Wu312fd022015-04-24 02:57:30 +00001871 aggBuffer->addSymbol(v, Cexpr->getOperand(0));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001872 aggBuffer->addZeros(8);
1873 break;
1874 }
1875 }
1876 llvm_unreachable("unsupported integer const type");
Craig Topperbdf39a42012-05-24 07:02:50 +00001877 } else
Justin Holewinskiae556d32012-05-04 20:18:50 +00001878 llvm_unreachable("unsupported integer const type");
1879 break;
1880 }
1881 case Type::FloatTyID:
1882 case Type::DoubleTyID: {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001883 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
Craig Toppere3dcce92015-08-01 22:20:21 +00001884 Type *Ty = CFP->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001885 if (Ty == Type::getFloatTy(CPV->getContext())) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001886 float float32 = (float) CFP->getValueAPF().convertToFloat();
Samuel Antaocd501352015-06-09 16:29:34 +00001887 ConvertFloatToBytes(ptr, float32);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001888 aggBuffer->addBytes(ptr, 4, Bytes);
1889 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1890 double float64 = CFP->getValueAPF().convertToDouble();
Samuel Antaocd501352015-06-09 16:29:34 +00001891 ConvertDoubleToBytes(ptr, float64);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001892 aggBuffer->addBytes(ptr, 8, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001893 } else {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001894 llvm_unreachable("unsupported fp const type");
1895 }
1896 break;
1897 }
1898 case Type::PointerTyID: {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001899 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
Jingyue Wu312fd022015-04-24 02:57:30 +00001900 aggBuffer->addSymbol(GVar, GVar);
Justin Holewinski01f89f02013-05-20 12:13:32 +00001901 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1902 const Value *v = Cexpr->stripPointerCasts();
Jingyue Wu312fd022015-04-24 02:57:30 +00001903 aggBuffer->addSymbol(v, Cexpr);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001904 }
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001905 unsigned int s = DL.getTypeAllocSize(CPV->getType());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001906 aggBuffer->addZeros(s);
1907 break;
1908 }
1909
1910 case Type::ArrayTyID:
1911 case Type::VectorTyID:
1912 case Type::StructTyID: {
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00001913 if (isa<ConstantAggregate>(CPV) || isa<ConstantDataSequential>(CPV)) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001914 int ElementSize = DL.getTypeAllocSize(CPV->getType());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001915 bufferAggregateConstant(CPV, aggBuffer);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001916 if (Bytes > ElementSize)
1917 aggBuffer->addZeros(Bytes - ElementSize);
1918 } else if (isa<ConstantAggregateZero>(CPV))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001919 aggBuffer->addZeros(Bytes);
1920 else
1921 llvm_unreachable("Unexpected Constant type");
1922 break;
1923 }
1924
1925 default:
1926 llvm_unreachable("unsupported type");
1927 }
1928}
1929
Justin Holewinski01f89f02013-05-20 12:13:32 +00001930void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001931 AggBuffer *aggBuffer) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001932 const DataLayout &DL = getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001933 int Bytes;
1934
1935 // Old constants
1936 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1937 if (CPV->getNumOperands())
1938 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1939 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1940 return;
1941 }
1942
1943 if (const ConstantDataSequential *CDS =
Justin Holewinski0497ab12013-03-30 14:29:21 +00001944 dyn_cast<ConstantDataSequential>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001945 if (CDS->getNumElements())
1946 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1947 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1948 aggBuffer);
1949 return;
1950 }
1951
Justin Holewinskiae556d32012-05-04 20:18:50 +00001952 if (isa<ConstantStruct>(CPV)) {
1953 if (CPV->getNumOperands()) {
1954 StructType *ST = cast<StructType>(CPV->getType());
1955 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001956 if (i == (e - 1))
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001957 Bytes = DL.getStructLayout(ST)->getElementOffset(0) +
1958 DL.getTypeAllocSize(ST) -
1959 DL.getStructLayout(ST)->getElementOffset(i);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001960 else
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001961 Bytes = DL.getStructLayout(ST)->getElementOffset(i + 1) -
1962 DL.getStructLayout(ST)->getElementOffset(i);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001963 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001964 }
1965 }
1966 return;
1967 }
Craig Topperbdf39a42012-05-24 07:02:50 +00001968 llvm_unreachable("unsupported constant type in printAggregateConstant()");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001969}
1970
1971// buildTypeNameMap - Run through symbol table looking for type names.
1972//
1973
Justin Holewinskiae556d32012-05-04 20:18:50 +00001974
Justin Holewinski0497ab12013-03-30 14:29:21 +00001975bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1976 switch (MI.getOpcode()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001977 default:
1978 return false;
Justin Holewinski0497ab12013-03-30 14:29:21 +00001979 case NVPTX::CallArgBeginInst:
1980 case NVPTX::CallArgEndInst0:
1981 case NVPTX::CallArgEndInst1:
1982 case NVPTX::CallArgF32:
1983 case NVPTX::CallArgF64:
1984 case NVPTX::CallArgI16:
1985 case NVPTX::CallArgI32:
1986 case NVPTX::CallArgI32imm:
1987 case NVPTX::CallArgI64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001988 case NVPTX::CallArgParam:
1989 case NVPTX::CallVoidInst:
1990 case NVPTX::CallVoidInstReg:
1991 case NVPTX::Callseq_End:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001992 case NVPTX::CallVoidInstReg64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001993 case NVPTX::DeclareParamInst:
1994 case NVPTX::DeclareRetMemInst:
1995 case NVPTX::DeclareRetRegInst:
1996 case NVPTX::DeclareRetScalarInst:
1997 case NVPTX::DeclareScalarParamInst:
1998 case NVPTX::DeclareScalarRegInst:
1999 case NVPTX::StoreParamF32:
2000 case NVPTX::StoreParamF64:
2001 case NVPTX::StoreParamI16:
2002 case NVPTX::StoreParamI32:
2003 case NVPTX::StoreParamI64:
2004 case NVPTX::StoreParamI8:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002005 case NVPTX::StoreRetvalF32:
2006 case NVPTX::StoreRetvalF64:
2007 case NVPTX::StoreRetvalI16:
2008 case NVPTX::StoreRetvalI32:
2009 case NVPTX::StoreRetvalI64:
2010 case NVPTX::StoreRetvalI8:
2011 case NVPTX::LastCallArgF32:
2012 case NVPTX::LastCallArgF64:
2013 case NVPTX::LastCallArgI16:
2014 case NVPTX::LastCallArgI32:
2015 case NVPTX::LastCallArgI32imm:
2016 case NVPTX::LastCallArgI64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002017 case NVPTX::LastCallArgParam:
2018 case NVPTX::LoadParamMemF32:
2019 case NVPTX::LoadParamMemF64:
2020 case NVPTX::LoadParamMemI16:
2021 case NVPTX::LoadParamMemI32:
2022 case NVPTX::LoadParamMemI64:
2023 case NVPTX::LoadParamMemI8:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002024 case NVPTX::PrototypeInst:
2025 case NVPTX::DBG_VALUE:
Justin Holewinskiae556d32012-05-04 20:18:50 +00002026 return true;
2027 }
2028 return false;
2029}
2030
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002031/// lowerConstantForGV - Return an MCExpr for the given Constant. This is mostly
2032/// a copy from AsmPrinter::lowerConstant, except customized to only handle
2033/// expressions that are representable in PTX and create
2034/// NVPTXGenericMCSymbolRefExpr nodes for addrspacecast instructions.
2035const MCExpr *
2036NVPTXAsmPrinter::lowerConstantForGV(const Constant *CV, bool ProcessingGeneric) {
2037 MCContext &Ctx = OutContext;
2038
2039 if (CV->isNullValue() || isa<UndefValue>(CV))
Jim Grosbach13760bd2015-05-30 01:25:56 +00002040 return MCConstantExpr::create(0, Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002041
2042 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
Jim Grosbach13760bd2015-05-30 01:25:56 +00002043 return MCConstantExpr::create(CI->getZExtValue(), Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002044
2045 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
2046 const MCSymbolRefExpr *Expr =
Jim Grosbach13760bd2015-05-30 01:25:56 +00002047 MCSymbolRefExpr::create(getSymbol(GV), Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002048 if (ProcessingGeneric) {
Jim Grosbach13760bd2015-05-30 01:25:56 +00002049 return NVPTXGenericMCSymbolRefExpr::create(Expr, Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002050 } else {
2051 return Expr;
2052 }
2053 }
2054
2055 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
2056 if (!CE) {
2057 llvm_unreachable("Unknown constant value to lower!");
2058 }
2059
2060 switch (CE->getOpcode()) {
2061 default:
2062 // If the code isn't optimized, there may be outstanding folding
2063 // opportunities. Attempt to fold the expression using DataLayout as a
2064 // last resort before giving up.
Mehdi Aminibd7287e2015-07-16 06:11:10 +00002065 if (Constant *C = ConstantFoldConstantExpression(CE, getDataLayout()))
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002066 if (C != CE)
2067 return lowerConstantForGV(C, ProcessingGeneric);
2068
2069 // Otherwise report the problem to the user.
2070 {
2071 std::string S;
2072 raw_string_ostream OS(S);
2073 OS << "Unsupported expression in static initializer: ";
2074 CE->printAsOperand(OS, /*PrintType=*/false,
2075 !MF ? nullptr : MF->getFunction()->getParent());
2076 report_fatal_error(OS.str());
2077 }
2078
2079 case Instruction::AddrSpaceCast: {
2080 // Strip the addrspacecast and pass along the operand
2081 PointerType *DstTy = cast<PointerType>(CE->getType());
2082 if (DstTy->getAddressSpace() == 0) {
2083 return lowerConstantForGV(cast<const Constant>(CE->getOperand(0)), true);
2084 }
2085 std::string S;
2086 raw_string_ostream OS(S);
2087 OS << "Unsupported expression in static initializer: ";
2088 CE->printAsOperand(OS, /*PrintType=*/ false,
2089 !MF ? 0 : MF->getFunction()->getParent());
2090 report_fatal_error(OS.str());
2091 }
2092
2093 case Instruction::GetElementPtr: {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00002094 const DataLayout &DL = getDataLayout();
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002095
2096 // Generate a symbolic expression for the byte address
2097 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
2098 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
2099
2100 const MCExpr *Base = lowerConstantForGV(CE->getOperand(0),
2101 ProcessingGeneric);
2102 if (!OffsetAI)
2103 return Base;
2104
2105 int64_t Offset = OffsetAI.getSExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00002106 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002107 Ctx);
2108 }
2109
2110 case Instruction::Trunc:
2111 // We emit the value and depend on the assembler to truncate the generated
2112 // expression properly. This is important for differences between
2113 // blockaddress labels. Since the two labels are in the same function, it
2114 // is reasonable to treat their delta as a 32-bit value.
2115 // FALL THROUGH.
2116 case Instruction::BitCast:
2117 return lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2118
2119 case Instruction::IntToPtr: {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00002120 const DataLayout &DL = getDataLayout();
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002121
2122 // Handle casts to pointers by changing them into casts to the appropriate
2123 // integer type. This promotes constant folding and simplifies this code.
2124 Constant *Op = CE->getOperand(0);
2125 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
2126 false/*ZExt*/);
2127 return lowerConstantForGV(Op, ProcessingGeneric);
2128 }
2129
2130 case Instruction::PtrToInt: {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00002131 const DataLayout &DL = getDataLayout();
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002132
2133 // Support only foldable casts to/from pointers that can be eliminated by
2134 // changing the pointer to the appropriately sized integer type.
2135 Constant *Op = CE->getOperand(0);
2136 Type *Ty = CE->getType();
2137
2138 const MCExpr *OpExpr = lowerConstantForGV(Op, ProcessingGeneric);
2139
2140 // We can emit the pointer value into this slot if the slot is an
2141 // integer slot equal to the size of the pointer.
2142 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
2143 return OpExpr;
2144
2145 // Otherwise the pointer is smaller than the resultant integer, mask off
2146 // the high bits so we are sure to get a proper truncation if the input is
2147 // a constant expr.
2148 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
Jim Grosbach13760bd2015-05-30 01:25:56 +00002149 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
2150 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002151 }
2152
2153 // The MC library also has a right-shift operator, but it isn't consistently
2154 // signed or unsigned between different targets.
2155 case Instruction::Add: {
2156 const MCExpr *LHS = lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2157 const MCExpr *RHS = lowerConstantForGV(CE->getOperand(1), ProcessingGeneric);
2158 switch (CE->getOpcode()) {
2159 default: llvm_unreachable("Unknown binary operator constant cast expr");
Jim Grosbach13760bd2015-05-30 01:25:56 +00002160 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002161 }
2162 }
2163 }
2164}
2165
2166// Copy of MCExpr::print customized for NVPTX
2167void NVPTXAsmPrinter::printMCExpr(const MCExpr &Expr, raw_ostream &OS) {
2168 switch (Expr.getKind()) {
2169 case MCExpr::Target:
Matt Arsenault8b643552015-06-09 00:31:39 +00002170 return cast<MCTargetExpr>(&Expr)->printImpl(OS, MAI);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002171 case MCExpr::Constant:
2172 OS << cast<MCConstantExpr>(Expr).getValue();
2173 return;
2174
2175 case MCExpr::SymbolRef: {
2176 const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(Expr);
2177 const MCSymbol &Sym = SRE.getSymbol();
Matt Arsenault8b643552015-06-09 00:31:39 +00002178 Sym.print(OS, MAI);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002179 return;
2180 }
2181
2182 case MCExpr::Unary: {
2183 const MCUnaryExpr &UE = cast<MCUnaryExpr>(Expr);
2184 switch (UE.getOpcode()) {
2185 case MCUnaryExpr::LNot: OS << '!'; break;
2186 case MCUnaryExpr::Minus: OS << '-'; break;
2187 case MCUnaryExpr::Not: OS << '~'; break;
2188 case MCUnaryExpr::Plus: OS << '+'; break;
2189 }
2190 printMCExpr(*UE.getSubExpr(), OS);
2191 return;
2192 }
2193
2194 case MCExpr::Binary: {
2195 const MCBinaryExpr &BE = cast<MCBinaryExpr>(Expr);
2196
2197 // Only print parens around the LHS if it is non-trivial.
2198 if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS()) ||
2199 isa<NVPTXGenericMCSymbolRefExpr>(BE.getLHS())) {
2200 printMCExpr(*BE.getLHS(), OS);
2201 } else {
2202 OS << '(';
2203 printMCExpr(*BE.getLHS(), OS);
2204 OS<< ')';
2205 }
2206
2207 switch (BE.getOpcode()) {
2208 case MCBinaryExpr::Add:
2209 // Print "X-42" instead of "X+-42".
2210 if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
2211 if (RHSC->getValue() < 0) {
2212 OS << RHSC->getValue();
2213 return;
2214 }
2215 }
2216
2217 OS << '+';
2218 break;
2219 default: llvm_unreachable("Unhandled binary operator");
2220 }
2221
2222 // Only print parens around the LHS if it is non-trivial.
2223 if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
2224 printMCExpr(*BE.getRHS(), OS);
2225 } else {
2226 OS << '(';
2227 printMCExpr(*BE.getRHS(), OS);
2228 OS << ')';
2229 }
2230 return;
2231 }
2232 }
2233
2234 llvm_unreachable("Invalid expression kind!");
2235}
2236
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002237/// PrintAsmOperand - Print out an operand for an inline asm expression.
2238///
2239bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2240 unsigned AsmVariant,
2241 const char *ExtraCode, raw_ostream &O) {
2242 if (ExtraCode && ExtraCode[0]) {
2243 if (ExtraCode[1] != 0)
2244 return true; // Unknown modifier.
2245
2246 switch (ExtraCode[0]) {
2247 default:
2248 // See if this is a generic print operand
2249 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2250 case 'r':
2251 break;
2252 }
2253 }
2254
2255 printOperand(MI, OpNo, O);
2256
2257 return false;
2258}
2259
2260bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2261 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2262 const char *ExtraCode, raw_ostream &O) {
2263 if (ExtraCode && ExtraCode[0])
2264 return true; // Unknown modifier
2265
2266 O << '[';
2267 printMemOperand(MI, OpNo, O);
2268 O << ']';
2269
2270 return false;
2271}
2272
2273void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2274 raw_ostream &O, const char *Modifier) {
2275 const MachineOperand &MO = MI->getOperand(opNum);
2276 switch (MO.getType()) {
2277 case MachineOperand::MO_Register:
2278 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2279 if (MO.getReg() == NVPTX::VRDepot)
2280 O << DEPOTNAME << getFunctionNumber();
2281 else
2282 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2283 } else {
Justin Holewinski660597d2013-10-11 12:39:36 +00002284 emitVirtualRegister(MO.getReg(), O);
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002285 }
2286 return;
2287
2288 case MachineOperand::MO_Immediate:
2289 if (!Modifier)
2290 O << MO.getImm();
2291 else if (strstr(Modifier, "vec") == Modifier)
2292 printVecModifiedImmediate(MO, Modifier, O);
2293 else
2294 llvm_unreachable(
2295 "Don't know how to handle modifier on immediate operand");
2296 return;
2297
2298 case MachineOperand::MO_FPImmediate:
2299 printFPConstant(MO.getFPImm(), O);
2300 break;
2301
2302 case MachineOperand::MO_GlobalAddress:
Matt Arsenault8b643552015-06-09 00:31:39 +00002303 getSymbol(MO.getGlobal())->print(O, MAI);
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002304 break;
2305
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002306 case MachineOperand::MO_MachineBasicBlock:
Matt Arsenault8b643552015-06-09 00:31:39 +00002307 MO.getMBB()->getSymbol()->print(O, MAI);
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002308 return;
2309
2310 default:
2311 llvm_unreachable("Operand type not supported.");
2312 }
2313}
2314
2315void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2316 raw_ostream &O, const char *Modifier) {
2317 printOperand(MI, opNum, O);
2318
2319 if (Modifier && !strcmp(Modifier, "add")) {
2320 O << ", ";
2321 printOperand(MI, opNum + 1, O);
2322 } else {
2323 if (MI->getOperand(opNum + 1).isImm() &&
2324 MI->getOperand(opNum + 1).getImm() == 0)
2325 return; // don't print ',0' or '+0'
2326 O << "+";
2327 printOperand(MI, opNum + 1, O);
2328 }
2329}
2330
Justin Holewinskiae556d32012-05-04 20:18:50 +00002331void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2332 std::stringstream temp;
Yaron Keren075759a2015-03-30 15:42:36 +00002333 LineReader *reader = this->getReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002334 temp << "\n//";
2335 temp << filename.str();
2336 temp << ":";
2337 temp << line;
2338 temp << " ";
2339 temp << reader->readLine(line);
2340 temp << "\n";
Lang Hames9ff69c82015-04-24 19:11:51 +00002341 this->OutStreamer->EmitRawText(temp.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +00002342}
2343
Justin Holewinskiae556d32012-05-04 20:18:50 +00002344LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
Craig Topper062a2ba2014-04-25 05:30:21 +00002345 if (!reader) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002346 reader = new LineReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002347 }
2348
2349 if (reader->fileName() != filename) {
2350 delete reader;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002351 reader = new LineReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002352 }
2353
2354 return reader;
2355}
2356
Justin Holewinski0497ab12013-03-30 14:29:21 +00002357std::string LineReader::readLine(unsigned lineNum) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00002358 if (lineNum < theCurLine) {
2359 theCurLine = 0;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002360 fstr.seekg(0, std::ios::beg);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002361 }
2362 while (theCurLine < lineNum) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002363 fstr.getline(buff, 500);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002364 theCurLine++;
2365 }
2366 return buff;
2367}
2368
2369// Force static initialization.
2370extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2371 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2372 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2373}