blob: 3c2594c77f451345b997a034cca73bf6a2557f0c [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
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000015#include "InstPrinter/NVPTXInstPrinter.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000016#include "MCTargetDesc/NVPTXBaseInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "MCTargetDesc/NVPTXMCAsmInfo.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000018#include "NVPTX.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000019#include "NVPTXAsmPrinter.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"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000023#include "NVPTXSubtarget.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "NVPTXTargetMachine.h"
25#include "NVPTXUtilities.h"
26#include "cl_common_defines.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000027#include "llvm/ADT/APFloat.h"
28#include "llvm/ADT/APInt.h"
29#include "llvm/ADT/DenseMap.h"
30#include "llvm/ADT/DenseSet.h"
31#include "llvm/ADT/SmallString.h"
32#include "llvm/ADT/SmallVector.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000033#include "llvm/ADT/StringExtras.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000034#include "llvm/ADT/StringRef.h"
35#include "llvm/ADT/Triple.h"
36#include "llvm/ADT/Twine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#include "llvm/Analysis/ConstantFolding.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000038#include "llvm/CodeGen/Analysis.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000039#include "llvm/CodeGen/MachineBasicBlock.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000040#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000041#include "llvm/CodeGen/MachineFunction.h"
42#include "llvm/CodeGen/MachineInstr.h"
Jingyue Wu0220df02015-02-01 02:27:45 +000043#include "llvm/CodeGen/MachineLoopInfo.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000044#include "llvm/CodeGen/MachineModuleInfo.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000045#include "llvm/CodeGen/MachineOperand.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000046#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000047#include "llvm/CodeGen/MachineValueType.h"
48#include "llvm/CodeGen/ValueTypes.h"
49#include "llvm/IR/Attributes.h"
50#include "llvm/IR/BasicBlock.h"
51#include "llvm/IR/Constant.h"
52#include "llvm/IR/Constants.h"
53#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000054#include "llvm/IR/DebugInfo.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000055#include "llvm/IR/DebugInfoMetadata.h"
56#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000057#include "llvm/IR/DerivedTypes.h"
58#include "llvm/IR/Function.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000059#include "llvm/IR/GlobalValue.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000060#include "llvm/IR/GlobalVariable.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000061#include "llvm/IR/Instruction.h"
62#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000063#include "llvm/IR/Module.h"
64#include "llvm/IR/Operator.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000065#include "llvm/IR/Type.h"
66#include "llvm/IR/User.h"
67#include "llvm/MC/MCExpr.h"
Pete Cooper81902a32015-05-15 22:19:42 +000068#include "llvm/MC/MCInst.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000069#include "llvm/MC/MCInstrDesc.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000070#include "llvm/MC/MCStreamer.h"
71#include "llvm/MC/MCSymbol.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000072#include "llvm/Support/Casting.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000073#include "llvm/Support/CommandLine.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000074#include "llvm/Support/ErrorHandling.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000075#include "llvm/Support/Path.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000076#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000077#include "llvm/Support/TargetRegistry.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000078#include "llvm/Target/TargetLowering.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000079#include "llvm/Target/TargetLoweringObjectFile.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000080#include "llvm/Target/TargetMachine.h"
81#include "llvm/Target/TargetRegisterInfo.h"
Jingyue Wu0220df02015-02-01 02:27:45 +000082#include "llvm/Transforms/Utils/UnrollLoop.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000083#include <cassert>
84#include <cstdint>
85#include <cstring>
86#include <new>
Bill Wendlinge38859d2012-06-28 00:05:13 +000087#include <sstream>
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000088#include <string>
89#include <utility>
90#include <vector>
91
Justin Holewinskiae556d32012-05-04 20:18:50 +000092using namespace llvm;
93
Justin Holewinskiae556d32012-05-04 20:18:50 +000094#define DEPOTNAME "__local_depot"
95
96static cl::opt<bool>
Nadav Rotem7f27e0b2013-10-18 23:38:13 +000097EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
Justin Holewinskiae556d32012-05-04 20:18:50 +000098 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
99 cl::init(true));
100
Benjamin Kramer7ad41002013-10-27 11:31:46 +0000101static cl::opt<bool>
Nadav Rotem7f27e0b2013-10-18 23:38:13 +0000102InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
Justin Holewinski0497ab12013-03-30 14:29:21 +0000103 cl::desc("NVPTX Specific: Emit source line in ptx file"),
Benjamin Kramer7ad41002013-10-27 11:31:46 +0000104 cl::init(false));
Justin Holewinskiae556d32012-05-04 20:18:50 +0000105
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000106/// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
107/// depends.
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000108static void
109DiscoverDependentGlobals(const Value *V,
110 DenseSet<const GlobalVariable *> &Globals) {
Justin Holewinski01f89f02013-05-20 12:13:32 +0000111 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000112 Globals.insert(GV);
113 else {
Justin Holewinski01f89f02013-05-20 12:13:32 +0000114 if (const User *U = dyn_cast<User>(V)) {
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000115 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
116 DiscoverDependentGlobals(U->getOperand(i), Globals);
117 }
118 }
119 }
120}
Justin Holewinskiae556d32012-05-04 20:18:50 +0000121
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000122/// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
123/// instances to be emitted, but only after any dependents have been added
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000124/// first.s
125static void
126VisitGlobalVariableForEmission(const GlobalVariable *GV,
127 SmallVectorImpl<const GlobalVariable *> &Order,
128 DenseSet<const GlobalVariable *> &Visited,
129 DenseSet<const GlobalVariable *> &Visiting) {
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000130 // Have we already visited this one?
Justin Holewinski0497ab12013-03-30 14:29:21 +0000131 if (Visited.count(GV))
132 return;
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000133
134 // Do we have a circular dependency?
Benjamin Kramer2c99e412014-10-10 15:32:50 +0000135 if (!Visiting.insert(GV).second)
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000136 report_fatal_error("Circular dependency found in global variable set");
137
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000138 // Make sure we visit all dependents first
Justin Holewinski01f89f02013-05-20 12:13:32 +0000139 DenseSet<const GlobalVariable *> Others;
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000140 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
141 DiscoverDependentGlobals(GV->getOperand(i), Others);
Justin Holewinski0497ab12013-03-30 14:29:21 +0000142
Justin Holewinski01f89f02013-05-20 12:13:32 +0000143 for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
144 E = Others.end();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000145 I != E; ++I)
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000146 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
147
148 // Now we can visit ourself
149 Order.push_back(GV);
150 Visited.insert(GV);
151 Visiting.erase(GV);
152}
Justin Holewinskiae556d32012-05-04 20:18:50 +0000153
Justin Holewinski0497ab12013-03-30 14:29:21 +0000154void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000155 if (!EmitLineNumbers)
156 return;
157 if (ignoreLoc(MI))
158 return;
159
Benjamin Kramer4fed9282016-05-27 12:30:51 +0000160 const DebugLoc &curLoc = MI.getDebugLoc();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000161
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000162 if (!prevDebugLoc && !curLoc)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000163 return;
164
165 if (prevDebugLoc == curLoc)
166 return;
167
168 prevDebugLoc = curLoc;
169
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000170 if (!curLoc)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000171 return;
172
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000173 auto *Scope = cast_or_null<DIScope>(curLoc.getScope());
Manman Ren983a16c2013-06-28 05:43:10 +0000174 if (!Scope)
175 return;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000176
Duncan P. N. Exon Smithb273d062015-04-16 01:37:00 +0000177 StringRef fileName(Scope->getFilename());
178 StringRef dirName(Scope->getDirectory());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000179 SmallString<128> FullPathName = dirName;
180 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
181 sys::path::append(FullPathName, fileName);
Yaron Keren075759a2015-03-30 15:42:36 +0000182 fileName = FullPathName;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000183 }
184
Yaron Keren075759a2015-03-30 15:42:36 +0000185 if (filenameMap.find(fileName) == filenameMap.end())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000186 return;
187
Justin Holewinskiae556d32012-05-04 20:18:50 +0000188 // Emit the line from the source file.
Benjamin Kramer7ad41002013-10-27 11:31:46 +0000189 if (InterleaveSrc)
Yaron Keren075759a2015-03-30 15:42:36 +0000190 this->emitSrcInText(fileName, curLoc.getLine());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000191
192 std::stringstream temp;
Yaron Keren075759a2015-03-30 15:42:36 +0000193 temp << "\t.loc " << filenameMap[fileName] << " " << curLoc.getLine()
Justin Holewinski0497ab12013-03-30 14:29:21 +0000194 << " " << curLoc.getCol();
Lang Hames9ff69c82015-04-24 19:11:51 +0000195 OutStreamer->EmitRawText(temp.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000196}
197
198void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
199 SmallString<128> Str;
200 raw_svector_ostream OS(Str);
Eric Christopherbeffc4e2015-02-19 00:08:23 +0000201 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000202 emitLineNumberAsDotLoc(*MI);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000203
204 MCInst Inst;
205 lowerToMCInst(MI, Inst);
Lang Hames9ff69c82015-04-24 19:11:51 +0000206 EmitToStreamer(*OutStreamer, Inst);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000207}
208
Justin Holewinski30d56a72014-04-09 15:39:15 +0000209// Handle symbol backtracking for targets that do not support image handles
210bool NVPTXAsmPrinter::lowerImageHandleOperand(const MachineInstr *MI,
211 unsigned OpNo, MCOperand &MCOp) {
212 const MachineOperand &MO = MI->getOperand(OpNo);
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000213 const MCInstrDesc &MCID = MI->getDesc();
Justin Holewinski30d56a72014-04-09 15:39:15 +0000214
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000215 if (MCID.TSFlags & NVPTXII::IsTexFlag) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000216 // This is a texture fetch, so operand 4 is a texref and operand 5 is
217 // a samplerref
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000218 if (OpNo == 4 && MO.isImm()) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000219 lowerImageHandleSymbol(MO.getImm(), MCOp);
220 return true;
221 }
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000222 if (OpNo == 5 && MO.isImm() && !(MCID.TSFlags & NVPTXII::IsTexModeUnifiedFlag)) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000223 lowerImageHandleSymbol(MO.getImm(), MCOp);
224 return true;
225 }
226
227 return false;
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000228 } else if (MCID.TSFlags & NVPTXII::IsSuldMask) {
229 unsigned VecSize =
230 1 << (((MCID.TSFlags & NVPTXII::IsSuldMask) >> NVPTXII::IsSuldShift) - 1);
231
232 // For a surface load of vector size N, the Nth operand will be the surfref
233 if (OpNo == VecSize && MO.isImm()) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000234 lowerImageHandleSymbol(MO.getImm(), MCOp);
235 return true;
236 }
237
238 return false;
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000239 } else if (MCID.TSFlags & NVPTXII::IsSustFlag) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000240 // This is a surface store, so operand 0 is a surfref
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000241 if (OpNo == 0 && MO.isImm()) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000242 lowerImageHandleSymbol(MO.getImm(), MCOp);
243 return true;
244 }
245
246 return false;
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000247 } else if (MCID.TSFlags & NVPTXII::IsSurfTexQueryFlag) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000248 // This is a query, so operand 1 is a surfref/texref
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000249 if (OpNo == 1 && MO.isImm()) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000250 lowerImageHandleSymbol(MO.getImm(), MCOp);
251 return true;
252 }
253
254 return false;
255 }
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000256
257 return false;
Justin Holewinski30d56a72014-04-09 15:39:15 +0000258}
259
260void NVPTXAsmPrinter::lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp) {
261 // Ewwww
262 TargetMachine &TM = const_cast<TargetMachine&>(MF->getTarget());
263 NVPTXTargetMachine &nvTM = static_cast<NVPTXTargetMachine&>(TM);
264 const NVPTXMachineFunctionInfo *MFI = MF->getInfo<NVPTXMachineFunctionInfo>();
265 const char *Sym = MFI->getImageHandleSymbol(Index);
266 std::string *SymNamePtr =
267 nvTM.getManagedStrPool()->getManagedString(Sym);
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000268 MCOp = GetSymbolRef(OutContext.getOrCreateSymbol(StringRef(*SymNamePtr)));
Justin Holewinski30d56a72014-04-09 15:39:15 +0000269}
270
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000271void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
272 OutMI.setOpcode(MI->getOpcode());
Justin Holewinski3d49e5c2013-11-15 12:30:04 +0000273 // Special: Do not mangle symbol operand of CALL_PROTOTYPE
274 if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
275 const MachineOperand &MO = MI->getOperand(0);
Justin Holewinski30d56a72014-04-09 15:39:15 +0000276 OutMI.addOperand(GetSymbolRef(
Jim Grosbach6f482002015-05-18 18:43:14 +0000277 OutContext.getOrCreateSymbol(Twine(MO.getSymbolName()))));
Justin Holewinski3d49e5c2013-11-15 12:30:04 +0000278 return;
279 }
280
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000281 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
282 const MachineOperand &MO = MI->getOperand(i);
283
284 MCOperand MCOp;
Eric Christopher6aad8b12015-02-19 00:08:14 +0000285 if (!nvptxSubtarget->hasImageHandles()) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000286 if (lowerImageHandleOperand(MI, i, MCOp)) {
287 OutMI.addOperand(MCOp);
288 continue;
289 }
290 }
291
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000292 if (lowerOperand(MO, MCOp))
293 OutMI.addOperand(MCOp);
294 }
295}
296
297bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
298 MCOperand &MCOp) {
299 switch (MO.getType()) {
300 default: llvm_unreachable("unknown operand type");
301 case MachineOperand::MO_Register:
Jim Grosbache9119e42015-05-13 18:37:00 +0000302 MCOp = MCOperand::createReg(encodeVirtualRegister(MO.getReg()));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000303 break;
304 case MachineOperand::MO_Immediate:
Jim Grosbache9119e42015-05-13 18:37:00 +0000305 MCOp = MCOperand::createImm(MO.getImm());
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000306 break;
307 case MachineOperand::MO_MachineBasicBlock:
Jim Grosbach13760bd2015-05-30 01:25:56 +0000308 MCOp = MCOperand::createExpr(MCSymbolRefExpr::create(
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000309 MO.getMBB()->getSymbol(), OutContext));
310 break;
311 case MachineOperand::MO_ExternalSymbol:
Justin Holewinski30d56a72014-04-09 15:39:15 +0000312 MCOp = GetSymbolRef(GetExternalSymbolSymbol(MO.getSymbolName()));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000313 break;
314 case MachineOperand::MO_GlobalAddress:
Justin Holewinski30d56a72014-04-09 15:39:15 +0000315 MCOp = GetSymbolRef(getSymbol(MO.getGlobal()));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000316 break;
317 case MachineOperand::MO_FPImmediate: {
318 const ConstantFP *Cnt = MO.getFPImm();
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000319 const APFloat &Val = Cnt->getValueAPF();
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000320
321 switch (Cnt->getType()->getTypeID()) {
322 default: report_fatal_error("Unsupported FP type"); break;
323 case Type::FloatTyID:
Jim Grosbache9119e42015-05-13 18:37:00 +0000324 MCOp = MCOperand::createExpr(
Jim Grosbach13760bd2015-05-30 01:25:56 +0000325 NVPTXFloatMCExpr::createConstantFPSingle(Val, OutContext));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000326 break;
327 case Type::DoubleTyID:
Jim Grosbache9119e42015-05-13 18:37:00 +0000328 MCOp = MCOperand::createExpr(
Jim Grosbach13760bd2015-05-30 01:25:56 +0000329 NVPTXFloatMCExpr::createConstantFPDouble(Val, OutContext));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000330 break;
331 }
332 break;
333 }
334 }
335 return true;
336}
337
338unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
Justin Holewinski871ec932013-08-06 14:13:31 +0000339 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
340 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000341
Justin Holewinski871ec932013-08-06 14:13:31 +0000342 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
343 unsigned RegNum = RegMap[Reg];
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000344
Justin Holewinski871ec932013-08-06 14:13:31 +0000345 // Encode the register class in the upper 4 bits
346 // Must be kept in sync with NVPTXInstPrinter::printRegName
347 unsigned Ret = 0;
348 if (RC == &NVPTX::Int1RegsRegClass) {
349 Ret = (1 << 28);
350 } else if (RC == &NVPTX::Int16RegsRegClass) {
351 Ret = (2 << 28);
352 } else if (RC == &NVPTX::Int32RegsRegClass) {
353 Ret = (3 << 28);
354 } else if (RC == &NVPTX::Int64RegsRegClass) {
355 Ret = (4 << 28);
356 } else if (RC == &NVPTX::Float32RegsRegClass) {
357 Ret = (5 << 28);
358 } else if (RC == &NVPTX::Float64RegsRegClass) {
359 Ret = (6 << 28);
360 } else {
361 report_fatal_error("Bad register class");
362 }
363
364 // Insert the vreg number
365 Ret |= (RegNum & 0x0FFFFFFF);
366 return Ret;
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000367 } else {
Justin Holewinski871ec932013-08-06 14:13:31 +0000368 // Some special-use registers are actually physical registers.
369 // Encode this as the register class ID of 0 and the real register ID.
370 return Reg & 0x0FFFFFFF;
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000371 }
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000372}
373
Justin Holewinski30d56a72014-04-09 15:39:15 +0000374MCOperand NVPTXAsmPrinter::GetSymbolRef(const MCSymbol *Symbol) {
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000375 const MCExpr *Expr;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000376 Expr = MCSymbolRefExpr::create(Symbol, MCSymbolRefExpr::VK_None,
Justin Holewinski8b24e1e2013-08-06 23:06:42 +0000377 OutContext);
Jim Grosbache9119e42015-05-13 18:37:00 +0000378 return MCOperand::createExpr(Expr);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000379}
380
Justin Holewinski0497ab12013-03-30 14:29:21 +0000381void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
Mehdi Amini56228da2015-07-09 01:57:34 +0000382 const DataLayout &DL = getDataLayout();
Eric Christopher6aad8b12015-02-19 00:08:14 +0000383 const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000384
385 Type *Ty = F->getReturnType();
386
Eric Christopher6aad8b12015-02-19 00:08:14 +0000387 bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000388
389 if (Ty->getTypeID() == Type::VoidTyID)
390 return;
391
392 O << " (";
393
394 if (isABI) {
Rafael Espindola08013342013-12-07 19:34:20 +0000395 if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000396 unsigned size = 0;
Craig Toppere3dcce92015-08-01 22:20:21 +0000397 if (auto *ITy = dyn_cast<IntegerType>(Ty)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000398 size = ITy->getBitWidth();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000399 if (size < 32)
400 size = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000401 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +0000402 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000403 size = Ty->getPrimitiveSizeInBits();
404 }
405
406 O << ".param .b" << size << " func_retval0";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000407 } else if (isa<PointerType>(Ty)) {
Mehdi Amini44ede332015-07-09 02:09:04 +0000408 O << ".param .b" << TLI->getPointerTy(DL).getSizeInBits()
Justin Holewinski0497ab12013-03-30 14:29:21 +0000409 << " func_retval0";
Artem Belevich74158b52016-07-20 18:39:52 +0000410 } else if (Ty->isAggregateType() || Ty->isVectorTy()) {
Mehdi Amini56228da2015-07-09 01:57:34 +0000411 unsigned totalsz = DL.getTypeAllocSize(Ty);
Artem Belevich74158b52016-07-20 18:39:52 +0000412 unsigned retAlignment = 0;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000413 if (!getAlign(*F, 0, retAlignment))
Artem Belevich74158b52016-07-20 18:39:52 +0000414 retAlignment = DL.getABITypeAlignment(Ty);
415 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
416 << "]";
Craig Topperd3c02f12015-01-05 10:15:49 +0000417 } else
418 llvm_unreachable("Unknown return type");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000419 } else {
420 SmallVector<EVT, 16> vtparts;
Mehdi Amini56228da2015-07-09 01:57:34 +0000421 ComputeValueVTs(*TLI, DL, Ty, vtparts);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000422 unsigned idx = 0;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000423 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000424 unsigned elems = 1;
425 EVT elemtype = vtparts[i];
426 if (vtparts[i].isVector()) {
427 elems = vtparts[i].getVectorNumElements();
428 elemtype = vtparts[i].getVectorElementType();
429 }
430
Justin Holewinski0497ab12013-03-30 14:29:21 +0000431 for (unsigned j = 0, je = elems; j != je; ++j) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000432 unsigned sz = elemtype.getSizeInBits();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000433 if (elemtype.isInteger() && (sz < 32))
434 sz = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000435 O << ".reg .b" << sz << " func_retval" << idx;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000436 if (j < je - 1)
437 O << ", ";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000438 ++idx;
439 }
Justin Holewinski0497ab12013-03-30 14:29:21 +0000440 if (i < e - 1)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000441 O << ", ";
442 }
443 }
444 O << ") ";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000445}
446
447void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
448 raw_ostream &O) {
449 const Function *F = MF.getFunction();
450 printReturnValStr(F, O);
451}
452
Jingyue Wu0220df02015-02-01 02:27:45 +0000453// Return true if MBB is the header of a loop marked with
454// llvm.loop.unroll.disable.
Jingyue Wu5bbcdaa2015-02-03 17:57:38 +0000455// TODO: consider "#pragma unroll 1" which is equivalent to "#pragma nounroll".
Jingyue Wu0220df02015-02-01 02:27:45 +0000456bool NVPTXAsmPrinter::isLoopHeaderOfNoUnroll(
457 const MachineBasicBlock &MBB) const {
458 MachineLoopInfo &LI = getAnalysis<MachineLoopInfo>();
Jingyue Wu0220df02015-02-01 02:27:45 +0000459 // We insert .pragma "nounroll" only to the loop header.
Benjamin Kramerdb220db2015-06-02 15:28:27 +0000460 if (!LI.isLoopHeader(&MBB))
Jingyue Wu0220df02015-02-01 02:27:45 +0000461 return false;
462
463 // llvm.loop.unroll.disable is marked on the back edges of a loop. Therefore,
464 // we iterate through each back edge of the loop with header MBB, and check
465 // whether its metadata contains llvm.loop.unroll.disable.
466 for (auto I = MBB.pred_begin(); I != MBB.pred_end(); ++I) {
467 const MachineBasicBlock *PMBB = *I;
468 if (LI.getLoopFor(PMBB) != LI.getLoopFor(&MBB)) {
469 // Edges from other loops to MBB are not back edges.
470 continue;
471 }
472 if (const BasicBlock *PBB = PMBB->getBasicBlock()) {
Duncan P. N. Exon Smith1d15a9f2016-03-25 00:35:38 +0000473 if (MDNode *LoopID =
474 PBB->getTerminator()->getMetadata(LLVMContext::MD_loop)) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000475 if (GetUnrollMetadata(LoopID, "llvm.loop.unroll.disable"))
476 return true;
477 }
478 }
479 }
480 return false;
481}
482
483void NVPTXAsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
484 AsmPrinter::EmitBasicBlockStart(MBB);
485 if (isLoopHeaderOfNoUnroll(MBB))
Lang Hames9ff69c82015-04-24 19:11:51 +0000486 OutStreamer->EmitRawText(StringRef("\t.pragma \"nounroll\";\n"));
Jingyue Wu0220df02015-02-01 02:27:45 +0000487}
488
Justin Holewinskiae556d32012-05-04 20:18:50 +0000489void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
490 SmallString<128> Str;
491 raw_svector_ostream O(Str);
492
Justin Holewinski01f89f02013-05-20 12:13:32 +0000493 if (!GlobalsEmitted) {
494 emitGlobals(*MF->getFunction()->getParent());
495 GlobalsEmitted = true;
496 }
497
Justin Holewinskiae556d32012-05-04 20:18:50 +0000498 // Set up
499 MRI = &MF->getRegInfo();
500 F = MF->getFunction();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000501 emitLinkageDirective(F, O);
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000502 if (isKernelFunction(*F))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000503 O << ".entry ";
504 else {
505 O << ".func ";
506 printReturnValStr(*MF, O);
507 }
508
Matt Arsenault8b643552015-06-09 00:31:39 +0000509 CurrentFnSym->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000510
511 emitFunctionParamList(*MF, O);
512
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000513 if (isKernelFunction(*F))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000514 emitKernelFunctionDirectives(*F, O);
515
Lang Hames9ff69c82015-04-24 19:11:51 +0000516 OutStreamer->EmitRawText(O.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000517
518 prevDebugLoc = DebugLoc();
519}
520
521void NVPTXAsmPrinter::EmitFunctionBodyStart() {
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +0000522 VRegMapping.clear();
Lang Hames9ff69c82015-04-24 19:11:51 +0000523 OutStreamer->EmitRawText(StringRef("{\n"));
Justin Holewinskiae556d32012-05-04 20:18:50 +0000524 setAndEmitFunctionVirtualRegisters(*MF);
525
526 SmallString<128> Str;
527 raw_svector_ostream O(Str);
528 emitDemotedVars(MF->getFunction(), O);
Lang Hames9ff69c82015-04-24 19:11:51 +0000529 OutStreamer->EmitRawText(O.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000530}
531
532void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
Lang Hames9ff69c82015-04-24 19:11:51 +0000533 OutStreamer->EmitRawText(StringRef("}\n"));
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +0000534 VRegMapping.clear();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000535}
536
Justin Holewinski660597d2013-10-11 12:39:36 +0000537void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
538 unsigned RegNo = MI->getOperand(0).getReg();
Andrew Kaylor5c73e1f2015-03-24 23:37:10 +0000539 if (TargetRegisterInfo::isVirtualRegister(RegNo)) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000540 OutStreamer->AddComment(Twine("implicit-def: ") +
541 getVirtualRegisterName(RegNo));
Justin Holewinski660597d2013-10-11 12:39:36 +0000542 } else {
Lang Hames9ff69c82015-04-24 19:11:51 +0000543 OutStreamer->AddComment(Twine("implicit-def: ") +
544 nvptxSubtarget->getRegisterInfo()->getName(RegNo));
Justin Holewinski660597d2013-10-11 12:39:36 +0000545 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000546 OutStreamer->AddBlankLine();
Justin Holewinski660597d2013-10-11 12:39:36 +0000547}
548
Justin Holewinski0497ab12013-03-30 14:29:21 +0000549void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
550 raw_ostream &O) const {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000551 // If the NVVM IR has some of reqntid* specified, then output
552 // the reqntid directive, and set the unspecified ones to 1.
553 // If none of reqntid* is specified, don't output reqntid directive.
554 unsigned reqntidx, reqntidy, reqntidz;
555 bool specified = false;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000556 if (!getReqNTIDx(F, reqntidx))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000557 reqntidx = 1;
558 else
559 specified = true;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000560 if (!getReqNTIDy(F, reqntidy))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000561 reqntidy = 1;
562 else
563 specified = true;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000564 if (!getReqNTIDz(F, reqntidz))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000565 reqntidz = 1;
566 else
567 specified = true;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000568
569 if (specified)
Justin Holewinski0497ab12013-03-30 14:29:21 +0000570 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
571 << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000572
573 // If the NVVM IR has some of maxntid* specified, then output
574 // the maxntid directive, and set the unspecified ones to 1.
575 // If none of maxntid* is specified, don't output maxntid directive.
576 unsigned maxntidx, maxntidy, maxntidz;
577 specified = false;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000578 if (!getMaxNTIDx(F, maxntidx))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000579 maxntidx = 1;
580 else
581 specified = true;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000582 if (!getMaxNTIDy(F, maxntidy))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000583 maxntidy = 1;
584 else
585 specified = true;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000586 if (!getMaxNTIDz(F, maxntidz))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000587 maxntidz = 1;
588 else
589 specified = true;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000590
591 if (specified)
Justin Holewinski0497ab12013-03-30 14:29:21 +0000592 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
593 << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000594
595 unsigned mincta;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000596 if (getMinCTASm(F, mincta))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000597 O << ".minnctapersm " << mincta << "\n";
Justin Lebar19bf9d22016-12-14 22:32:50 +0000598
599 unsigned maxnreg;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000600 if (getMaxNReg(F, maxnreg))
Justin Lebar19bf9d22016-12-14 22:32:50 +0000601 O << ".maxnreg " << maxnreg << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000602}
603
Justin Holewinski660597d2013-10-11 12:39:36 +0000604std::string
605NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
606 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000607
Justin Holewinski660597d2013-10-11 12:39:36 +0000608 std::string Name;
609 raw_string_ostream NameStr(Name);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000610
Justin Holewinski660597d2013-10-11 12:39:36 +0000611 VRegRCMap::const_iterator I = VRegMapping.find(RC);
612 assert(I != VRegMapping.end() && "Bad register class");
613 const DenseMap<unsigned, unsigned> &RegMap = I->second;
614
615 VRegMap::const_iterator VI = RegMap.find(Reg);
616 assert(VI != RegMap.end() && "Bad virtual register");
617 unsigned MappedVR = VI->second;
618
619 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
620
621 NameStr.flush();
622 return Name;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000623}
624
Justin Holewinski660597d2013-10-11 12:39:36 +0000625void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
Justin Holewinski0497ab12013-03-30 14:29:21 +0000626 raw_ostream &O) {
Justin Holewinski660597d2013-10-11 12:39:36 +0000627 O << getVirtualRegisterName(vr);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000628}
629
Justin Holewinski0497ab12013-03-30 14:29:21 +0000630void NVPTXAsmPrinter::printVecModifiedImmediate(
631 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
632 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
633 int Imm = (int) MO.getImm();
634 if (0 == strcmp(Modifier, "vecelem"))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000635 O << "_" << vecelem[Imm];
Justin Holewinski0497ab12013-03-30 14:29:21 +0000636 else if (0 == strcmp(Modifier, "vecv4comm1")) {
637 if ((Imm < 0) || (Imm > 3))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000638 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000639 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
640 if ((Imm < 4) || (Imm > 7))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000641 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000642 } else if (0 == strcmp(Modifier, "vecv4pos")) {
643 if (Imm < 0)
644 Imm = 0;
645 O << "_" << vecelem[Imm % 4];
646 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
647 if ((Imm < 0) || (Imm > 1))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000648 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000649 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
650 if ((Imm < 2) || (Imm > 3))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000651 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000652 } else if (0 == strcmp(Modifier, "vecv2pos")) {
653 if (Imm < 0)
654 Imm = 0;
655 O << "_" << vecelem[Imm % 2];
656 } else
Craig Topperbdf39a42012-05-24 07:02:50 +0000657 llvm_unreachable("Unknown Modifier on immediate operand");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000658}
659
Justin Holewinski0497ab12013-03-30 14:29:21 +0000660void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
Justin Holewinski0497ab12013-03-30 14:29:21 +0000661 emitLinkageDirective(F, O);
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000662 if (isKernelFunction(*F))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000663 O << ".entry ";
664 else
665 O << ".func ";
666 printReturnValStr(F, O);
Matt Arsenault8b643552015-06-09 00:31:39 +0000667 getSymbol(F)->print(O, MAI);
668 O << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000669 emitFunctionParamList(F, O);
670 O << ";\n";
671}
672
Justin Holewinski0497ab12013-03-30 14:29:21 +0000673static bool usedInGlobalVarDef(const Constant *C) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000674 if (!C)
675 return false;
676
677 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
Jingyue Wu4be014a2015-07-31 05:09:47 +0000678 return GV->getName() != "llvm.used";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000679 }
680
Chandler Carruthcdf47882014-03-09 03:16:01 +0000681 for (const User *U : C->users())
682 if (const Constant *C = dyn_cast<Constant>(U))
683 if (usedInGlobalVarDef(C))
684 return true;
685
Justin Holewinskiae556d32012-05-04 20:18:50 +0000686 return false;
687}
688
Justin Holewinski0497ab12013-03-30 14:29:21 +0000689static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000690 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
Yaron Keren075759a2015-03-30 15:42:36 +0000691 if (othergv->getName() == "llvm.used")
Justin Holewinskiae556d32012-05-04 20:18:50 +0000692 return true;
693 }
694
695 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
696 if (instr->getParent() && instr->getParent()->getParent()) {
697 const Function *curFunc = instr->getParent()->getParent();
698 if (oneFunc && (curFunc != oneFunc))
699 return false;
700 oneFunc = curFunc;
701 return true;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000702 } else
Justin Holewinskiae556d32012-05-04 20:18:50 +0000703 return false;
704 }
705
Chandler Carruthcdf47882014-03-09 03:16:01 +0000706 for (const User *UU : U->users())
Eli Bendersky3e840192015-03-23 16:26:23 +0000707 if (!usedInOneFunc(UU, oneFunc))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000708 return false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000709
Justin Holewinskiae556d32012-05-04 20:18:50 +0000710 return true;
711}
712
713/* Find out if a global variable can be demoted to local scope.
714 * Currently, this is valid for CUDA shared variables, which have local
715 * scope and global lifetime. So the conditions to check are :
716 * 1. Is the global variable in shared address space?
717 * 2. Does it have internal linkage?
718 * 3. Is the global variable referenced only in one function?
719 */
720static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
Eli Bendersky3e840192015-03-23 16:26:23 +0000721 if (!gv->hasInternalLinkage())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000722 return false;
Craig Toppere3dcce92015-08-01 22:20:21 +0000723 PointerType *Pty = gv->getType();
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000724 if (Pty->getAddressSpace() != ADDRESS_SPACE_SHARED)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000725 return false;
726
Craig Topper062a2ba2014-04-25 05:30:21 +0000727 const Function *oneFunc = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000728
729 bool flag = usedInOneFunc(gv, oneFunc);
Eli Bendersky3e840192015-03-23 16:26:23 +0000730 if (!flag)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000731 return false;
732 if (!oneFunc)
733 return false;
734 f = oneFunc;
735 return true;
736}
737
738static bool useFuncSeen(const Constant *C,
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000739 DenseMap<const Function *, bool> &seenMap) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000740 for (const User *U : C->users()) {
741 if (const Constant *cu = dyn_cast<Constant>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000742 if (useFuncSeen(cu, seenMap))
743 return true;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000744 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000745 const BasicBlock *bb = I->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000746 if (!bb)
747 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000748 const Function *caller = bb->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000749 if (!caller)
750 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000751 if (seenMap.find(caller) != seenMap.end())
752 return true;
753 }
754 }
755 return false;
756}
757
Justin Holewinski01f89f02013-05-20 12:13:32 +0000758void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000759 DenseMap<const Function *, bool> seenMap;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000760 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
Duncan P. N. Exon Smith61149b82015-10-20 00:54:09 +0000761 const Function *F = &*FI;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000762
763 if (F->isDeclaration()) {
764 if (F->use_empty())
765 continue;
766 if (F->getIntrinsicID())
767 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000768 emitDeclaration(F, O);
769 continue;
770 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000771 for (const User *U : F->users()) {
772 if (const Constant *C = dyn_cast<Constant>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000773 if (usedInGlobalVarDef(C)) {
774 // The use is in the initialization of a global variable
775 // that is a function pointer, so print a declaration
776 // for the original function
Justin Holewinskiae556d32012-05-04 20:18:50 +0000777 emitDeclaration(F, O);
778 break;
779 }
780 // Emit a declaration of this function if the function that
781 // uses this constant expr has already been seen.
782 if (useFuncSeen(C, seenMap)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000783 emitDeclaration(F, O);
784 break;
785 }
786 }
787
Chandler Carruthcdf47882014-03-09 03:16:01 +0000788 if (!isa<Instruction>(U))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000789 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000790 const Instruction *instr = cast<Instruction>(U);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000791 const BasicBlock *bb = instr->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000792 if (!bb)
793 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000794 const Function *caller = bb->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000795 if (!caller)
796 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000797
798 // If a caller has already been seen, then the caller is
799 // appearing in the module before the callee. so print out
800 // a declaration for the callee.
801 if (seenMap.find(caller) != seenMap.end()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000802 emitDeclaration(F, O);
803 break;
804 }
805 }
806 seenMap[F] = true;
807 }
808}
809
810void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
811 DebugInfoFinder DbgFinder;
812 DbgFinder.processModule(M);
813
Justin Holewinski0497ab12013-03-30 14:29:21 +0000814 unsigned i = 1;
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000815 for (const DICompileUnit *DIUnit : DbgFinder.compile_units()) {
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +0000816 StringRef Filename = DIUnit->getFilename();
817 StringRef Dirname = DIUnit->getDirectory();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000818 SmallString<128> FullPathName = Dirname;
819 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
820 sys::path::append(FullPathName, Filename);
Yaron Keren075759a2015-03-30 15:42:36 +0000821 Filename = FullPathName;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000822 }
Yaron Keren075759a2015-03-30 15:42:36 +0000823 if (filenameMap.find(Filename) != filenameMap.end())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000824 continue;
Yaron Keren075759a2015-03-30 15:42:36 +0000825 filenameMap[Filename] = i;
Lang Hames9ff69c82015-04-24 19:11:51 +0000826 OutStreamer->EmitDwarfFileDirective(i, "", Filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000827 ++i;
828 }
829
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000830 for (DISubprogram *SP : DbgFinder.subprograms()) {
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000831 StringRef Filename = SP->getFilename();
832 StringRef Dirname = SP->getDirectory();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000833 SmallString<128> FullPathName = Dirname;
834 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
835 sys::path::append(FullPathName, Filename);
Yaron Keren075759a2015-03-30 15:42:36 +0000836 Filename = FullPathName;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000837 }
Yaron Keren075759a2015-03-30 15:42:36 +0000838 if (filenameMap.find(Filename) != filenameMap.end())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000839 continue;
Yaron Keren075759a2015-03-30 15:42:36 +0000840 filenameMap[Filename] = i;
Artem Belevicha8455f22016-02-11 18:21:47 +0000841 OutStreamer->EmitDwarfFileDirective(i, "", Filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000842 ++i;
843 }
844}
845
Justin Lebaread59f42016-01-30 01:07:38 +0000846static bool isEmptyXXStructor(GlobalVariable *GV) {
847 if (!GV) return true;
848 const ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
849 if (!InitList) return true; // Not an array; we don't know how to parse.
850 return InitList->getNumOperands() == 0;
851}
852
Justin Holewinski0497ab12013-03-30 14:29:21 +0000853bool NVPTXAsmPrinter::doInitialization(Module &M) {
Eric Christopher6aad8b12015-02-19 00:08:14 +0000854 // Construct a default subtarget off of the TargetMachine defaults. The
855 // rest of NVPTX isn't friendly to change subtargets per function and
856 // so the default TargetMachine will have all of the options.
Daniel Sandersc81f4502015-06-16 15:44:21 +0000857 const Triple &TT = TM.getTargetTriple();
Eric Christopher6aad8b12015-02-19 00:08:14 +0000858 StringRef CPU = TM.getTargetCPU();
859 StringRef FS = TM.getTargetFeatureString();
860 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
Eric Christopher02389e32015-02-19 00:08:27 +0000861 const NVPTXSubtarget STI(TT, CPU, FS, NTM);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000862
Justin Lebar3a5f5792016-01-23 21:12:20 +0000863 if (M.alias_size()) {
864 report_fatal_error("Module has aliases, which NVPTX does not support.");
865 return true; // error
866 }
Justin Lebaread59f42016-01-30 01:07:38 +0000867 if (!isEmptyXXStructor(M.getNamedGlobal("llvm.global_ctors"))) {
868 report_fatal_error(
869 "Module has a nontrivial global ctor, which NVPTX does not support.");
870 return true; // error
871 }
872 if (!isEmptyXXStructor(M.getNamedGlobal("llvm.global_dtors"))) {
873 report_fatal_error(
874 "Module has a nontrivial global dtor, which NVPTX does not support.");
875 return true; // error
876 }
Justin Lebar3a5f5792016-01-23 21:12:20 +0000877
Justin Holewinskiae556d32012-05-04 20:18:50 +0000878 SmallString<128> Str1;
879 raw_svector_ostream OS1(Str1);
880
881 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000882
883 // We need to call the parent's one explicitly.
884 //bool Result = AsmPrinter::doInitialization(M);
885
Eric Christopherb4b75a52016-09-29 02:03:47 +0000886 // Initialize TargetLoweringObjectFile since we didn't do in
887 // AsmPrinter::doInitialization either right above or where it's commented out
888 // below.
Justin Holewinski0497ab12013-03-30 14:29:21 +0000889 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
890 .Initialize(OutContext, TM);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000891
Justin Holewinskiae556d32012-05-04 20:18:50 +0000892 // Emit header before any dwarf directives are emitted below.
Eric Christopher6aad8b12015-02-19 00:08:14 +0000893 emitHeader(M, OS1, STI);
Lang Hames9ff69c82015-04-24 19:11:51 +0000894 OutStreamer->EmitRawText(OS1.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000895
Justin Holewinskiae556d32012-05-04 20:18:50 +0000896 // Already commented out
897 //bool Result = AsmPrinter::doInitialization(M);
898
Justin Holewinskid2bbdf02013-07-01 13:00:14 +0000899 // Emit module-level inline asm if it exists.
900 if (!M.getModuleInlineAsm().empty()) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000901 OutStreamer->AddComment("Start of file scope inline assembly");
902 OutStreamer->AddBlankLine();
903 OutStreamer->EmitRawText(StringRef(M.getModuleInlineAsm()));
904 OutStreamer->AddBlankLine();
905 OutStreamer->AddComment("End of file scope inline assembly");
906 OutStreamer->AddBlankLine();
Justin Holewinskid2bbdf02013-07-01 13:00:14 +0000907 }
908
Eric Christopher6aad8b12015-02-19 00:08:14 +0000909 // If we're not NVCL we're CUDA, go ahead and emit filenames.
Daniel Sandersc81f4502015-06-16 15:44:21 +0000910 if (TM.getTargetTriple().getOS() != Triple::NVCL)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000911 recordAndEmitFilenames(M);
912
Justin Holewinski01f89f02013-05-20 12:13:32 +0000913 GlobalsEmitted = false;
914
915 return false; // success
916}
917
918void NVPTXAsmPrinter::emitGlobals(const Module &M) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000919 SmallString<128> Str2;
920 raw_svector_ostream OS2(Str2);
921
922 emitDeclarations(M, OS2);
923
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000924 // As ptxas does not support forward references of globals, we need to first
925 // sort the list of module-level globals in def-use order. We visit each
926 // global variable in order, and ensure that we emit it *after* its dependent
927 // globals. We use a little extra memory maintaining both a set and a list to
928 // have fast searches while maintaining a strict ordering.
Justin Holewinski01f89f02013-05-20 12:13:32 +0000929 SmallVector<const GlobalVariable *, 8> Globals;
930 DenseSet<const GlobalVariable *> GVVisited;
931 DenseSet<const GlobalVariable *> GVVisiting;
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000932
933 // Visit each global variable, in order
Duncan P. N. Exon Smith61149b82015-10-20 00:54:09 +0000934 for (const GlobalVariable &I : M.globals())
935 VisitGlobalVariableForEmission(&I, Globals, GVVisited, GVVisiting);
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000936
Justin Holewinski0497ab12013-03-30 14:29:21 +0000937 assert(GVVisited.size() == M.getGlobalList().size() &&
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000938 "Missed a global variable");
939 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
940
941 // Print out module-level global variables in proper order
942 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
943 printModuleLevelGV(Globals[i], OS2);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000944
945 OS2 << '\n';
946
Lang Hames9ff69c82015-04-24 19:11:51 +0000947 OutStreamer->EmitRawText(OS2.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000948}
949
Eric Christopher6aad8b12015-02-19 00:08:14 +0000950void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O,
951 const NVPTXSubtarget &STI) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000952 O << "//\n";
953 O << "// Generated by LLVM NVPTX Back-End\n";
954 O << "//\n";
955 O << "\n";
956
Eric Christopher6aad8b12015-02-19 00:08:14 +0000957 unsigned PTXVersion = STI.getPTXVersion();
Justin Holewinski1812ee92012-11-12 03:16:43 +0000958 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000959
960 O << ".target ";
Eric Christopher6aad8b12015-02-19 00:08:14 +0000961 O << STI.getTargetName();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000962
Eric Christopherca929f22015-02-19 00:22:47 +0000963 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
964 if (NTM.getDrvInterface() == NVPTX::NVCL)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000965 O << ", texmode_independent";
Eric Christopherbeffc4e2015-02-19 00:08:23 +0000966 else {
Eric Christopher6aad8b12015-02-19 00:08:14 +0000967 if (!STI.hasDouble())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000968 O << ", map_f64_to_f32";
969 }
970
971 if (MAI->doesSupportDebugInformation())
972 O << ", debug";
973
974 O << "\n";
975
976 O << ".address_size ";
Eric Christopherca929f22015-02-19 00:22:47 +0000977 if (NTM.is64Bit())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000978 O << "64";
979 else
980 O << "32";
981 O << "\n";
982
983 O << "\n";
984}
985
986bool NVPTXAsmPrinter::doFinalization(Module &M) {
Justin Holewinski01f89f02013-05-20 12:13:32 +0000987 // If we did not emit any functions, then the global declarations have not
988 // yet been emitted.
989 if (!GlobalsEmitted) {
990 emitGlobals(M);
991 GlobalsEmitted = true;
992 }
993
Justin Holewinskiae556d32012-05-04 20:18:50 +0000994 // XXX Temproarily remove global variables so that doFinalization() will not
995 // emit them again (global variables are emitted at beginning).
996
997 Module::GlobalListType &global_list = M.getGlobalList();
998 int i, n = global_list.size();
Dylan Noblesmithc9e2a272014-08-26 02:03:35 +0000999 GlobalVariable **gv_array = new GlobalVariable *[n];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001000
1001 // first, back-up GlobalVariable in gv_array
1002 i = 0;
1003 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001004 I != E; ++I)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001005 gv_array[i++] = &*I;
1006
1007 // second, empty global_list
1008 while (!global_list.empty())
1009 global_list.remove(global_list.begin());
1010
1011 // call doFinalization
1012 bool ret = AsmPrinter::doFinalization(M);
1013
1014 // now we restore global variables
Justin Holewinski0497ab12013-03-30 14:29:21 +00001015 for (i = 0; i < n; i++)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001016 global_list.insert(global_list.end(), gv_array[i]);
1017
Justin Holewinski59596952014-04-09 15:38:52 +00001018 clearAnnotationCache(&M);
Dylan Noblesmithc9e2a272014-08-26 02:03:35 +00001019
1020 delete[] gv_array;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001021 return ret;
1022
Justin Holewinskiae556d32012-05-04 20:18:50 +00001023 //bool Result = AsmPrinter::doFinalization(M);
1024 // Instead of calling the parents doFinalization, we may
1025 // clone parents doFinalization and customize here.
1026 // Currently, we if NVISA out the EmitGlobals() in
1027 // parent's doFinalization, which is too intrusive.
1028 //
1029 // Same for the doInitialization.
1030 //return Result;
1031}
1032
1033// This function emits appropriate linkage directives for
1034// functions and global variables.
1035//
1036// extern function declaration -> .extern
1037// extern function definition -> .visible
1038// external global variable with init -> .visible
1039// external without init -> .extern
1040// appending -> not allowed, assert.
Justin Holewinski7d5bf662014-06-27 18:35:10 +00001041// for any linkage other than
1042// internal, private, linker_private,
1043// linker_private_weak, linker_private_weak_def_auto,
1044// we emit -> .weak.
Justin Holewinskiae556d32012-05-04 20:18:50 +00001045
Justin Holewinski0497ab12013-03-30 14:29:21 +00001046void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1047 raw_ostream &O) {
Eric Christopherbeffc4e2015-02-19 00:08:23 +00001048 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001049 if (V->hasExternalLinkage()) {
1050 if (isa<GlobalVariable>(V)) {
1051 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1052 if (GVar) {
1053 if (GVar->hasInitializer())
1054 O << ".visible ";
1055 else
1056 O << ".extern ";
1057 }
1058 } else if (V->isDeclaration())
1059 O << ".extern ";
1060 else
1061 O << ".visible ";
1062 } else if (V->hasAppendingLinkage()) {
1063 std::string msg;
1064 msg.append("Error: ");
1065 msg.append("Symbol ");
1066 if (V->hasName())
Yaron Keren075759a2015-03-30 15:42:36 +00001067 msg.append(V->getName());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001068 msg.append("has unsupported appending linkage type");
1069 llvm_unreachable(msg.c_str());
Justin Holewinski7d5bf662014-06-27 18:35:10 +00001070 } else if (!V->hasInternalLinkage() &&
1071 !V->hasPrivateLinkage()) {
1072 O << ".weak ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001073 }
1074 }
1075}
1076
Justin Holewinski01f89f02013-05-20 12:13:32 +00001077void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1078 raw_ostream &O,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001079 bool processDemoted) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001080 // Skip meta data
1081 if (GVar->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001082 if (GVar->getSection() == "llvm.metadata")
Justin Holewinskiae556d32012-05-04 20:18:50 +00001083 return;
1084 }
1085
Justin Holewinski73cb5de2014-06-27 18:35:53 +00001086 // Skip LLVM intrinsic global variables
1087 if (GVar->getName().startswith("llvm.") ||
1088 GVar->getName().startswith("nvvm."))
1089 return;
1090
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001091 const DataLayout &DL = getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001092
1093 // GlobalVariables are always constant pointers themselves.
Craig Toppere3dcce92015-08-01 22:20:21 +00001094 PointerType *PTy = GVar->getType();
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001095 Type *ETy = GVar->getValueType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001096
1097 if (GVar->hasExternalLinkage()) {
1098 if (GVar->hasInitializer())
1099 O << ".visible ";
1100 else
1101 O << ".extern ";
Justin Holewinskid73767a2014-06-27 18:35:56 +00001102 } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1103 GVar->hasAvailableExternallyLinkage() ||
1104 GVar->hasCommonLinkage()) {
1105 O << ".weak ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001106 }
1107
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001108 if (isTexture(*GVar)) {
1109 O << ".global .texref " << getTextureName(*GVar) << ";\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001110 return;
1111 }
1112
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001113 if (isSurface(*GVar)) {
1114 O << ".global .surfref " << getSurfaceName(*GVar) << ";\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001115 return;
1116 }
1117
1118 if (GVar->isDeclaration()) {
1119 // (extern) declarations, no definition or initializer
1120 // Currently the only known declaration is for an automatic __local
1121 // (.shared) promoted to global.
1122 emitPTXGlobalVariable(GVar, O);
1123 O << ";\n";
1124 return;
1125 }
1126
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001127 if (isSampler(*GVar)) {
1128 O << ".global .samplerref " << getSamplerName(*GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001129
Craig Topper062a2ba2014-04-25 05:30:21 +00001130 const Constant *Initializer = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001131 if (GVar->hasInitializer())
1132 Initializer = GVar->getInitializer();
Craig Topper062a2ba2014-04-25 05:30:21 +00001133 const ConstantInt *CI = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001134 if (Initializer)
1135 CI = dyn_cast<ConstantInt>(Initializer);
1136 if (CI) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001137 unsigned sample = CI->getZExtValue();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001138
1139 O << " = { ";
1140
Justin Holewinski0497ab12013-03-30 14:29:21 +00001141 for (int i = 0,
1142 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1143 i < 3; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001144 O << "addr_mode_" << i << " = ";
1145 switch (addr) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001146 case 0:
1147 O << "wrap";
1148 break;
1149 case 1:
1150 O << "clamp_to_border";
1151 break;
1152 case 2:
1153 O << "clamp_to_edge";
1154 break;
1155 case 3:
1156 O << "wrap";
1157 break;
1158 case 4:
1159 O << "mirror";
1160 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001161 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001162 O << ", ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001163 }
1164 O << "filter_mode = ";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001165 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1166 case 0:
1167 O << "nearest";
1168 break;
1169 case 1:
1170 O << "linear";
1171 break;
1172 case 2:
Craig Topper2a30d782014-06-18 05:05:13 +00001173 llvm_unreachable("Anisotropic filtering is not supported");
Justin Holewinski0497ab12013-03-30 14:29:21 +00001174 default:
1175 O << "nearest";
1176 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001177 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001178 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001179 O << ", force_unnormalized_coords = 1";
1180 }
1181 O << " }";
1182 }
1183
1184 O << ";\n";
1185 return;
1186 }
1187
1188 if (GVar->hasPrivateLinkage()) {
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001189 if (strncmp(GVar->getName().data(), "unrollpragma", 12) == 0)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001190 return;
1191
1192 // FIXME - need better way (e.g. Metadata) to avoid generating this global
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001193 if (strncmp(GVar->getName().data(), "filename", 8) == 0)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001194 return;
1195 if (GVar->use_empty())
1196 return;
1197 }
1198
Craig Topper062a2ba2014-04-25 05:30:21 +00001199 const Function *demotedFunc = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001200 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
Yaron Keren075759a2015-03-30 15:42:36 +00001201 O << "// " << GVar->getName() << " has been demoted\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001202 if (localDecls.find(demotedFunc) != localDecls.end())
1203 localDecls[demotedFunc].push_back(GVar);
1204 else {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001205 std::vector<const GlobalVariable *> temp;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001206 temp.push_back(GVar);
1207 localDecls[demotedFunc] = temp;
1208 }
1209 return;
1210 }
1211
1212 O << ".";
1213 emitPTXAddressSpace(PTy->getAddressSpace(), O);
Justin Holewinski773ca402014-06-27 18:35:58 +00001214
1215 if (isManaged(*GVar)) {
1216 O << " .attribute(.managed)";
1217 }
1218
Justin Holewinskiae556d32012-05-04 20:18:50 +00001219 if (GVar->getAlignment() == 0)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001220 O << " .align " << (int)DL.getPrefTypeAlignment(ETy);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001221 else
1222 O << " .align " << GVar->getAlignment();
1223
Jingyue Wue4c9cf02014-12-17 17:59:04 +00001224 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001225 O << " .";
Justin Holewinski700b6fa2013-05-20 12:13:28 +00001226 // Special case: ABI requires that we use .u8 for predicates
1227 if (ETy->isIntegerTy(1))
1228 O << "u8";
1229 else
1230 O << getPTXFundamentalTypeStr(ETy, false);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001231 O << " ";
Matt Arsenault8b643552015-06-09 00:31:39 +00001232 getSymbol(GVar)->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001233
1234 // Ptx allows variable initilization only for constant and global state
1235 // spaces.
Justin Holewinski549c7732014-06-27 18:36:01 +00001236 if (GVar->hasInitializer()) {
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001237 if ((PTy->getAddressSpace() == ADDRESS_SPACE_GLOBAL) ||
1238 (PTy->getAddressSpace() == ADDRESS_SPACE_CONST)) {
Justin Holewinski549c7732014-06-27 18:36:01 +00001239 const Constant *Initializer = GVar->getInitializer();
Jingyue Wu312fd022015-04-24 02:57:30 +00001240 // 'undef' is treated as there is no value specified.
Justin Holewinski549c7732014-06-27 18:36:01 +00001241 if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1242 O << " = ";
1243 printScalarConstant(Initializer, O);
1244 }
1245 } else {
Jingyue Wufcec0982015-08-22 05:40:26 +00001246 // The frontend adds zero-initializer to device and constant variables
1247 // that don't have an initial value, and UndefValue to shared
1248 // variables, so skip warning for this case.
1249 if (!GVar->getInitializer()->isNullValue() &&
1250 !isa<UndefValue>(GVar->getInitializer())) {
Benjamin Kramerdba7ee92015-05-28 11:24:24 +00001251 report_fatal_error("initial value of '" + GVar->getName() +
1252 "' is not allowed in addrspace(" +
1253 Twine(PTy->getAddressSpace()) + ")");
Justin Holewinski549c7732014-06-27 18:36:01 +00001254 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001255 }
1256 }
1257 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001258 unsigned int ElementSize = 0;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001259
1260 // Although PTX has direct support for struct type and array type and
1261 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1262 // targets that support these high level field accesses. Structs, arrays
1263 // and vectors are lowered into arrays of bytes.
1264 switch (ETy->getTypeID()) {
1265 case Type::StructTyID:
1266 case Type::ArrayTyID:
1267 case Type::VectorTyID:
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001268 ElementSize = DL.getTypeStoreSize(ETy);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001269 // Ptx allows variable initilization only for constant and
1270 // global state spaces.
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001271 if (((PTy->getAddressSpace() == ADDRESS_SPACE_GLOBAL) ||
1272 (PTy->getAddressSpace() == ADDRESS_SPACE_CONST)) &&
Justin Holewinski0497ab12013-03-30 14:29:21 +00001273 GVar->hasInitializer()) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001274 const Constant *Initializer = GVar->getInitializer();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001275 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001276 AggBuffer aggBuffer(ElementSize, O, *this);
1277 bufferAggregateConstant(Initializer, &aggBuffer);
1278 if (aggBuffer.numSymbols) {
Eric Christopher6aad8b12015-02-19 00:08:14 +00001279 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit()) {
Matt Arsenault8b643552015-06-09 00:31:39 +00001280 O << " .u64 ";
1281 getSymbol(GVar)->print(O, MAI);
1282 O << "[";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001283 O << ElementSize / 8;
1284 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001285 O << " .u32 ";
1286 getSymbol(GVar)->print(O, MAI);
1287 O << "[";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001288 O << ElementSize / 4;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001289 }
1290 O << "]";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001291 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001292 O << " .b8 ";
1293 getSymbol(GVar)->print(O, MAI);
1294 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001295 O << ElementSize;
1296 O << "]";
1297 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001298 O << " = {";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001299 aggBuffer.print();
1300 O << "}";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001301 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001302 O << " .b8 ";
1303 getSymbol(GVar)->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001304 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001305 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001306 O << ElementSize;
1307 O << "]";
1308 }
1309 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001310 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001311 O << " .b8 ";
1312 getSymbol(GVar)->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001313 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001314 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001315 O << ElementSize;
1316 O << "]";
1317 }
1318 }
1319 break;
1320 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001321 llvm_unreachable("type not supported yet");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001322 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001323 }
1324 O << ";\n";
1325}
1326
1327void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1328 if (localDecls.find(f) == localDecls.end())
1329 return;
1330
Justin Holewinski01f89f02013-05-20 12:13:32 +00001331 std::vector<const GlobalVariable *> &gvars = localDecls[f];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001332
Justin Holewinski0497ab12013-03-30 14:29:21 +00001333 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001334 O << "\t// demoted variable\n\t";
1335 printModuleLevelGV(gvars[i], O, true);
1336 }
1337}
1338
1339void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1340 raw_ostream &O) const {
1341 switch (AddressSpace) {
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001342 case ADDRESS_SPACE_LOCAL:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001343 O << "local";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001344 break;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001345 case ADDRESS_SPACE_GLOBAL:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001346 O << "global";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001347 break;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001348 case ADDRESS_SPACE_CONST:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001349 O << "const";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001350 break;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001351 case ADDRESS_SPACE_SHARED:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001352 O << "shared";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001353 break;
1354 default:
Justin Holewinski36a50992013-02-09 13:34:15 +00001355 report_fatal_error("Bad address space found while emitting PTX");
1356 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001357 }
1358}
1359
Justin Holewinski0497ab12013-03-30 14:29:21 +00001360std::string
Craig Toppere3dcce92015-08-01 22:20:21 +00001361NVPTXAsmPrinter::getPTXFundamentalTypeStr(Type *Ty, bool useB4PTR) const {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001362 switch (Ty->getTypeID()) {
1363 default:
1364 llvm_unreachable("unexpected type");
1365 break;
1366 case Type::IntegerTyID: {
1367 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1368 if (NumBits == 1)
1369 return "pred";
1370 else if (NumBits <= 64) {
1371 std::string name = "u";
1372 return name + utostr(NumBits);
1373 } else {
1374 llvm_unreachable("Integer too large");
1375 break;
1376 }
1377 break;
1378 }
1379 case Type::FloatTyID:
1380 return "f32";
1381 case Type::DoubleTyID:
1382 return "f64";
1383 case Type::PointerTyID:
Eric Christopher6aad8b12015-02-19 00:08:14 +00001384 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit())
Justin Holewinski0497ab12013-03-30 14:29:21 +00001385 if (useB4PTR)
1386 return "b64";
1387 else
1388 return "u64";
1389 else if (useB4PTR)
1390 return "b32";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001391 else
Justin Holewinski0497ab12013-03-30 14:29:21 +00001392 return "u32";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001393 }
1394 llvm_unreachable("unexpected type");
Craig Topper062a2ba2014-04-25 05:30:21 +00001395 return nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001396}
1397
Justin Holewinski0497ab12013-03-30 14:29:21 +00001398void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001399 raw_ostream &O) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001400 const DataLayout &DL = getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001401
1402 // GlobalVariables are always constant pointers themselves.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001403 Type *ETy = GVar->getValueType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001404
1405 O << ".";
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001406 emitPTXAddressSpace(GVar->getType()->getAddressSpace(), O);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001407 if (GVar->getAlignment() == 0)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001408 O << " .align " << (int)DL.getPrefTypeAlignment(ETy);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001409 else
1410 O << " .align " << GVar->getAlignment();
1411
Jingyue Wue4c9cf02014-12-17 17:59:04 +00001412 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001413 O << " .";
1414 O << getPTXFundamentalTypeStr(ETy);
1415 O << " ";
Matt Arsenault8b643552015-06-09 00:31:39 +00001416 getSymbol(GVar)->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001417 return;
1418 }
1419
Justin Holewinski0497ab12013-03-30 14:29:21 +00001420 int64_t ElementSize = 0;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001421
1422 // Although PTX has direct support for struct type and array type and LLVM IR
1423 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1424 // support these high level field accesses. Structs and arrays are lowered
1425 // into arrays of bytes.
1426 switch (ETy->getTypeID()) {
1427 case Type::StructTyID:
1428 case Type::ArrayTyID:
1429 case Type::VectorTyID:
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001430 ElementSize = DL.getTypeStoreSize(ETy);
Matt Arsenault8b643552015-06-09 00:31:39 +00001431 O << " .b8 ";
1432 getSymbol(GVar)->print(O, MAI);
1433 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001434 if (ElementSize) {
Benjamin Kramerdba7ee92015-05-28 11:24:24 +00001435 O << ElementSize;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001436 }
1437 O << "]";
1438 break;
1439 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001440 llvm_unreachable("type not supported yet");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001441 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001442}
1443
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001444static unsigned int getOpenCLAlignment(const DataLayout &DL, Type *Ty) {
Rafael Espindola08013342013-12-07 19:34:20 +00001445 if (Ty->isSingleValueType())
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001446 return DL.getPrefTypeAlignment(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001447
Craig Toppere3dcce92015-08-01 22:20:21 +00001448 auto *ATy = dyn_cast<ArrayType>(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001449 if (ATy)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001450 return getOpenCLAlignment(DL, ATy->getElementType());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001451
Craig Toppere3dcce92015-08-01 22:20:21 +00001452 auto *STy = dyn_cast<StructType>(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001453 if (STy) {
1454 unsigned int alignStruct = 1;
1455 // Go through each element of the struct and find the
1456 // largest alignment.
Justin Holewinski0497ab12013-03-30 14:29:21 +00001457 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001458 Type *ETy = STy->getElementType(i);
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001459 unsigned int align = getOpenCLAlignment(DL, ETy);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001460 if (align > alignStruct)
1461 alignStruct = align;
1462 }
1463 return alignStruct;
1464 }
1465
Craig Toppere3dcce92015-08-01 22:20:21 +00001466 auto *FTy = dyn_cast<FunctionType>(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001467 if (FTy)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001468 return DL.getPointerPrefAlignment();
1469 return DL.getPrefTypeAlignment(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001470}
1471
1472void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1473 int paramIndex, raw_ostream &O) {
Matt Arsenault8b643552015-06-09 00:31:39 +00001474 getSymbol(I->getParent())->print(O, MAI);
1475 O << "_param_" << paramIndex;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001476}
1477
Justin Holewinski0497ab12013-03-30 14:29:21 +00001478void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001479 const DataLayout &DL = getDataLayout();
Bill Wendlinge94d8432012-12-07 23:16:57 +00001480 const AttributeSet &PAL = F->getAttributes();
Eric Christopher6aad8b12015-02-19 00:08:14 +00001481 const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001482 Function::const_arg_iterator I, E;
1483 unsigned paramIndex = 0;
1484 bool first = true;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001485 bool isKernelFunc = isKernelFunction(*F);
Eric Christopher6aad8b12015-02-19 00:08:14 +00001486 bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001487 MVT thePointerTy = TLI->getPointerTy(DL);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001488
Justin Lebar2a161f92016-01-23 21:12:17 +00001489 if (F->arg_empty()) {
1490 O << "()\n";
1491 return;
1492 }
1493
Justin Holewinskiae556d32012-05-04 20:18:50 +00001494 O << "(\n";
1495
1496 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
Justin Holewinskie9884092013-03-24 21:17:47 +00001497 Type *Ty = I->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001498
1499 if (!first)
1500 O << ",\n";
1501
1502 first = false;
1503
1504 // Handle image/sampler parameters
Justin Holewinski30d56a72014-04-09 15:39:15 +00001505 if (isKernelFunction(*F)) {
1506 if (isSampler(*I) || isImage(*I)) {
1507 if (isImage(*I)) {
1508 std::string sname = I->getName();
1509 if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
Eric Christopher6aad8b12015-02-19 00:08:14 +00001510 if (nvptxSubtarget->hasImageHandles())
Justin Holewinski30d56a72014-04-09 15:39:15 +00001511 O << "\t.param .u64 .ptr .surfref ";
1512 else
1513 O << "\t.param .surfref ";
Matt Arsenault8b643552015-06-09 00:31:39 +00001514 CurrentFnSym->print(O, MAI);
1515 O << "_param_" << paramIndex;
Justin Holewinski30d56a72014-04-09 15:39:15 +00001516 }
1517 else { // Default image is read_only
Eric Christopher6aad8b12015-02-19 00:08:14 +00001518 if (nvptxSubtarget->hasImageHandles())
Justin Holewinski30d56a72014-04-09 15:39:15 +00001519 O << "\t.param .u64 .ptr .texref ";
1520 else
1521 O << "\t.param .texref ";
Matt Arsenault8b643552015-06-09 00:31:39 +00001522 CurrentFnSym->print(O, MAI);
1523 O << "_param_" << paramIndex;
Justin Holewinski30d56a72014-04-09 15:39:15 +00001524 }
1525 } else {
Eric Christopher6aad8b12015-02-19 00:08:14 +00001526 if (nvptxSubtarget->hasImageHandles())
Justin Holewinski30d56a72014-04-09 15:39:15 +00001527 O << "\t.param .u64 .ptr .samplerref ";
1528 else
1529 O << "\t.param .samplerref ";
Matt Arsenault8b643552015-06-09 00:31:39 +00001530 CurrentFnSym->print(O, MAI);
1531 O << "_param_" << paramIndex;
Justin Holewinski30d56a72014-04-09 15:39:15 +00001532 }
1533 continue;
1534 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001535 }
1536
Eli Bendersky3e840192015-03-23 16:26:23 +00001537 if (!PAL.hasAttribute(paramIndex + 1, Attribute::ByVal)) {
Gautam Chakrabarti2c283402014-01-28 18:35:29 +00001538 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1539 // Just print .param .align <a> .b8 .param[size];
Justin Holewinskie9884092013-03-24 21:17:47 +00001540 // <a> = PAL.getparamalignment
1541 // size = typeallocsize of element type
Justin Holewinski0497ab12013-03-30 14:29:21 +00001542 unsigned align = PAL.getParamAlignment(paramIndex + 1);
Justin Holewinskie9884092013-03-24 21:17:47 +00001543 if (align == 0)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001544 align = DL.getABITypeAlignment(Ty);
Justin Holewinskie9884092013-03-24 21:17:47 +00001545
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001546 unsigned sz = DL.getTypeAllocSize(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001547 O << "\t.param .align " << align << " .b8 ";
Justin Holewinskie9884092013-03-24 21:17:47 +00001548 printParamName(I, paramIndex, O);
1549 O << "[" << sz << "]";
1550
1551 continue;
1552 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001553 // Just a scalar
Craig Toppere3dcce92015-08-01 22:20:21 +00001554 auto *PTy = dyn_cast<PointerType>(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001555 if (isKernelFunc) {
1556 if (PTy) {
1557 // Special handling for pointer arguments to kernel
1558 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1559
Eric Christopherbeffc4e2015-02-19 00:08:23 +00001560 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() !=
1561 NVPTX::CUDA) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001562 Type *ETy = PTy->getElementType();
1563 int addrSpace = PTy->getAddressSpace();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001564 switch (addrSpace) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001565 default:
1566 O << ".ptr ";
1567 break;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001568 case ADDRESS_SPACE_CONST:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001569 O << ".ptr .const ";
1570 break;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001571 case ADDRESS_SPACE_SHARED:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001572 O << ".ptr .shared ";
1573 break;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001574 case ADDRESS_SPACE_GLOBAL:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001575 O << ".ptr .global ";
1576 break;
1577 }
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001578 O << ".align " << (int)getOpenCLAlignment(DL, ETy) << " ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001579 }
1580 printParamName(I, paramIndex, O);
1581 continue;
1582 }
1583
1584 // non-pointer scalar to kernel func
Justin Holewinski700b6fa2013-05-20 12:13:28 +00001585 O << "\t.param .";
1586 // Special case: predicate operands become .u8 types
1587 if (Ty->isIntegerTy(1))
1588 O << "u8";
1589 else
1590 O << getPTXFundamentalTypeStr(Ty);
1591 O << " ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001592 printParamName(I, paramIndex, O);
1593 continue;
1594 }
1595 // Non-kernel function, just print .param .b<size> for ABI
Alp Tokerf907b892013-12-05 05:44:44 +00001596 // and .reg .b<size> for non-ABI
Justin Holewinskiae556d32012-05-04 20:18:50 +00001597 unsigned sz = 0;
1598 if (isa<IntegerType>(Ty)) {
1599 sz = cast<IntegerType>(Ty)->getBitWidth();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001600 if (sz < 32)
1601 sz = 32;
1602 } else if (isa<PointerType>(Ty))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001603 sz = thePointerTy.getSizeInBits();
1604 else
1605 sz = Ty->getPrimitiveSizeInBits();
1606 if (isABI)
1607 O << "\t.param .b" << sz << " ";
1608 else
1609 O << "\t.reg .b" << sz << " ";
1610 printParamName(I, paramIndex, O);
1611 continue;
1612 }
1613
1614 // param has byVal attribute. So should be a pointer
Craig Toppere3dcce92015-08-01 22:20:21 +00001615 auto *PTy = dyn_cast<PointerType>(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001616 assert(PTy && "Param with byval attribute should be a pointer type");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001617 Type *ETy = PTy->getElementType();
1618
1619 if (isABI || isKernelFunc) {
Gautam Chakrabarti2c283402014-01-28 18:35:29 +00001620 // Just print .param .align <a> .b8 .param[size];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001621 // <a> = PAL.getparamalignment
1622 // size = typeallocsize of element type
Justin Holewinski0497ab12013-03-30 14:29:21 +00001623 unsigned align = PAL.getParamAlignment(paramIndex + 1);
Justin Holewinski2dc9d072012-11-09 23:50:24 +00001624 if (align == 0)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001625 align = DL.getABITypeAlignment(ETy);
Artem Belevich052b1ed2016-07-18 19:54:56 +00001626 // Work around a bug in ptxas. When PTX code takes address of
1627 // byval parameter with alignment < 4, ptxas generates code to
1628 // spill argument into memory. Alas on sm_50+ ptxas generates
1629 // SASS code that fails with misaligned access. To work around
1630 // the problem, make sure that we align byval parameters by at
1631 // least 4. Matching change must be made in LowerCall() where we
1632 // prepare parameters for the call.
1633 //
1634 // TODO: this will need to be undone when we get to support multi-TU
1635 // device-side compilation as it breaks ABI compatibility with nvcc.
1636 // Hopefully ptxas bug is fixed by then.
1637 if (!isKernelFunc && align < 4)
1638 align = 4;
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001639 unsigned sz = DL.getTypeAllocSize(ETy);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001640 O << "\t.param .align " << align << " .b8 ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001641 printParamName(I, paramIndex, O);
1642 O << "[" << sz << "]";
1643 continue;
1644 } else {
1645 // Split the ETy into constituent parts and
1646 // print .param .b<size> <name> for each part.
1647 // Further, if a part is vector, print the above for
1648 // each vector element.
1649 SmallVector<EVT, 16> vtparts;
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001650 ComputeValueVTs(*TLI, DL, ETy, vtparts);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001651 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001652 unsigned elems = 1;
1653 EVT elemtype = vtparts[i];
1654 if (vtparts[i].isVector()) {
1655 elems = vtparts[i].getVectorNumElements();
1656 elemtype = vtparts[i].getVectorElementType();
1657 }
1658
Justin Holewinski0497ab12013-03-30 14:29:21 +00001659 for (unsigned j = 0, je = elems; j != je; ++j) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001660 unsigned sz = elemtype.getSizeInBits();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001661 if (elemtype.isInteger() && (sz < 32))
1662 sz = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001663 O << "\t.reg .b" << sz << " ";
1664 printParamName(I, paramIndex, O);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001665 if (j < je - 1)
1666 O << ",\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001667 ++paramIndex;
1668 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001669 if (i < e - 1)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001670 O << ",\n";
1671 }
1672 --paramIndex;
1673 continue;
1674 }
1675 }
1676
1677 O << "\n)\n";
1678}
1679
1680void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1681 raw_ostream &O) {
1682 const Function *F = MF.getFunction();
1683 emitFunctionParamList(F, O);
1684}
1685
Justin Holewinski0497ab12013-03-30 14:29:21 +00001686void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1687 const MachineFunction &MF) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001688 SmallString<128> Str;
1689 raw_svector_ostream O(Str);
1690
1691 // Map the global virtual register number to a register class specific
1692 // virtual register number starting from 1 with that class.
Eric Christopherfc6de422014-08-05 02:39:49 +00001693 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001694 //unsigned numRegClasses = TRI->getNumRegClasses();
1695
1696 // Emit the Fake Stack Object
Matthias Braun941a7052016-07-28 18:40:00 +00001697 const MachineFrameInfo &MFI = MF.getFrameInfo();
1698 int NumBytes = (int) MFI.getStackSize();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001699 if (NumBytes) {
Matthias Braun941a7052016-07-28 18:40:00 +00001700 O << "\t.local .align " << MFI.getMaxAlignment() << " .b8 \t" << DEPOTNAME
Justin Holewinski0497ab12013-03-30 14:29:21 +00001701 << getFunctionNumber() << "[" << NumBytes << "];\n";
Eric Christopher02389e32015-02-19 00:08:27 +00001702 if (static_cast<const NVPTXTargetMachine &>(MF.getTarget()).is64Bit()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001703 O << "\t.reg .b64 \t%SP;\n";
1704 O << "\t.reg .b64 \t%SPL;\n";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001705 } else {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001706 O << "\t.reg .b32 \t%SP;\n";
1707 O << "\t.reg .b32 \t%SPL;\n";
1708 }
1709 }
1710
1711 // Go through all virtual registers to establish the mapping between the
1712 // global virtual
1713 // register number and the per class virtual register number.
1714 // We use the per class virtual register number in the ptx output.
1715 unsigned int numVRs = MRI->getNumVirtRegs();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001716 for (unsigned i = 0; i < numVRs; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001717 unsigned int vr = TRI->index2VirtReg(i);
1718 const TargetRegisterClass *RC = MRI->getRegClass(vr);
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001719 DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001720 int n = regmap.size();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001721 regmap.insert(std::make_pair(vr, n + 1));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001722 }
1723
1724 // Emit register declarations
1725 // @TODO: Extract out the real register usage
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001726 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1727 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1728 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1729 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
Justin Holewinski3e037d92014-07-16 16:26:58 +00001730 // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001731 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
Justin Holewinski3e037d92014-07-16 16:26:58 +00001732 // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001733
1734 // Emit declaration of the virtual registers or 'physical' registers for
1735 // each register class
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001736 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1737 const TargetRegisterClass *RC = TRI->getRegClass(i);
1738 DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
1739 std::string rcname = getNVPTXRegClassName(RC);
1740 std::string rcStr = getNVPTXRegClassStr(RC);
1741 int n = regmap.size();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001742
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001743 // Only declare those registers that may be used.
1744 if (n) {
1745 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1746 << ">;\n";
1747 }
1748 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001749
Lang Hames9ff69c82015-04-24 19:11:51 +00001750 OutStreamer->EmitRawText(O.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001751}
1752
Justin Holewinskiae556d32012-05-04 20:18:50 +00001753void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001754 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
Justin Holewinskiae556d32012-05-04 20:18:50 +00001755 bool ignored;
1756 unsigned int numHex;
1757 const char *lead;
1758
Justin Holewinski0497ab12013-03-30 14:29:21 +00001759 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001760 numHex = 8;
1761 lead = "0f";
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001762 APF.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &ignored);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001763 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1764 numHex = 16;
1765 lead = "0d";
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001766 APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &ignored);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001767 } else
1768 llvm_unreachable("unsupported fp type");
1769
1770 APInt API = APF.bitcastToAPInt();
1771 std::string hexstr(utohexstr(API.getZExtValue()));
1772 O << lead;
1773 if (hexstr.length() < numHex)
1774 O << std::string(numHex - hexstr.length(), '0');
1775 O << utohexstr(API.getZExtValue());
1776}
1777
Justin Holewinski01f89f02013-05-20 12:13:32 +00001778void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1779 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001780 O << CI->getValue();
1781 return;
1782 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001783 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001784 printFPConstant(CFP, O);
1785 return;
1786 }
1787 if (isa<ConstantPointerNull>(CPV)) {
1788 O << "0";
1789 return;
1790 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001791 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
Justin Holewinski9d852a82014-04-09 15:39:11 +00001792 bool IsNonGenericPointer = false;
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001793 if (GVar->getType()->getAddressSpace() != 0) {
Justin Holewinski9d852a82014-04-09 15:39:11 +00001794 IsNonGenericPointer = true;
1795 }
1796 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1797 O << "generic(";
Matt Arsenault8b643552015-06-09 00:31:39 +00001798 getSymbol(GVar)->print(O, MAI);
Justin Holewinski9d852a82014-04-09 15:39:11 +00001799 O << ")";
1800 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001801 getSymbol(GVar)->print(O, MAI);
Justin Holewinski9d852a82014-04-09 15:39:11 +00001802 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001803 return;
1804 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001805 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1806 const Value *v = Cexpr->stripPointerCasts();
Justin Holewinski9d852a82014-04-09 15:39:11 +00001807 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1808 bool IsNonGenericPointer = false;
1809 if (PTy && PTy->getAddressSpace() != 0) {
1810 IsNonGenericPointer = true;
1811 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001812 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
Justin Holewinski9d852a82014-04-09 15:39:11 +00001813 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1814 O << "generic(";
Matt Arsenault8b643552015-06-09 00:31:39 +00001815 getSymbol(GVar)->print(O, MAI);
Justin Holewinski9d852a82014-04-09 15:39:11 +00001816 O << ")";
1817 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001818 getSymbol(GVar)->print(O, MAI);
Justin Holewinski9d852a82014-04-09 15:39:11 +00001819 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001820 return;
1821 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001822 lowerConstant(CPV)->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001823 return;
1824 }
1825 }
1826 llvm_unreachable("Not scalar type found in printScalarConstant()");
1827}
1828
Samuel Antaocd501352015-06-09 16:29:34 +00001829// These utility functions assure we get the right sequence of bytes for a given
1830// type even for big-endian machines
1831template <typename T> static void ConvertIntToBytes(unsigned char *p, T val) {
1832 int64_t vp = (int64_t)val;
1833 for (unsigned i = 0; i < sizeof(T); ++i) {
1834 p[i] = (unsigned char)vp;
1835 vp >>= 8;
1836 }
1837}
1838static void ConvertFloatToBytes(unsigned char *p, float val) {
1839 int32_t *vp = (int32_t *)&val;
1840 for (unsigned i = 0; i < sizeof(int32_t); ++i) {
1841 p[i] = (unsigned char)*vp;
1842 *vp >>= 8;
1843 }
1844}
1845static void ConvertDoubleToBytes(unsigned char *p, double val) {
1846 int64_t *vp = (int64_t *)&val;
1847 for (unsigned i = 0; i < sizeof(int64_t); ++i) {
1848 p[i] = (unsigned char)*vp;
1849 *vp >>= 8;
1850 }
1851}
1852
Justin Holewinski01f89f02013-05-20 12:13:32 +00001853void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001854 AggBuffer *aggBuffer) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001855 const DataLayout &DL = getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001856
1857 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001858 int s = DL.getTypeAllocSize(CPV->getType());
Justin Holewinski0497ab12013-03-30 14:29:21 +00001859 if (s < Bytes)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001860 s = Bytes;
1861 aggBuffer->addZeros(s);
1862 return;
1863 }
1864
Samuel Antaocd501352015-06-09 16:29:34 +00001865 unsigned char ptr[8];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001866 switch (CPV->getType()->getTypeID()) {
1867
1868 case Type::IntegerTyID: {
Craig Toppere3dcce92015-08-01 22:20:21 +00001869 Type *ETy = CPV->getType();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001870 if (ETy == Type::getInt8Ty(CPV->getContext())) {
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001871 unsigned char c = (unsigned char)cast<ConstantInt>(CPV)->getZExtValue();
Samuel Antaocd501352015-06-09 16:29:34 +00001872 ConvertIntToBytes<>(ptr, c);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001873 aggBuffer->addBytes(ptr, 1, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001874 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001875 short int16 = (short)cast<ConstantInt>(CPV)->getZExtValue();
Samuel Antaocd501352015-06-09 16:29:34 +00001876 ConvertIntToBytes<>(ptr, int16);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001877 aggBuffer->addBytes(ptr, 2, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001878 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001879 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001880 int int32 = (int)(constInt->getZExtValue());
Samuel Antaocd501352015-06-09 16:29:34 +00001881 ConvertIntToBytes<>(ptr, int32);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001882 aggBuffer->addBytes(ptr, 4, Bytes);
1883 break;
David Majnemerd536f232016-07-29 03:27:26 +00001884 } else if (const auto *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1885 if (const auto *constInt = dyn_cast_or_null<ConstantInt>(
1886 ConstantFoldConstant(Cexpr, DL))) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001887 int int32 = (int)(constInt->getZExtValue());
Samuel Antaocd501352015-06-09 16:29:34 +00001888 ConvertIntToBytes<>(ptr, int32);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001889 aggBuffer->addBytes(ptr, 4, Bytes);
1890 break;
1891 }
1892 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1893 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
Jingyue Wu312fd022015-04-24 02:57:30 +00001894 aggBuffer->addSymbol(v, Cexpr->getOperand(0));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001895 aggBuffer->addZeros(4);
1896 break;
1897 }
1898 }
Craig Topperbdf39a42012-05-24 07:02:50 +00001899 llvm_unreachable("unsupported integer const type");
Justin Holewinski0497ab12013-03-30 14:29:21 +00001900 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001901 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001902 long long int64 = (long long)(constInt->getZExtValue());
Samuel Antaocd501352015-06-09 16:29:34 +00001903 ConvertIntToBytes<>(ptr, int64);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001904 aggBuffer->addBytes(ptr, 8, Bytes);
1905 break;
Justin Holewinski01f89f02013-05-20 12:13:32 +00001906 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
David Majnemerd536f232016-07-29 03:27:26 +00001907 if (const auto *constInt = dyn_cast_or_null<ConstantInt>(
1908 ConstantFoldConstant(Cexpr, DL))) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001909 long long int64 = (long long)(constInt->getZExtValue());
Samuel Antaocd501352015-06-09 16:29:34 +00001910 ConvertIntToBytes<>(ptr, int64);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001911 aggBuffer->addBytes(ptr, 8, Bytes);
1912 break;
1913 }
1914 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1915 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
Jingyue Wu312fd022015-04-24 02:57:30 +00001916 aggBuffer->addSymbol(v, Cexpr->getOperand(0));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001917 aggBuffer->addZeros(8);
1918 break;
1919 }
1920 }
1921 llvm_unreachable("unsupported integer const type");
Craig Topperbdf39a42012-05-24 07:02:50 +00001922 } else
Justin Holewinskiae556d32012-05-04 20:18:50 +00001923 llvm_unreachable("unsupported integer const type");
1924 break;
1925 }
1926 case Type::FloatTyID:
1927 case Type::DoubleTyID: {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001928 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
Craig Toppere3dcce92015-08-01 22:20:21 +00001929 Type *Ty = CFP->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001930 if (Ty == Type::getFloatTy(CPV->getContext())) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001931 float float32 = (float) CFP->getValueAPF().convertToFloat();
Samuel Antaocd501352015-06-09 16:29:34 +00001932 ConvertFloatToBytes(ptr, float32);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001933 aggBuffer->addBytes(ptr, 4, Bytes);
1934 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1935 double float64 = CFP->getValueAPF().convertToDouble();
Samuel Antaocd501352015-06-09 16:29:34 +00001936 ConvertDoubleToBytes(ptr, float64);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001937 aggBuffer->addBytes(ptr, 8, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001938 } else {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001939 llvm_unreachable("unsupported fp const type");
1940 }
1941 break;
1942 }
1943 case Type::PointerTyID: {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001944 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
Jingyue Wu312fd022015-04-24 02:57:30 +00001945 aggBuffer->addSymbol(GVar, GVar);
Justin Holewinski01f89f02013-05-20 12:13:32 +00001946 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1947 const Value *v = Cexpr->stripPointerCasts();
Jingyue Wu312fd022015-04-24 02:57:30 +00001948 aggBuffer->addSymbol(v, Cexpr);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001949 }
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001950 unsigned int s = DL.getTypeAllocSize(CPV->getType());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001951 aggBuffer->addZeros(s);
1952 break;
1953 }
1954
1955 case Type::ArrayTyID:
1956 case Type::VectorTyID:
1957 case Type::StructTyID: {
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00001958 if (isa<ConstantAggregate>(CPV) || isa<ConstantDataSequential>(CPV)) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001959 int ElementSize = DL.getTypeAllocSize(CPV->getType());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001960 bufferAggregateConstant(CPV, aggBuffer);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001961 if (Bytes > ElementSize)
1962 aggBuffer->addZeros(Bytes - ElementSize);
1963 } else if (isa<ConstantAggregateZero>(CPV))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001964 aggBuffer->addZeros(Bytes);
1965 else
1966 llvm_unreachable("Unexpected Constant type");
1967 break;
1968 }
1969
1970 default:
1971 llvm_unreachable("unsupported type");
1972 }
1973}
1974
Justin Holewinski01f89f02013-05-20 12:13:32 +00001975void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001976 AggBuffer *aggBuffer) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001977 const DataLayout &DL = getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001978 int Bytes;
1979
1980 // Old constants
1981 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1982 if (CPV->getNumOperands())
1983 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1984 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1985 return;
1986 }
1987
1988 if (const ConstantDataSequential *CDS =
Justin Holewinski0497ab12013-03-30 14:29:21 +00001989 dyn_cast<ConstantDataSequential>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001990 if (CDS->getNumElements())
1991 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1992 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1993 aggBuffer);
1994 return;
1995 }
1996
Justin Holewinskiae556d32012-05-04 20:18:50 +00001997 if (isa<ConstantStruct>(CPV)) {
1998 if (CPV->getNumOperands()) {
1999 StructType *ST = cast<StructType>(CPV->getType());
2000 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002001 if (i == (e - 1))
Mehdi Aminibd7287e2015-07-16 06:11:10 +00002002 Bytes = DL.getStructLayout(ST)->getElementOffset(0) +
2003 DL.getTypeAllocSize(ST) -
2004 DL.getStructLayout(ST)->getElementOffset(i);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002005 else
Mehdi Aminibd7287e2015-07-16 06:11:10 +00002006 Bytes = DL.getStructLayout(ST)->getElementOffset(i + 1) -
2007 DL.getStructLayout(ST)->getElementOffset(i);
Justin Holewinski0497ab12013-03-30 14:29:21 +00002008 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002009 }
2010 }
2011 return;
2012 }
Craig Topperbdf39a42012-05-24 07:02:50 +00002013 llvm_unreachable("unsupported constant type in printAggregateConstant()");
Justin Holewinskiae556d32012-05-04 20:18:50 +00002014}
2015
2016// buildTypeNameMap - Run through symbol table looking for type names.
2017//
2018
Justin Holewinski0497ab12013-03-30 14:29:21 +00002019bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
2020 switch (MI.getOpcode()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00002021 default:
2022 return false;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002023 case NVPTX::CallArgBeginInst:
2024 case NVPTX::CallArgEndInst0:
2025 case NVPTX::CallArgEndInst1:
2026 case NVPTX::CallArgF32:
2027 case NVPTX::CallArgF64:
2028 case NVPTX::CallArgI16:
2029 case NVPTX::CallArgI32:
2030 case NVPTX::CallArgI32imm:
2031 case NVPTX::CallArgI64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002032 case NVPTX::CallArgParam:
2033 case NVPTX::CallVoidInst:
2034 case NVPTX::CallVoidInstReg:
2035 case NVPTX::Callseq_End:
Justin Holewinskiae556d32012-05-04 20:18:50 +00002036 case NVPTX::CallVoidInstReg64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002037 case NVPTX::DeclareParamInst:
2038 case NVPTX::DeclareRetMemInst:
2039 case NVPTX::DeclareRetRegInst:
2040 case NVPTX::DeclareRetScalarInst:
2041 case NVPTX::DeclareScalarParamInst:
2042 case NVPTX::DeclareScalarRegInst:
2043 case NVPTX::StoreParamF32:
2044 case NVPTX::StoreParamF64:
2045 case NVPTX::StoreParamI16:
2046 case NVPTX::StoreParamI32:
2047 case NVPTX::StoreParamI64:
2048 case NVPTX::StoreParamI8:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002049 case NVPTX::StoreRetvalF32:
2050 case NVPTX::StoreRetvalF64:
2051 case NVPTX::StoreRetvalI16:
2052 case NVPTX::StoreRetvalI32:
2053 case NVPTX::StoreRetvalI64:
2054 case NVPTX::StoreRetvalI8:
2055 case NVPTX::LastCallArgF32:
2056 case NVPTX::LastCallArgF64:
2057 case NVPTX::LastCallArgI16:
2058 case NVPTX::LastCallArgI32:
2059 case NVPTX::LastCallArgI32imm:
2060 case NVPTX::LastCallArgI64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002061 case NVPTX::LastCallArgParam:
2062 case NVPTX::LoadParamMemF32:
2063 case NVPTX::LoadParamMemF64:
2064 case NVPTX::LoadParamMemI16:
2065 case NVPTX::LoadParamMemI32:
2066 case NVPTX::LoadParamMemI64:
2067 case NVPTX::LoadParamMemI8:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002068 case NVPTX::PrototypeInst:
2069 case NVPTX::DBG_VALUE:
Justin Holewinskiae556d32012-05-04 20:18:50 +00002070 return true;
2071 }
2072 return false;
2073}
2074
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002075/// lowerConstantForGV - Return an MCExpr for the given Constant. This is mostly
2076/// a copy from AsmPrinter::lowerConstant, except customized to only handle
2077/// expressions that are representable in PTX and create
2078/// NVPTXGenericMCSymbolRefExpr nodes for addrspacecast instructions.
2079const MCExpr *
2080NVPTXAsmPrinter::lowerConstantForGV(const Constant *CV, bool ProcessingGeneric) {
2081 MCContext &Ctx = OutContext;
2082
2083 if (CV->isNullValue() || isa<UndefValue>(CV))
Jim Grosbach13760bd2015-05-30 01:25:56 +00002084 return MCConstantExpr::create(0, Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002085
2086 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
Jim Grosbach13760bd2015-05-30 01:25:56 +00002087 return MCConstantExpr::create(CI->getZExtValue(), Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002088
2089 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
2090 const MCSymbolRefExpr *Expr =
Jim Grosbach13760bd2015-05-30 01:25:56 +00002091 MCSymbolRefExpr::create(getSymbol(GV), Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002092 if (ProcessingGeneric) {
Jim Grosbach13760bd2015-05-30 01:25:56 +00002093 return NVPTXGenericMCSymbolRefExpr::create(Expr, Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002094 } else {
2095 return Expr;
2096 }
2097 }
2098
2099 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
2100 if (!CE) {
2101 llvm_unreachable("Unknown constant value to lower!");
2102 }
2103
2104 switch (CE->getOpcode()) {
2105 default:
2106 // If the code isn't optimized, there may be outstanding folding
2107 // opportunities. Attempt to fold the expression using DataLayout as a
2108 // last resort before giving up.
David Majnemerd536f232016-07-29 03:27:26 +00002109 if (Constant *C = ConstantFoldConstant(CE, getDataLayout()))
2110 if (C && C != CE)
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002111 return lowerConstantForGV(C, ProcessingGeneric);
2112
2113 // Otherwise report the problem to the user.
2114 {
2115 std::string S;
2116 raw_string_ostream OS(S);
2117 OS << "Unsupported expression in static initializer: ";
2118 CE->printAsOperand(OS, /*PrintType=*/false,
2119 !MF ? nullptr : MF->getFunction()->getParent());
2120 report_fatal_error(OS.str());
2121 }
2122
2123 case Instruction::AddrSpaceCast: {
2124 // Strip the addrspacecast and pass along the operand
2125 PointerType *DstTy = cast<PointerType>(CE->getType());
2126 if (DstTy->getAddressSpace() == 0) {
2127 return lowerConstantForGV(cast<const Constant>(CE->getOperand(0)), true);
2128 }
2129 std::string S;
2130 raw_string_ostream OS(S);
2131 OS << "Unsupported expression in static initializer: ";
2132 CE->printAsOperand(OS, /*PrintType=*/ false,
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00002133 !MF ? nullptr : MF->getFunction()->getParent());
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002134 report_fatal_error(OS.str());
2135 }
2136
2137 case Instruction::GetElementPtr: {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00002138 const DataLayout &DL = getDataLayout();
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002139
2140 // Generate a symbolic expression for the byte address
2141 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
2142 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
2143
2144 const MCExpr *Base = lowerConstantForGV(CE->getOperand(0),
2145 ProcessingGeneric);
2146 if (!OffsetAI)
2147 return Base;
2148
2149 int64_t Offset = OffsetAI.getSExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00002150 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002151 Ctx);
2152 }
2153
2154 case Instruction::Trunc:
2155 // We emit the value and depend on the assembler to truncate the generated
2156 // expression properly. This is important for differences between
2157 // blockaddress labels. Since the two labels are in the same function, it
2158 // is reasonable to treat their delta as a 32-bit value.
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002159 LLVM_FALLTHROUGH;
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002160 case Instruction::BitCast:
2161 return lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2162
2163 case Instruction::IntToPtr: {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00002164 const DataLayout &DL = getDataLayout();
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002165
2166 // Handle casts to pointers by changing them into casts to the appropriate
2167 // integer type. This promotes constant folding and simplifies this code.
2168 Constant *Op = CE->getOperand(0);
2169 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
2170 false/*ZExt*/);
2171 return lowerConstantForGV(Op, ProcessingGeneric);
2172 }
2173
2174 case Instruction::PtrToInt: {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00002175 const DataLayout &DL = getDataLayout();
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002176
2177 // Support only foldable casts to/from pointers that can be eliminated by
2178 // changing the pointer to the appropriately sized integer type.
2179 Constant *Op = CE->getOperand(0);
2180 Type *Ty = CE->getType();
2181
2182 const MCExpr *OpExpr = lowerConstantForGV(Op, ProcessingGeneric);
2183
2184 // We can emit the pointer value into this slot if the slot is an
2185 // integer slot equal to the size of the pointer.
2186 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
2187 return OpExpr;
2188
2189 // Otherwise the pointer is smaller than the resultant integer, mask off
2190 // the high bits so we are sure to get a proper truncation if the input is
2191 // a constant expr.
2192 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
Jim Grosbach13760bd2015-05-30 01:25:56 +00002193 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
2194 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002195 }
2196
2197 // The MC library also has a right-shift operator, but it isn't consistently
2198 // signed or unsigned between different targets.
2199 case Instruction::Add: {
2200 const MCExpr *LHS = lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2201 const MCExpr *RHS = lowerConstantForGV(CE->getOperand(1), ProcessingGeneric);
2202 switch (CE->getOpcode()) {
2203 default: llvm_unreachable("Unknown binary operator constant cast expr");
Jim Grosbach13760bd2015-05-30 01:25:56 +00002204 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002205 }
2206 }
2207 }
2208}
2209
2210// Copy of MCExpr::print customized for NVPTX
2211void NVPTXAsmPrinter::printMCExpr(const MCExpr &Expr, raw_ostream &OS) {
2212 switch (Expr.getKind()) {
2213 case MCExpr::Target:
Matt Arsenault8b643552015-06-09 00:31:39 +00002214 return cast<MCTargetExpr>(&Expr)->printImpl(OS, MAI);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002215 case MCExpr::Constant:
2216 OS << cast<MCConstantExpr>(Expr).getValue();
2217 return;
2218
2219 case MCExpr::SymbolRef: {
2220 const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(Expr);
2221 const MCSymbol &Sym = SRE.getSymbol();
Matt Arsenault8b643552015-06-09 00:31:39 +00002222 Sym.print(OS, MAI);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002223 return;
2224 }
2225
2226 case MCExpr::Unary: {
2227 const MCUnaryExpr &UE = cast<MCUnaryExpr>(Expr);
2228 switch (UE.getOpcode()) {
2229 case MCUnaryExpr::LNot: OS << '!'; break;
2230 case MCUnaryExpr::Minus: OS << '-'; break;
2231 case MCUnaryExpr::Not: OS << '~'; break;
2232 case MCUnaryExpr::Plus: OS << '+'; break;
2233 }
2234 printMCExpr(*UE.getSubExpr(), OS);
2235 return;
2236 }
2237
2238 case MCExpr::Binary: {
2239 const MCBinaryExpr &BE = cast<MCBinaryExpr>(Expr);
2240
2241 // Only print parens around the LHS if it is non-trivial.
2242 if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS()) ||
2243 isa<NVPTXGenericMCSymbolRefExpr>(BE.getLHS())) {
2244 printMCExpr(*BE.getLHS(), OS);
2245 } else {
2246 OS << '(';
2247 printMCExpr(*BE.getLHS(), OS);
2248 OS<< ')';
2249 }
2250
2251 switch (BE.getOpcode()) {
2252 case MCBinaryExpr::Add:
2253 // Print "X-42" instead of "X+-42".
2254 if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
2255 if (RHSC->getValue() < 0) {
2256 OS << RHSC->getValue();
2257 return;
2258 }
2259 }
2260
2261 OS << '+';
2262 break;
2263 default: llvm_unreachable("Unhandled binary operator");
2264 }
2265
2266 // Only print parens around the LHS if it is non-trivial.
2267 if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
2268 printMCExpr(*BE.getRHS(), OS);
2269 } else {
2270 OS << '(';
2271 printMCExpr(*BE.getRHS(), OS);
2272 OS << ')';
2273 }
2274 return;
2275 }
2276 }
2277
2278 llvm_unreachable("Invalid expression kind!");
2279}
2280
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002281/// PrintAsmOperand - Print out an operand for an inline asm expression.
2282///
2283bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2284 unsigned AsmVariant,
2285 const char *ExtraCode, raw_ostream &O) {
2286 if (ExtraCode && ExtraCode[0]) {
2287 if (ExtraCode[1] != 0)
2288 return true; // Unknown modifier.
2289
2290 switch (ExtraCode[0]) {
2291 default:
2292 // See if this is a generic print operand
2293 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2294 case 'r':
2295 break;
2296 }
2297 }
2298
2299 printOperand(MI, OpNo, O);
2300
2301 return false;
2302}
2303
2304bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2305 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2306 const char *ExtraCode, raw_ostream &O) {
2307 if (ExtraCode && ExtraCode[0])
2308 return true; // Unknown modifier
2309
2310 O << '[';
2311 printMemOperand(MI, OpNo, O);
2312 O << ']';
2313
2314 return false;
2315}
2316
2317void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2318 raw_ostream &O, const char *Modifier) {
2319 const MachineOperand &MO = MI->getOperand(opNum);
2320 switch (MO.getType()) {
2321 case MachineOperand::MO_Register:
2322 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2323 if (MO.getReg() == NVPTX::VRDepot)
2324 O << DEPOTNAME << getFunctionNumber();
2325 else
2326 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2327 } else {
Justin Holewinski660597d2013-10-11 12:39:36 +00002328 emitVirtualRegister(MO.getReg(), O);
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002329 }
2330 return;
2331
2332 case MachineOperand::MO_Immediate:
2333 if (!Modifier)
2334 O << MO.getImm();
2335 else if (strstr(Modifier, "vec") == Modifier)
2336 printVecModifiedImmediate(MO, Modifier, O);
2337 else
2338 llvm_unreachable(
2339 "Don't know how to handle modifier on immediate operand");
2340 return;
2341
2342 case MachineOperand::MO_FPImmediate:
2343 printFPConstant(MO.getFPImm(), O);
2344 break;
2345
2346 case MachineOperand::MO_GlobalAddress:
Matt Arsenault8b643552015-06-09 00:31:39 +00002347 getSymbol(MO.getGlobal())->print(O, MAI);
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002348 break;
2349
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002350 case MachineOperand::MO_MachineBasicBlock:
Matt Arsenault8b643552015-06-09 00:31:39 +00002351 MO.getMBB()->getSymbol()->print(O, MAI);
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002352 return;
2353
2354 default:
2355 llvm_unreachable("Operand type not supported.");
2356 }
2357}
2358
2359void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2360 raw_ostream &O, const char *Modifier) {
2361 printOperand(MI, opNum, O);
2362
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00002363 if (Modifier && strcmp(Modifier, "add") == 0) {
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002364 O << ", ";
2365 printOperand(MI, opNum + 1, O);
2366 } else {
2367 if (MI->getOperand(opNum + 1).isImm() &&
2368 MI->getOperand(opNum + 1).getImm() == 0)
2369 return; // don't print ',0' or '+0'
2370 O << "+";
2371 printOperand(MI, opNum + 1, O);
2372 }
2373}
2374
Justin Holewinskiae556d32012-05-04 20:18:50 +00002375void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2376 std::stringstream temp;
Yaron Keren075759a2015-03-30 15:42:36 +00002377 LineReader *reader = this->getReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002378 temp << "\n//";
2379 temp << filename.str();
2380 temp << ":";
2381 temp << line;
2382 temp << " ";
2383 temp << reader->readLine(line);
2384 temp << "\n";
Lang Hames9ff69c82015-04-24 19:11:51 +00002385 this->OutStreamer->EmitRawText(temp.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +00002386}
2387
Benjamin Kramerc321e532016-06-08 19:09:22 +00002388LineReader *NVPTXAsmPrinter::getReader(const std::string &filename) {
Craig Topper062a2ba2014-04-25 05:30:21 +00002389 if (!reader) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002390 reader = new LineReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002391 }
2392
2393 if (reader->fileName() != filename) {
2394 delete reader;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002395 reader = new LineReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002396 }
2397
2398 return reader;
2399}
2400
Justin Holewinski0497ab12013-03-30 14:29:21 +00002401std::string LineReader::readLine(unsigned lineNum) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00002402 if (lineNum < theCurLine) {
2403 theCurLine = 0;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002404 fstr.seekg(0, std::ios::beg);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002405 }
2406 while (theCurLine < lineNum) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002407 fstr.getline(buff, 500);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002408 theCurLine++;
2409 }
2410 return buff;
2411}
2412
2413// Force static initialization.
2414extern "C" void LLVMInitializeNVPTXAsmPrinter() {
Mehdi Aminif42454b2016-10-09 23:00:34 +00002415 RegisterAsmPrinter<NVPTXAsmPrinter> X(getTheNVPTXTarget32());
2416 RegisterAsmPrinter<NVPTXAsmPrinter> Y(getTheNVPTXTarget64());
Justin Holewinskiae556d32012-05-04 20:18:50 +00002417}