blob: d0b47f61e114d37349535dee0b1cd81104a7b985 [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 Carruth6bda14b2017-06-06 11:49:48 +000015#include "NVPTXAsmPrinter.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000016#include "InstPrinter/NVPTXInstPrinter.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000017#include "MCTargetDesc/NVPTXBaseInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "MCTargetDesc/NVPTXMCAsmInfo.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000019#include "NVPTX.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"
David Blaikieb3bde2e2017-11-17 01:07:10 +000048#include "llvm/CodeGen/TargetLowering.h"
49#include "llvm/CodeGen/TargetLoweringObjectFile.h"
50#include "llvm/CodeGen/TargetRegisterInfo.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000051#include "llvm/CodeGen/ValueTypes.h"
52#include "llvm/IR/Attributes.h"
53#include "llvm/IR/BasicBlock.h"
54#include "llvm/IR/Constant.h"
55#include "llvm/IR/Constants.h"
56#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000057#include "llvm/IR/DebugInfo.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000058#include "llvm/IR/DebugInfoMetadata.h"
59#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000060#include "llvm/IR/DerivedTypes.h"
61#include "llvm/IR/Function.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000062#include "llvm/IR/GlobalValue.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000063#include "llvm/IR/GlobalVariable.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000064#include "llvm/IR/Instruction.h"
65#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000066#include "llvm/IR/Module.h"
67#include "llvm/IR/Operator.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000068#include "llvm/IR/Type.h"
69#include "llvm/IR/User.h"
70#include "llvm/MC/MCExpr.h"
Pete Cooper81902a32015-05-15 22:19:42 +000071#include "llvm/MC/MCInst.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000072#include "llvm/MC/MCInstrDesc.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000073#include "llvm/MC/MCStreamer.h"
74#include "llvm/MC/MCSymbol.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000075#include "llvm/Support/Casting.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000076#include "llvm/Support/CommandLine.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000077#include "llvm/Support/ErrorHandling.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000078#include "llvm/Support/Path.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000079#include "llvm/Support/TargetRegistry.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000080#include "llvm/Support/raw_ostream.h"
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +000081#include "llvm/Target/TargetMachine.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;
Artem Belevich64dc9be2017-01-13 20:56:17 +0000323 case Type::HalfTyID:
324 MCOp = MCOperand::createExpr(
325 NVPTXFloatMCExpr::createConstantFPHalf(Val, OutContext));
326 break;
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000327 case Type::FloatTyID:
Jim Grosbache9119e42015-05-13 18:37:00 +0000328 MCOp = MCOperand::createExpr(
Jim Grosbach13760bd2015-05-30 01:25:56 +0000329 NVPTXFloatMCExpr::createConstantFPSingle(Val, OutContext));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000330 break;
331 case Type::DoubleTyID:
Jim Grosbache9119e42015-05-13 18:37:00 +0000332 MCOp = MCOperand::createExpr(
Jim Grosbach13760bd2015-05-30 01:25:56 +0000333 NVPTXFloatMCExpr::createConstantFPDouble(Val, OutContext));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000334 break;
335 }
336 break;
337 }
338 }
339 return true;
340}
341
342unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
Justin Holewinski871ec932013-08-06 14:13:31 +0000343 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
344 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000345
Justin Holewinski871ec932013-08-06 14:13:31 +0000346 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
347 unsigned RegNum = RegMap[Reg];
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000348
Justin Holewinski871ec932013-08-06 14:13:31 +0000349 // Encode the register class in the upper 4 bits
350 // Must be kept in sync with NVPTXInstPrinter::printRegName
351 unsigned Ret = 0;
352 if (RC == &NVPTX::Int1RegsRegClass) {
353 Ret = (1 << 28);
354 } else if (RC == &NVPTX::Int16RegsRegClass) {
355 Ret = (2 << 28);
356 } else if (RC == &NVPTX::Int32RegsRegClass) {
357 Ret = (3 << 28);
358 } else if (RC == &NVPTX::Int64RegsRegClass) {
359 Ret = (4 << 28);
360 } else if (RC == &NVPTX::Float32RegsRegClass) {
361 Ret = (5 << 28);
362 } else if (RC == &NVPTX::Float64RegsRegClass) {
363 Ret = (6 << 28);
Artem Belevich64dc9be2017-01-13 20:56:17 +0000364 } else if (RC == &NVPTX::Float16RegsRegClass) {
365 Ret = (7 << 28);
Artem Belevich620db1f2017-02-23 22:38:24 +0000366 } else if (RC == &NVPTX::Float16x2RegsRegClass) {
367 Ret = (8 << 28);
Justin Holewinski871ec932013-08-06 14:13:31 +0000368 } else {
369 report_fatal_error("Bad register class");
370 }
371
372 // Insert the vreg number
373 Ret |= (RegNum & 0x0FFFFFFF);
374 return Ret;
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000375 } else {
Justin Holewinski871ec932013-08-06 14:13:31 +0000376 // Some special-use registers are actually physical registers.
377 // Encode this as the register class ID of 0 and the real register ID.
378 return Reg & 0x0FFFFFFF;
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000379 }
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000380}
381
Justin Holewinski30d56a72014-04-09 15:39:15 +0000382MCOperand NVPTXAsmPrinter::GetSymbolRef(const MCSymbol *Symbol) {
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000383 const MCExpr *Expr;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000384 Expr = MCSymbolRefExpr::create(Symbol, MCSymbolRefExpr::VK_None,
Justin Holewinski8b24e1e2013-08-06 23:06:42 +0000385 OutContext);
Jim Grosbache9119e42015-05-13 18:37:00 +0000386 return MCOperand::createExpr(Expr);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000387}
388
Justin Holewinski0497ab12013-03-30 14:29:21 +0000389void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
Mehdi Amini56228da2015-07-09 01:57:34 +0000390 const DataLayout &DL = getDataLayout();
Eric Christopher6aad8b12015-02-19 00:08:14 +0000391 const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000392
393 Type *Ty = F->getReturnType();
394
Eric Christopher6aad8b12015-02-19 00:08:14 +0000395 bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000396
397 if (Ty->getTypeID() == Type::VoidTyID)
398 return;
399
400 O << " (";
401
402 if (isABI) {
Artem Belevichd7a73822017-07-20 21:16:03 +0000403 if (Ty->isFloatingPointTy() || (Ty->isIntegerTy() && !Ty->isIntegerTy(128))) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000404 unsigned size = 0;
Craig Toppere3dcce92015-08-01 22:20:21 +0000405 if (auto *ITy = dyn_cast<IntegerType>(Ty)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000406 size = ITy->getBitWidth();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000407 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +0000408 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000409 size = Ty->getPrimitiveSizeInBits();
410 }
Artem Belevich64dc9be2017-01-13 20:56:17 +0000411 // PTX ABI requires all scalar return values to be at least 32
412 // bits in size. fp16 normally uses .b16 as its storage type in
413 // PTX, so its size must be adjusted here, too.
414 if (size < 32)
415 size = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000416
417 O << ".param .b" << size << " func_retval0";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000418 } else if (isa<PointerType>(Ty)) {
Mehdi Amini44ede332015-07-09 02:09:04 +0000419 O << ".param .b" << TLI->getPointerTy(DL).getSizeInBits()
Justin Holewinski0497ab12013-03-30 14:29:21 +0000420 << " func_retval0";
Artem Belevichd7a73822017-07-20 21:16:03 +0000421 } else if (Ty->isAggregateType() || Ty->isVectorTy() || Ty->isIntegerTy(128)) {
Mehdi Amini56228da2015-07-09 01:57:34 +0000422 unsigned totalsz = DL.getTypeAllocSize(Ty);
Artem Belevich74158b52016-07-20 18:39:52 +0000423 unsigned retAlignment = 0;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000424 if (!getAlign(*F, 0, retAlignment))
Artem Belevich74158b52016-07-20 18:39:52 +0000425 retAlignment = DL.getABITypeAlignment(Ty);
426 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
427 << "]";
Craig Topperd3c02f12015-01-05 10:15:49 +0000428 } else
429 llvm_unreachable("Unknown return type");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000430 } else {
431 SmallVector<EVT, 16> vtparts;
Mehdi Amini56228da2015-07-09 01:57:34 +0000432 ComputeValueVTs(*TLI, DL, Ty, vtparts);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000433 unsigned idx = 0;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000434 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000435 unsigned elems = 1;
436 EVT elemtype = vtparts[i];
437 if (vtparts[i].isVector()) {
438 elems = vtparts[i].getVectorNumElements();
439 elemtype = vtparts[i].getVectorElementType();
440 }
441
Justin Holewinski0497ab12013-03-30 14:29:21 +0000442 for (unsigned j = 0, je = elems; j != je; ++j) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000443 unsigned sz = elemtype.getSizeInBits();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000444 if (elemtype.isInteger() && (sz < 32))
445 sz = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000446 O << ".reg .b" << sz << " func_retval" << idx;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000447 if (j < je - 1)
448 O << ", ";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000449 ++idx;
450 }
Justin Holewinski0497ab12013-03-30 14:29:21 +0000451 if (i < e - 1)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000452 O << ", ";
453 }
454 }
455 O << ") ";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000456}
457
458void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
459 raw_ostream &O) {
460 const Function *F = MF.getFunction();
461 printReturnValStr(F, O);
462}
463
Jingyue Wu0220df02015-02-01 02:27:45 +0000464// Return true if MBB is the header of a loop marked with
465// llvm.loop.unroll.disable.
Jingyue Wu5bbcdaa2015-02-03 17:57:38 +0000466// TODO: consider "#pragma unroll 1" which is equivalent to "#pragma nounroll".
Jingyue Wu0220df02015-02-01 02:27:45 +0000467bool NVPTXAsmPrinter::isLoopHeaderOfNoUnroll(
468 const MachineBasicBlock &MBB) const {
469 MachineLoopInfo &LI = getAnalysis<MachineLoopInfo>();
Jingyue Wu0220df02015-02-01 02:27:45 +0000470 // We insert .pragma "nounroll" only to the loop header.
Benjamin Kramerdb220db2015-06-02 15:28:27 +0000471 if (!LI.isLoopHeader(&MBB))
Jingyue Wu0220df02015-02-01 02:27:45 +0000472 return false;
473
474 // llvm.loop.unroll.disable is marked on the back edges of a loop. Therefore,
475 // we iterate through each back edge of the loop with header MBB, and check
476 // whether its metadata contains llvm.loop.unroll.disable.
477 for (auto I = MBB.pred_begin(); I != MBB.pred_end(); ++I) {
478 const MachineBasicBlock *PMBB = *I;
479 if (LI.getLoopFor(PMBB) != LI.getLoopFor(&MBB)) {
480 // Edges from other loops to MBB are not back edges.
481 continue;
482 }
483 if (const BasicBlock *PBB = PMBB->getBasicBlock()) {
Duncan P. N. Exon Smith1d15a9f2016-03-25 00:35:38 +0000484 if (MDNode *LoopID =
485 PBB->getTerminator()->getMetadata(LLVMContext::MD_loop)) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000486 if (GetUnrollMetadata(LoopID, "llvm.loop.unroll.disable"))
487 return true;
488 }
489 }
490 }
491 return false;
492}
493
494void NVPTXAsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
495 AsmPrinter::EmitBasicBlockStart(MBB);
496 if (isLoopHeaderOfNoUnroll(MBB))
Lang Hames9ff69c82015-04-24 19:11:51 +0000497 OutStreamer->EmitRawText(StringRef("\t.pragma \"nounroll\";\n"));
Jingyue Wu0220df02015-02-01 02:27:45 +0000498}
499
Justin Holewinskiae556d32012-05-04 20:18:50 +0000500void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
501 SmallString<128> Str;
502 raw_svector_ostream O(Str);
503
Justin Holewinski01f89f02013-05-20 12:13:32 +0000504 if (!GlobalsEmitted) {
505 emitGlobals(*MF->getFunction()->getParent());
506 GlobalsEmitted = true;
507 }
508
Justin Holewinskiae556d32012-05-04 20:18:50 +0000509 // Set up
510 MRI = &MF->getRegInfo();
511 F = MF->getFunction();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000512 emitLinkageDirective(F, O);
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000513 if (isKernelFunction(*F))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000514 O << ".entry ";
515 else {
516 O << ".func ";
517 printReturnValStr(*MF, O);
518 }
519
Matt Arsenault8b643552015-06-09 00:31:39 +0000520 CurrentFnSym->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000521
522 emitFunctionParamList(*MF, O);
523
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000524 if (isKernelFunction(*F))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000525 emitKernelFunctionDirectives(*F, O);
526
Lang Hames9ff69c82015-04-24 19:11:51 +0000527 OutStreamer->EmitRawText(O.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000528
529 prevDebugLoc = DebugLoc();
530}
531
532void NVPTXAsmPrinter::EmitFunctionBodyStart() {
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +0000533 VRegMapping.clear();
Lang Hames9ff69c82015-04-24 19:11:51 +0000534 OutStreamer->EmitRawText(StringRef("{\n"));
Justin Holewinskiae556d32012-05-04 20:18:50 +0000535 setAndEmitFunctionVirtualRegisters(*MF);
536
537 SmallString<128> Str;
538 raw_svector_ostream O(Str);
539 emitDemotedVars(MF->getFunction(), O);
Lang Hames9ff69c82015-04-24 19:11:51 +0000540 OutStreamer->EmitRawText(O.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000541}
542
543void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
Lang Hames9ff69c82015-04-24 19:11:51 +0000544 OutStreamer->EmitRawText(StringRef("}\n"));
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +0000545 VRegMapping.clear();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000546}
547
Justin Holewinski660597d2013-10-11 12:39:36 +0000548void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
549 unsigned RegNo = MI->getOperand(0).getReg();
Andrew Kaylor5c73e1f2015-03-24 23:37:10 +0000550 if (TargetRegisterInfo::isVirtualRegister(RegNo)) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000551 OutStreamer->AddComment(Twine("implicit-def: ") +
552 getVirtualRegisterName(RegNo));
Justin Holewinski660597d2013-10-11 12:39:36 +0000553 } else {
Lang Hames9ff69c82015-04-24 19:11:51 +0000554 OutStreamer->AddComment(Twine("implicit-def: ") +
555 nvptxSubtarget->getRegisterInfo()->getName(RegNo));
Justin Holewinski660597d2013-10-11 12:39:36 +0000556 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000557 OutStreamer->AddBlankLine();
Justin Holewinski660597d2013-10-11 12:39:36 +0000558}
559
Justin Holewinski0497ab12013-03-30 14:29:21 +0000560void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
561 raw_ostream &O) const {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000562 // If the NVVM IR has some of reqntid* specified, then output
563 // the reqntid directive, and set the unspecified ones to 1.
564 // If none of reqntid* is specified, don't output reqntid directive.
565 unsigned reqntidx, reqntidy, reqntidz;
566 bool specified = false;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000567 if (!getReqNTIDx(F, reqntidx))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000568 reqntidx = 1;
569 else
570 specified = true;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000571 if (!getReqNTIDy(F, reqntidy))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000572 reqntidy = 1;
573 else
574 specified = true;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000575 if (!getReqNTIDz(F, reqntidz))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000576 reqntidz = 1;
577 else
578 specified = true;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000579
580 if (specified)
Justin Holewinski0497ab12013-03-30 14:29:21 +0000581 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
582 << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000583
584 // If the NVVM IR has some of maxntid* specified, then output
585 // the maxntid directive, and set the unspecified ones to 1.
586 // If none of maxntid* is specified, don't output maxntid directive.
587 unsigned maxntidx, maxntidy, maxntidz;
588 specified = false;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000589 if (!getMaxNTIDx(F, maxntidx))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000590 maxntidx = 1;
591 else
592 specified = true;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000593 if (!getMaxNTIDy(F, maxntidy))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000594 maxntidy = 1;
595 else
596 specified = true;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000597 if (!getMaxNTIDz(F, maxntidz))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000598 maxntidz = 1;
599 else
600 specified = true;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000601
602 if (specified)
Justin Holewinski0497ab12013-03-30 14:29:21 +0000603 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
604 << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000605
606 unsigned mincta;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000607 if (getMinCTASm(F, mincta))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000608 O << ".minnctapersm " << mincta << "\n";
Justin Lebar19bf9d22016-12-14 22:32:50 +0000609
610 unsigned maxnreg;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000611 if (getMaxNReg(F, maxnreg))
Justin Lebar19bf9d22016-12-14 22:32:50 +0000612 O << ".maxnreg " << maxnreg << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000613}
614
Justin Holewinski660597d2013-10-11 12:39:36 +0000615std::string
616NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
617 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000618
Justin Holewinski660597d2013-10-11 12:39:36 +0000619 std::string Name;
620 raw_string_ostream NameStr(Name);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000621
Justin Holewinski660597d2013-10-11 12:39:36 +0000622 VRegRCMap::const_iterator I = VRegMapping.find(RC);
623 assert(I != VRegMapping.end() && "Bad register class");
624 const DenseMap<unsigned, unsigned> &RegMap = I->second;
625
626 VRegMap::const_iterator VI = RegMap.find(Reg);
627 assert(VI != RegMap.end() && "Bad virtual register");
628 unsigned MappedVR = VI->second;
629
630 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
631
632 NameStr.flush();
633 return Name;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000634}
635
Justin Holewinski660597d2013-10-11 12:39:36 +0000636void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
Justin Holewinski0497ab12013-03-30 14:29:21 +0000637 raw_ostream &O) {
Justin Holewinski660597d2013-10-11 12:39:36 +0000638 O << getVirtualRegisterName(vr);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000639}
640
Justin Holewinski0497ab12013-03-30 14:29:21 +0000641void NVPTXAsmPrinter::printVecModifiedImmediate(
642 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
643 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
644 int Imm = (int) MO.getImm();
645 if (0 == strcmp(Modifier, "vecelem"))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000646 O << "_" << vecelem[Imm];
Justin Holewinski0497ab12013-03-30 14:29:21 +0000647 else if (0 == strcmp(Modifier, "vecv4comm1")) {
648 if ((Imm < 0) || (Imm > 3))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000649 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000650 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
651 if ((Imm < 4) || (Imm > 7))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000652 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000653 } else if (0 == strcmp(Modifier, "vecv4pos")) {
654 if (Imm < 0)
655 Imm = 0;
656 O << "_" << vecelem[Imm % 4];
657 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
658 if ((Imm < 0) || (Imm > 1))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000659 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000660 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
661 if ((Imm < 2) || (Imm > 3))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000662 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000663 } else if (0 == strcmp(Modifier, "vecv2pos")) {
664 if (Imm < 0)
665 Imm = 0;
666 O << "_" << vecelem[Imm % 2];
667 } else
Craig Topperbdf39a42012-05-24 07:02:50 +0000668 llvm_unreachable("Unknown Modifier on immediate operand");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000669}
670
Justin Holewinski0497ab12013-03-30 14:29:21 +0000671void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
Justin Holewinski0497ab12013-03-30 14:29:21 +0000672 emitLinkageDirective(F, O);
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000673 if (isKernelFunction(*F))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000674 O << ".entry ";
675 else
676 O << ".func ";
677 printReturnValStr(F, O);
Matt Arsenault8b643552015-06-09 00:31:39 +0000678 getSymbol(F)->print(O, MAI);
679 O << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000680 emitFunctionParamList(F, O);
681 O << ";\n";
682}
683
Justin Holewinski0497ab12013-03-30 14:29:21 +0000684static bool usedInGlobalVarDef(const Constant *C) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000685 if (!C)
686 return false;
687
688 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
Jingyue Wu4be014a2015-07-31 05:09:47 +0000689 return GV->getName() != "llvm.used";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000690 }
691
Chandler Carruthcdf47882014-03-09 03:16:01 +0000692 for (const User *U : C->users())
693 if (const Constant *C = dyn_cast<Constant>(U))
694 if (usedInGlobalVarDef(C))
695 return true;
696
Justin Holewinskiae556d32012-05-04 20:18:50 +0000697 return false;
698}
699
Justin Holewinski0497ab12013-03-30 14:29:21 +0000700static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000701 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
Yaron Keren075759a2015-03-30 15:42:36 +0000702 if (othergv->getName() == "llvm.used")
Justin Holewinskiae556d32012-05-04 20:18:50 +0000703 return true;
704 }
705
706 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
707 if (instr->getParent() && instr->getParent()->getParent()) {
708 const Function *curFunc = instr->getParent()->getParent();
709 if (oneFunc && (curFunc != oneFunc))
710 return false;
711 oneFunc = curFunc;
712 return true;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000713 } else
Justin Holewinskiae556d32012-05-04 20:18:50 +0000714 return false;
715 }
716
Chandler Carruthcdf47882014-03-09 03:16:01 +0000717 for (const User *UU : U->users())
Eli Bendersky3e840192015-03-23 16:26:23 +0000718 if (!usedInOneFunc(UU, oneFunc))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000719 return false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000720
Justin Holewinskiae556d32012-05-04 20:18:50 +0000721 return true;
722}
723
724/* Find out if a global variable can be demoted to local scope.
725 * Currently, this is valid for CUDA shared variables, which have local
726 * scope and global lifetime. So the conditions to check are :
727 * 1. Is the global variable in shared address space?
728 * 2. Does it have internal linkage?
729 * 3. Is the global variable referenced only in one function?
730 */
731static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
Eli Bendersky3e840192015-03-23 16:26:23 +0000732 if (!gv->hasInternalLinkage())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000733 return false;
Craig Toppere3dcce92015-08-01 22:20:21 +0000734 PointerType *Pty = gv->getType();
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000735 if (Pty->getAddressSpace() != ADDRESS_SPACE_SHARED)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000736 return false;
737
Craig Topper062a2ba2014-04-25 05:30:21 +0000738 const Function *oneFunc = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000739
740 bool flag = usedInOneFunc(gv, oneFunc);
Eli Bendersky3e840192015-03-23 16:26:23 +0000741 if (!flag)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000742 return false;
743 if (!oneFunc)
744 return false;
745 f = oneFunc;
746 return true;
747}
748
749static bool useFuncSeen(const Constant *C,
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000750 DenseMap<const Function *, bool> &seenMap) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000751 for (const User *U : C->users()) {
752 if (const Constant *cu = dyn_cast<Constant>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000753 if (useFuncSeen(cu, seenMap))
754 return true;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000755 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000756 const BasicBlock *bb = I->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000757 if (!bb)
758 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000759 const Function *caller = bb->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000760 if (!caller)
761 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000762 if (seenMap.find(caller) != seenMap.end())
763 return true;
764 }
765 }
766 return false;
767}
768
Justin Holewinski01f89f02013-05-20 12:13:32 +0000769void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +0000770 DenseMap<const Function *, bool> seenMap;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000771 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
Duncan P. N. Exon Smith61149b82015-10-20 00:54:09 +0000772 const Function *F = &*FI;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000773
774 if (F->isDeclaration()) {
775 if (F->use_empty())
776 continue;
777 if (F->getIntrinsicID())
778 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000779 emitDeclaration(F, O);
780 continue;
781 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000782 for (const User *U : F->users()) {
783 if (const Constant *C = dyn_cast<Constant>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000784 if (usedInGlobalVarDef(C)) {
785 // The use is in the initialization of a global variable
786 // that is a function pointer, so print a declaration
787 // for the original function
Justin Holewinskiae556d32012-05-04 20:18:50 +0000788 emitDeclaration(F, O);
789 break;
790 }
791 // Emit a declaration of this function if the function that
792 // uses this constant expr has already been seen.
793 if (useFuncSeen(C, seenMap)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000794 emitDeclaration(F, O);
795 break;
796 }
797 }
798
Chandler Carruthcdf47882014-03-09 03:16:01 +0000799 if (!isa<Instruction>(U))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000800 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000801 const Instruction *instr = cast<Instruction>(U);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000802 const BasicBlock *bb = instr->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000803 if (!bb)
804 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000805 const Function *caller = bb->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000806 if (!caller)
807 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000808
809 // If a caller has already been seen, then the caller is
810 // appearing in the module before the callee. so print out
811 // a declaration for the callee.
812 if (seenMap.find(caller) != seenMap.end()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000813 emitDeclaration(F, O);
814 break;
815 }
816 }
817 seenMap[F] = true;
818 }
819}
820
821void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
822 DebugInfoFinder DbgFinder;
823 DbgFinder.processModule(M);
824
Justin Holewinski0497ab12013-03-30 14:29:21 +0000825 unsigned i = 1;
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000826 for (const DICompileUnit *DIUnit : DbgFinder.compile_units()) {
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +0000827 StringRef Filename = DIUnit->getFilename();
828 StringRef Dirname = DIUnit->getDirectory();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000829 SmallString<128> FullPathName = Dirname;
830 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
831 sys::path::append(FullPathName, Filename);
Yaron Keren075759a2015-03-30 15:42:36 +0000832 Filename = FullPathName;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000833 }
Yaron Keren075759a2015-03-30 15:42:36 +0000834 if (filenameMap.find(Filename) != filenameMap.end())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000835 continue;
Yaron Keren075759a2015-03-30 15:42:36 +0000836 filenameMap[Filename] = i;
Lang Hames9ff69c82015-04-24 19:11:51 +0000837 OutStreamer->EmitDwarfFileDirective(i, "", Filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000838 ++i;
839 }
840
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000841 for (DISubprogram *SP : DbgFinder.subprograms()) {
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000842 StringRef Filename = SP->getFilename();
843 StringRef Dirname = SP->getDirectory();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000844 SmallString<128> FullPathName = Dirname;
845 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
846 sys::path::append(FullPathName, Filename);
Yaron Keren075759a2015-03-30 15:42:36 +0000847 Filename = FullPathName;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000848 }
Yaron Keren075759a2015-03-30 15:42:36 +0000849 if (filenameMap.find(Filename) != filenameMap.end())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000850 continue;
Yaron Keren075759a2015-03-30 15:42:36 +0000851 filenameMap[Filename] = i;
Artem Belevicha8455f22016-02-11 18:21:47 +0000852 OutStreamer->EmitDwarfFileDirective(i, "", Filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000853 ++i;
854 }
855}
856
Justin Lebaread59f42016-01-30 01:07:38 +0000857static bool isEmptyXXStructor(GlobalVariable *GV) {
858 if (!GV) return true;
859 const ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
860 if (!InitList) return true; // Not an array; we don't know how to parse.
861 return InitList->getNumOperands() == 0;
862}
863
Justin Holewinski0497ab12013-03-30 14:29:21 +0000864bool NVPTXAsmPrinter::doInitialization(Module &M) {
Eric Christopher6aad8b12015-02-19 00:08:14 +0000865 // Construct a default subtarget off of the TargetMachine defaults. The
866 // rest of NVPTX isn't friendly to change subtargets per function and
867 // so the default TargetMachine will have all of the options.
Daniel Sandersc81f4502015-06-16 15:44:21 +0000868 const Triple &TT = TM.getTargetTriple();
Eric Christopher6aad8b12015-02-19 00:08:14 +0000869 StringRef CPU = TM.getTargetCPU();
870 StringRef FS = TM.getTargetFeatureString();
871 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
Eric Christopher02389e32015-02-19 00:08:27 +0000872 const NVPTXSubtarget STI(TT, CPU, FS, NTM);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000873
Justin Lebar3a5f5792016-01-23 21:12:20 +0000874 if (M.alias_size()) {
875 report_fatal_error("Module has aliases, which NVPTX does not support.");
876 return true; // error
877 }
Justin Lebaread59f42016-01-30 01:07:38 +0000878 if (!isEmptyXXStructor(M.getNamedGlobal("llvm.global_ctors"))) {
879 report_fatal_error(
880 "Module has a nontrivial global ctor, which NVPTX does not support.");
881 return true; // error
882 }
883 if (!isEmptyXXStructor(M.getNamedGlobal("llvm.global_dtors"))) {
884 report_fatal_error(
885 "Module has a nontrivial global dtor, which NVPTX does not support.");
886 return true; // error
887 }
Justin Lebar3a5f5792016-01-23 21:12:20 +0000888
Justin Holewinskiae556d32012-05-04 20:18:50 +0000889 SmallString<128> Str1;
890 raw_svector_ostream OS1(Str1);
891
892 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000893
894 // We need to call the parent's one explicitly.
895 //bool Result = AsmPrinter::doInitialization(M);
896
Eric Christopherb4b75a52016-09-29 02:03:47 +0000897 // Initialize TargetLoweringObjectFile since we didn't do in
898 // AsmPrinter::doInitialization either right above or where it's commented out
899 // below.
Justin Holewinski0497ab12013-03-30 14:29:21 +0000900 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
901 .Initialize(OutContext, TM);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000902
Justin Holewinskiae556d32012-05-04 20:18:50 +0000903 // Emit header before any dwarf directives are emitted below.
Eric Christopher6aad8b12015-02-19 00:08:14 +0000904 emitHeader(M, OS1, STI);
Lang Hames9ff69c82015-04-24 19:11:51 +0000905 OutStreamer->EmitRawText(OS1.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000906
Justin Holewinskiae556d32012-05-04 20:18:50 +0000907 // Already commented out
908 //bool Result = AsmPrinter::doInitialization(M);
909
Justin Holewinskid2bbdf02013-07-01 13:00:14 +0000910 // Emit module-level inline asm if it exists.
911 if (!M.getModuleInlineAsm().empty()) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000912 OutStreamer->AddComment("Start of file scope inline assembly");
913 OutStreamer->AddBlankLine();
914 OutStreamer->EmitRawText(StringRef(M.getModuleInlineAsm()));
915 OutStreamer->AddBlankLine();
916 OutStreamer->AddComment("End of file scope inline assembly");
917 OutStreamer->AddBlankLine();
Justin Holewinskid2bbdf02013-07-01 13:00:14 +0000918 }
919
Eric Christopher6aad8b12015-02-19 00:08:14 +0000920 // If we're not NVCL we're CUDA, go ahead and emit filenames.
Daniel Sandersc81f4502015-06-16 15:44:21 +0000921 if (TM.getTargetTriple().getOS() != Triple::NVCL)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000922 recordAndEmitFilenames(M);
923
Justin Holewinski01f89f02013-05-20 12:13:32 +0000924 GlobalsEmitted = false;
925
926 return false; // success
927}
928
929void NVPTXAsmPrinter::emitGlobals(const Module &M) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000930 SmallString<128> Str2;
931 raw_svector_ostream OS2(Str2);
932
933 emitDeclarations(M, OS2);
934
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000935 // As ptxas does not support forward references of globals, we need to first
936 // sort the list of module-level globals in def-use order. We visit each
937 // global variable in order, and ensure that we emit it *after* its dependent
938 // globals. We use a little extra memory maintaining both a set and a list to
939 // have fast searches while maintaining a strict ordering.
Justin Holewinski01f89f02013-05-20 12:13:32 +0000940 SmallVector<const GlobalVariable *, 8> Globals;
941 DenseSet<const GlobalVariable *> GVVisited;
942 DenseSet<const GlobalVariable *> GVVisiting;
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000943
944 // Visit each global variable, in order
Duncan P. N. Exon Smith61149b82015-10-20 00:54:09 +0000945 for (const GlobalVariable &I : M.globals())
946 VisitGlobalVariableForEmission(&I, Globals, GVVisited, GVVisiting);
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000947
Justin Holewinski0497ab12013-03-30 14:29:21 +0000948 assert(GVVisited.size() == M.getGlobalList().size() &&
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000949 "Missed a global variable");
950 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
951
952 // Print out module-level global variables in proper order
953 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
954 printModuleLevelGV(Globals[i], OS2);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000955
956 OS2 << '\n';
957
Lang Hames9ff69c82015-04-24 19:11:51 +0000958 OutStreamer->EmitRawText(OS2.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000959}
960
Eric Christopher6aad8b12015-02-19 00:08:14 +0000961void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O,
962 const NVPTXSubtarget &STI) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000963 O << "//\n";
964 O << "// Generated by LLVM NVPTX Back-End\n";
965 O << "//\n";
966 O << "\n";
967
Eric Christopher6aad8b12015-02-19 00:08:14 +0000968 unsigned PTXVersion = STI.getPTXVersion();
Justin Holewinski1812ee92012-11-12 03:16:43 +0000969 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000970
971 O << ".target ";
Eric Christopher6aad8b12015-02-19 00:08:14 +0000972 O << STI.getTargetName();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000973
Eric Christopherca929f22015-02-19 00:22:47 +0000974 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
975 if (NTM.getDrvInterface() == NVPTX::NVCL)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000976 O << ", texmode_independent";
Eric Christopherbeffc4e2015-02-19 00:08:23 +0000977 else {
Eric Christopher6aad8b12015-02-19 00:08:14 +0000978 if (!STI.hasDouble())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000979 O << ", map_f64_to_f32";
980 }
981
982 if (MAI->doesSupportDebugInformation())
983 O << ", debug";
984
985 O << "\n";
986
987 O << ".address_size ";
Eric Christopherca929f22015-02-19 00:22:47 +0000988 if (NTM.is64Bit())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000989 O << "64";
990 else
991 O << "32";
992 O << "\n";
993
994 O << "\n";
995}
996
997bool NVPTXAsmPrinter::doFinalization(Module &M) {
Justin Holewinski01f89f02013-05-20 12:13:32 +0000998 // If we did not emit any functions, then the global declarations have not
999 // yet been emitted.
1000 if (!GlobalsEmitted) {
1001 emitGlobals(M);
1002 GlobalsEmitted = true;
1003 }
1004
Justin Holewinskiae556d32012-05-04 20:18:50 +00001005 // XXX Temproarily remove global variables so that doFinalization() will not
1006 // emit them again (global variables are emitted at beginning).
1007
1008 Module::GlobalListType &global_list = M.getGlobalList();
1009 int i, n = global_list.size();
Dylan Noblesmithc9e2a272014-08-26 02:03:35 +00001010 GlobalVariable **gv_array = new GlobalVariable *[n];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001011
1012 // first, back-up GlobalVariable in gv_array
1013 i = 0;
1014 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001015 I != E; ++I)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001016 gv_array[i++] = &*I;
1017
1018 // second, empty global_list
1019 while (!global_list.empty())
1020 global_list.remove(global_list.begin());
1021
1022 // call doFinalization
1023 bool ret = AsmPrinter::doFinalization(M);
1024
1025 // now we restore global variables
Justin Holewinski0497ab12013-03-30 14:29:21 +00001026 for (i = 0; i < n; i++)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001027 global_list.insert(global_list.end(), gv_array[i]);
1028
Justin Holewinski59596952014-04-09 15:38:52 +00001029 clearAnnotationCache(&M);
Dylan Noblesmithc9e2a272014-08-26 02:03:35 +00001030
1031 delete[] gv_array;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001032 return ret;
1033
Justin Holewinskiae556d32012-05-04 20:18:50 +00001034 //bool Result = AsmPrinter::doFinalization(M);
1035 // Instead of calling the parents doFinalization, we may
1036 // clone parents doFinalization and customize here.
1037 // Currently, we if NVISA out the EmitGlobals() in
1038 // parent's doFinalization, which is too intrusive.
1039 //
1040 // Same for the doInitialization.
1041 //return Result;
1042}
1043
1044// This function emits appropriate linkage directives for
1045// functions and global variables.
1046//
1047// extern function declaration -> .extern
1048// extern function definition -> .visible
1049// external global variable with init -> .visible
1050// external without init -> .extern
1051// appending -> not allowed, assert.
Justin Holewinski7d5bf662014-06-27 18:35:10 +00001052// for any linkage other than
1053// internal, private, linker_private,
1054// linker_private_weak, linker_private_weak_def_auto,
1055// we emit -> .weak.
Justin Holewinskiae556d32012-05-04 20:18:50 +00001056
Justin Holewinski0497ab12013-03-30 14:29:21 +00001057void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1058 raw_ostream &O) {
Eric Christopherbeffc4e2015-02-19 00:08:23 +00001059 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001060 if (V->hasExternalLinkage()) {
1061 if (isa<GlobalVariable>(V)) {
1062 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1063 if (GVar) {
1064 if (GVar->hasInitializer())
1065 O << ".visible ";
1066 else
1067 O << ".extern ";
1068 }
1069 } else if (V->isDeclaration())
1070 O << ".extern ";
1071 else
1072 O << ".visible ";
1073 } else if (V->hasAppendingLinkage()) {
1074 std::string msg;
1075 msg.append("Error: ");
1076 msg.append("Symbol ");
1077 if (V->hasName())
Yaron Keren075759a2015-03-30 15:42:36 +00001078 msg.append(V->getName());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001079 msg.append("has unsupported appending linkage type");
1080 llvm_unreachable(msg.c_str());
Justin Holewinski7d5bf662014-06-27 18:35:10 +00001081 } else if (!V->hasInternalLinkage() &&
1082 !V->hasPrivateLinkage()) {
1083 O << ".weak ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001084 }
1085 }
1086}
1087
Justin Holewinski01f89f02013-05-20 12:13:32 +00001088void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1089 raw_ostream &O,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001090 bool processDemoted) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001091 // Skip meta data
1092 if (GVar->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001093 if (GVar->getSection() == "llvm.metadata")
Justin Holewinskiae556d32012-05-04 20:18:50 +00001094 return;
1095 }
1096
Justin Holewinski73cb5de2014-06-27 18:35:53 +00001097 // Skip LLVM intrinsic global variables
1098 if (GVar->getName().startswith("llvm.") ||
1099 GVar->getName().startswith("nvvm."))
1100 return;
1101
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001102 const DataLayout &DL = getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001103
1104 // GlobalVariables are always constant pointers themselves.
Craig Toppere3dcce92015-08-01 22:20:21 +00001105 PointerType *PTy = GVar->getType();
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001106 Type *ETy = GVar->getValueType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001107
1108 if (GVar->hasExternalLinkage()) {
1109 if (GVar->hasInitializer())
1110 O << ".visible ";
1111 else
1112 O << ".extern ";
Justin Holewinskid73767a2014-06-27 18:35:56 +00001113 } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1114 GVar->hasAvailableExternallyLinkage() ||
1115 GVar->hasCommonLinkage()) {
1116 O << ".weak ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001117 }
1118
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001119 if (isTexture(*GVar)) {
1120 O << ".global .texref " << getTextureName(*GVar) << ";\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001121 return;
1122 }
1123
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001124 if (isSurface(*GVar)) {
1125 O << ".global .surfref " << getSurfaceName(*GVar) << ";\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001126 return;
1127 }
1128
1129 if (GVar->isDeclaration()) {
1130 // (extern) declarations, no definition or initializer
1131 // Currently the only known declaration is for an automatic __local
1132 // (.shared) promoted to global.
1133 emitPTXGlobalVariable(GVar, O);
1134 O << ";\n";
1135 return;
1136 }
1137
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001138 if (isSampler(*GVar)) {
1139 O << ".global .samplerref " << getSamplerName(*GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001140
Craig Topper062a2ba2014-04-25 05:30:21 +00001141 const Constant *Initializer = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001142 if (GVar->hasInitializer())
1143 Initializer = GVar->getInitializer();
Craig Topper062a2ba2014-04-25 05:30:21 +00001144 const ConstantInt *CI = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001145 if (Initializer)
1146 CI = dyn_cast<ConstantInt>(Initializer);
1147 if (CI) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001148 unsigned sample = CI->getZExtValue();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001149
1150 O << " = { ";
1151
Justin Holewinski0497ab12013-03-30 14:29:21 +00001152 for (int i = 0,
1153 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1154 i < 3; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001155 O << "addr_mode_" << i << " = ";
1156 switch (addr) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001157 case 0:
1158 O << "wrap";
1159 break;
1160 case 1:
1161 O << "clamp_to_border";
1162 break;
1163 case 2:
1164 O << "clamp_to_edge";
1165 break;
1166 case 3:
1167 O << "wrap";
1168 break;
1169 case 4:
1170 O << "mirror";
1171 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001172 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001173 O << ", ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001174 }
1175 O << "filter_mode = ";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001176 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1177 case 0:
1178 O << "nearest";
1179 break;
1180 case 1:
1181 O << "linear";
1182 break;
1183 case 2:
Craig Topper2a30d782014-06-18 05:05:13 +00001184 llvm_unreachable("Anisotropic filtering is not supported");
Justin Holewinski0497ab12013-03-30 14:29:21 +00001185 default:
1186 O << "nearest";
1187 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001188 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001189 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001190 O << ", force_unnormalized_coords = 1";
1191 }
1192 O << " }";
1193 }
1194
1195 O << ";\n";
1196 return;
1197 }
1198
1199 if (GVar->hasPrivateLinkage()) {
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001200 if (strncmp(GVar->getName().data(), "unrollpragma", 12) == 0)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001201 return;
1202
1203 // FIXME - need better way (e.g. Metadata) to avoid generating this global
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001204 if (strncmp(GVar->getName().data(), "filename", 8) == 0)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001205 return;
1206 if (GVar->use_empty())
1207 return;
1208 }
1209
Craig Topper062a2ba2014-04-25 05:30:21 +00001210 const Function *demotedFunc = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001211 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
Yaron Keren075759a2015-03-30 15:42:36 +00001212 O << "// " << GVar->getName() << " has been demoted\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001213 if (localDecls.find(demotedFunc) != localDecls.end())
1214 localDecls[demotedFunc].push_back(GVar);
1215 else {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001216 std::vector<const GlobalVariable *> temp;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001217 temp.push_back(GVar);
1218 localDecls[demotedFunc] = temp;
1219 }
1220 return;
1221 }
1222
1223 O << ".";
1224 emitPTXAddressSpace(PTy->getAddressSpace(), O);
Justin Holewinski773ca402014-06-27 18:35:58 +00001225
1226 if (isManaged(*GVar)) {
1227 O << " .attribute(.managed)";
1228 }
1229
Justin Holewinskiae556d32012-05-04 20:18:50 +00001230 if (GVar->getAlignment() == 0)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001231 O << " .align " << (int)DL.getPrefTypeAlignment(ETy);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001232 else
1233 O << " .align " << GVar->getAlignment();
1234
Justin Lebar1cf6bf42017-01-18 00:29:53 +00001235 if (ETy->isFloatingPointTy() || ETy->isPointerTy() ||
1236 (ETy->isIntegerTy() && ETy->getScalarSizeInBits() <= 64)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001237 O << " .";
Justin Holewinski700b6fa2013-05-20 12:13:28 +00001238 // Special case: ABI requires that we use .u8 for predicates
1239 if (ETy->isIntegerTy(1))
1240 O << "u8";
1241 else
1242 O << getPTXFundamentalTypeStr(ETy, false);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001243 O << " ";
Matt Arsenault8b643552015-06-09 00:31:39 +00001244 getSymbol(GVar)->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001245
1246 // Ptx allows variable initilization only for constant and global state
1247 // spaces.
Justin Holewinski549c7732014-06-27 18:36:01 +00001248 if (GVar->hasInitializer()) {
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001249 if ((PTy->getAddressSpace() == ADDRESS_SPACE_GLOBAL) ||
1250 (PTy->getAddressSpace() == ADDRESS_SPACE_CONST)) {
Justin Holewinski549c7732014-06-27 18:36:01 +00001251 const Constant *Initializer = GVar->getInitializer();
Jingyue Wu312fd022015-04-24 02:57:30 +00001252 // 'undef' is treated as there is no value specified.
Justin Holewinski549c7732014-06-27 18:36:01 +00001253 if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1254 O << " = ";
1255 printScalarConstant(Initializer, O);
1256 }
1257 } else {
Jingyue Wufcec0982015-08-22 05:40:26 +00001258 // The frontend adds zero-initializer to device and constant variables
1259 // that don't have an initial value, and UndefValue to shared
1260 // variables, so skip warning for this case.
1261 if (!GVar->getInitializer()->isNullValue() &&
1262 !isa<UndefValue>(GVar->getInitializer())) {
Benjamin Kramerdba7ee92015-05-28 11:24:24 +00001263 report_fatal_error("initial value of '" + GVar->getName() +
1264 "' is not allowed in addrspace(" +
1265 Twine(PTy->getAddressSpace()) + ")");
Justin Holewinski549c7732014-06-27 18:36:01 +00001266 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001267 }
1268 }
1269 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001270 unsigned int ElementSize = 0;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001271
1272 // Although PTX has direct support for struct type and array type and
1273 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1274 // targets that support these high level field accesses. Structs, arrays
1275 // and vectors are lowered into arrays of bytes.
1276 switch (ETy->getTypeID()) {
Justin Lebar1cf6bf42017-01-18 00:29:53 +00001277 case Type::IntegerTyID: // Integers larger than 64 bits
Justin Holewinskiae556d32012-05-04 20:18:50 +00001278 case Type::StructTyID:
1279 case Type::ArrayTyID:
1280 case Type::VectorTyID:
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001281 ElementSize = DL.getTypeStoreSize(ETy);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001282 // Ptx allows variable initilization only for constant and
1283 // global state spaces.
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001284 if (((PTy->getAddressSpace() == ADDRESS_SPACE_GLOBAL) ||
1285 (PTy->getAddressSpace() == ADDRESS_SPACE_CONST)) &&
Justin Holewinski0497ab12013-03-30 14:29:21 +00001286 GVar->hasInitializer()) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001287 const Constant *Initializer = GVar->getInitializer();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001288 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001289 AggBuffer aggBuffer(ElementSize, O, *this);
1290 bufferAggregateConstant(Initializer, &aggBuffer);
1291 if (aggBuffer.numSymbols) {
Eric Christopher6aad8b12015-02-19 00:08:14 +00001292 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit()) {
Matt Arsenault8b643552015-06-09 00:31:39 +00001293 O << " .u64 ";
1294 getSymbol(GVar)->print(O, MAI);
1295 O << "[";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001296 O << ElementSize / 8;
1297 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001298 O << " .u32 ";
1299 getSymbol(GVar)->print(O, MAI);
1300 O << "[";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001301 O << ElementSize / 4;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001302 }
1303 O << "]";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001304 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001305 O << " .b8 ";
1306 getSymbol(GVar)->print(O, MAI);
1307 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001308 O << ElementSize;
1309 O << "]";
1310 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001311 O << " = {";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001312 aggBuffer.print();
1313 O << "}";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001314 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001315 O << " .b8 ";
1316 getSymbol(GVar)->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001317 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001318 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001319 O << ElementSize;
1320 O << "]";
1321 }
1322 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001323 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001324 O << " .b8 ";
1325 getSymbol(GVar)->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001326 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001327 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001328 O << ElementSize;
1329 O << "]";
1330 }
1331 }
1332 break;
1333 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001334 llvm_unreachable("type not supported yet");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001335 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001336 }
1337 O << ";\n";
1338}
1339
1340void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1341 if (localDecls.find(f) == localDecls.end())
1342 return;
1343
Justin Holewinski01f89f02013-05-20 12:13:32 +00001344 std::vector<const GlobalVariable *> &gvars = localDecls[f];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001345
Justin Holewinski0497ab12013-03-30 14:29:21 +00001346 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001347 O << "\t// demoted variable\n\t";
1348 printModuleLevelGV(gvars[i], O, true);
1349 }
1350}
1351
1352void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1353 raw_ostream &O) const {
1354 switch (AddressSpace) {
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001355 case ADDRESS_SPACE_LOCAL:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001356 O << "local";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001357 break;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001358 case ADDRESS_SPACE_GLOBAL:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001359 O << "global";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001360 break;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001361 case ADDRESS_SPACE_CONST:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001362 O << "const";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001363 break;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001364 case ADDRESS_SPACE_SHARED:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001365 O << "shared";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001366 break;
1367 default:
Justin Holewinski36a50992013-02-09 13:34:15 +00001368 report_fatal_error("Bad address space found while emitting PTX");
1369 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001370 }
1371}
1372
Justin Holewinski0497ab12013-03-30 14:29:21 +00001373std::string
Craig Toppere3dcce92015-08-01 22:20:21 +00001374NVPTXAsmPrinter::getPTXFundamentalTypeStr(Type *Ty, bool useB4PTR) const {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001375 switch (Ty->getTypeID()) {
1376 default:
1377 llvm_unreachable("unexpected type");
1378 break;
1379 case Type::IntegerTyID: {
1380 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1381 if (NumBits == 1)
1382 return "pred";
1383 else if (NumBits <= 64) {
1384 std::string name = "u";
1385 return name + utostr(NumBits);
1386 } else {
1387 llvm_unreachable("Integer too large");
1388 break;
1389 }
1390 break;
1391 }
Artem Belevich64dc9be2017-01-13 20:56:17 +00001392 case Type::HalfTyID:
1393 // fp16 is stored as .b16 for compatibility with pre-sm_53 PTX assembly.
1394 return "b16";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001395 case Type::FloatTyID:
1396 return "f32";
1397 case Type::DoubleTyID:
1398 return "f64";
1399 case Type::PointerTyID:
Eric Christopher6aad8b12015-02-19 00:08:14 +00001400 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit())
Justin Holewinski0497ab12013-03-30 14:29:21 +00001401 if (useB4PTR)
1402 return "b64";
1403 else
1404 return "u64";
1405 else if (useB4PTR)
1406 return "b32";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001407 else
Justin Holewinski0497ab12013-03-30 14:29:21 +00001408 return "u32";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001409 }
1410 llvm_unreachable("unexpected type");
Craig Topper062a2ba2014-04-25 05:30:21 +00001411 return nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001412}
1413
Justin Holewinski0497ab12013-03-30 14:29:21 +00001414void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001415 raw_ostream &O) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001416 const DataLayout &DL = getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001417
1418 // GlobalVariables are always constant pointers themselves.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001419 Type *ETy = GVar->getValueType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001420
1421 O << ".";
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001422 emitPTXAddressSpace(GVar->getType()->getAddressSpace(), O);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001423 if (GVar->getAlignment() == 0)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001424 O << " .align " << (int)DL.getPrefTypeAlignment(ETy);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001425 else
1426 O << " .align " << GVar->getAlignment();
1427
Artem Belevichd7a73822017-07-20 21:16:03 +00001428 // Special case for i128
1429 if (ETy->isIntegerTy(128)) {
1430 O << " .b8 ";
1431 getSymbol(GVar)->print(O, MAI);
1432 O << "[16]";
1433 return;
1434 }
1435
Jingyue Wue4c9cf02014-12-17 17:59:04 +00001436 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001437 O << " .";
1438 O << getPTXFundamentalTypeStr(ETy);
1439 O << " ";
Matt Arsenault8b643552015-06-09 00:31:39 +00001440 getSymbol(GVar)->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001441 return;
1442 }
1443
Justin Holewinski0497ab12013-03-30 14:29:21 +00001444 int64_t ElementSize = 0;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001445
1446 // Although PTX has direct support for struct type and array type and LLVM IR
1447 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1448 // support these high level field accesses. Structs and arrays are lowered
1449 // into arrays of bytes.
1450 switch (ETy->getTypeID()) {
1451 case Type::StructTyID:
1452 case Type::ArrayTyID:
1453 case Type::VectorTyID:
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001454 ElementSize = DL.getTypeStoreSize(ETy);
Matt Arsenault8b643552015-06-09 00:31:39 +00001455 O << " .b8 ";
1456 getSymbol(GVar)->print(O, MAI);
1457 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001458 if (ElementSize) {
Benjamin Kramerdba7ee92015-05-28 11:24:24 +00001459 O << ElementSize;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001460 }
1461 O << "]";
1462 break;
1463 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001464 llvm_unreachable("type not supported yet");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001465 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001466}
1467
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001468static unsigned int getOpenCLAlignment(const DataLayout &DL, Type *Ty) {
Rafael Espindola08013342013-12-07 19:34:20 +00001469 if (Ty->isSingleValueType())
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001470 return DL.getPrefTypeAlignment(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001471
Craig Toppere3dcce92015-08-01 22:20:21 +00001472 auto *ATy = dyn_cast<ArrayType>(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001473 if (ATy)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001474 return getOpenCLAlignment(DL, ATy->getElementType());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001475
Craig Toppere3dcce92015-08-01 22:20:21 +00001476 auto *STy = dyn_cast<StructType>(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001477 if (STy) {
1478 unsigned int alignStruct = 1;
1479 // Go through each element of the struct and find the
1480 // largest alignment.
Justin Holewinski0497ab12013-03-30 14:29:21 +00001481 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001482 Type *ETy = STy->getElementType(i);
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001483 unsigned int align = getOpenCLAlignment(DL, ETy);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001484 if (align > alignStruct)
1485 alignStruct = align;
1486 }
1487 return alignStruct;
1488 }
1489
Craig Toppere3dcce92015-08-01 22:20:21 +00001490 auto *FTy = dyn_cast<FunctionType>(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001491 if (FTy)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001492 return DL.getPointerPrefAlignment();
1493 return DL.getPrefTypeAlignment(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001494}
1495
1496void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1497 int paramIndex, raw_ostream &O) {
Matt Arsenault8b643552015-06-09 00:31:39 +00001498 getSymbol(I->getParent())->print(O, MAI);
1499 O << "_param_" << paramIndex;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001500}
1501
Justin Holewinski0497ab12013-03-30 14:29:21 +00001502void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001503 const DataLayout &DL = getDataLayout();
Reid Klecknerb5180542017-03-21 16:57:19 +00001504 const AttributeList &PAL = F->getAttributes();
Eric Christopher6aad8b12015-02-19 00:08:14 +00001505 const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001506 Function::const_arg_iterator I, E;
1507 unsigned paramIndex = 0;
1508 bool first = true;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001509 bool isKernelFunc = isKernelFunction(*F);
Eric Christopher6aad8b12015-02-19 00:08:14 +00001510 bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001511 MVT thePointerTy = TLI->getPointerTy(DL);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001512
Justin Lebar2a161f92016-01-23 21:12:17 +00001513 if (F->arg_empty()) {
1514 O << "()\n";
1515 return;
1516 }
1517
Justin Holewinskiae556d32012-05-04 20:18:50 +00001518 O << "(\n";
1519
1520 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
Justin Holewinskie9884092013-03-24 21:17:47 +00001521 Type *Ty = I->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001522
1523 if (!first)
1524 O << ",\n";
1525
1526 first = false;
1527
1528 // Handle image/sampler parameters
Justin Holewinski30d56a72014-04-09 15:39:15 +00001529 if (isKernelFunction(*F)) {
1530 if (isSampler(*I) || isImage(*I)) {
1531 if (isImage(*I)) {
1532 std::string sname = I->getName();
1533 if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
Eric Christopher6aad8b12015-02-19 00:08:14 +00001534 if (nvptxSubtarget->hasImageHandles())
Justin Holewinski30d56a72014-04-09 15:39:15 +00001535 O << "\t.param .u64 .ptr .surfref ";
1536 else
1537 O << "\t.param .surfref ";
Matt Arsenault8b643552015-06-09 00:31:39 +00001538 CurrentFnSym->print(O, MAI);
1539 O << "_param_" << paramIndex;
Justin Holewinski30d56a72014-04-09 15:39:15 +00001540 }
1541 else { // Default image is read_only
Eric Christopher6aad8b12015-02-19 00:08:14 +00001542 if (nvptxSubtarget->hasImageHandles())
Justin Holewinski30d56a72014-04-09 15:39:15 +00001543 O << "\t.param .u64 .ptr .texref ";
1544 else
1545 O << "\t.param .texref ";
Matt Arsenault8b643552015-06-09 00:31:39 +00001546 CurrentFnSym->print(O, MAI);
1547 O << "_param_" << paramIndex;
Justin Holewinski30d56a72014-04-09 15:39:15 +00001548 }
1549 } else {
Eric Christopher6aad8b12015-02-19 00:08:14 +00001550 if (nvptxSubtarget->hasImageHandles())
Justin Holewinski30d56a72014-04-09 15:39:15 +00001551 O << "\t.param .u64 .ptr .samplerref ";
1552 else
1553 O << "\t.param .samplerref ";
Matt Arsenault8b643552015-06-09 00:31:39 +00001554 CurrentFnSym->print(O, MAI);
1555 O << "_param_" << paramIndex;
Justin Holewinski30d56a72014-04-09 15:39:15 +00001556 }
1557 continue;
1558 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001559 }
1560
Reid Klecknerf021fab2017-04-13 23:12:13 +00001561 if (!PAL.hasParamAttribute(paramIndex, Attribute::ByVal)) {
Artem Belevichd7a73822017-07-20 21:16:03 +00001562 if (Ty->isAggregateType() || Ty->isVectorTy() || Ty->isIntegerTy(128)) {
Gautam Chakrabarti2c283402014-01-28 18:35:29 +00001563 // Just print .param .align <a> .b8 .param[size];
Justin Holewinskie9884092013-03-24 21:17:47 +00001564 // <a> = PAL.getparamalignment
1565 // size = typeallocsize of element type
Reid Kleckner859f8b52017-04-28 20:34:27 +00001566 unsigned align = PAL.getParamAlignment(paramIndex);
Justin Holewinskie9884092013-03-24 21:17:47 +00001567 if (align == 0)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001568 align = DL.getABITypeAlignment(Ty);
Justin Holewinskie9884092013-03-24 21:17:47 +00001569
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001570 unsigned sz = DL.getTypeAllocSize(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001571 O << "\t.param .align " << align << " .b8 ";
Justin Holewinskie9884092013-03-24 21:17:47 +00001572 printParamName(I, paramIndex, O);
1573 O << "[" << sz << "]";
1574
1575 continue;
1576 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001577 // Just a scalar
Craig Toppere3dcce92015-08-01 22:20:21 +00001578 auto *PTy = dyn_cast<PointerType>(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001579 if (isKernelFunc) {
1580 if (PTy) {
1581 // Special handling for pointer arguments to kernel
1582 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1583
Eric Christopherbeffc4e2015-02-19 00:08:23 +00001584 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() !=
1585 NVPTX::CUDA) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001586 Type *ETy = PTy->getElementType();
1587 int addrSpace = PTy->getAddressSpace();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001588 switch (addrSpace) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001589 default:
1590 O << ".ptr ";
1591 break;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001592 case ADDRESS_SPACE_CONST:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001593 O << ".ptr .const ";
1594 break;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001595 case ADDRESS_SPACE_SHARED:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001596 O << ".ptr .shared ";
1597 break;
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00001598 case ADDRESS_SPACE_GLOBAL:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001599 O << ".ptr .global ";
1600 break;
1601 }
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001602 O << ".align " << (int)getOpenCLAlignment(DL, ETy) << " ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001603 }
1604 printParamName(I, paramIndex, O);
1605 continue;
1606 }
1607
1608 // non-pointer scalar to kernel func
Justin Holewinski700b6fa2013-05-20 12:13:28 +00001609 O << "\t.param .";
1610 // Special case: predicate operands become .u8 types
1611 if (Ty->isIntegerTy(1))
1612 O << "u8";
1613 else
1614 O << getPTXFundamentalTypeStr(Ty);
1615 O << " ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001616 printParamName(I, paramIndex, O);
1617 continue;
1618 }
1619 // Non-kernel function, just print .param .b<size> for ABI
Alp Tokerf907b892013-12-05 05:44:44 +00001620 // and .reg .b<size> for non-ABI
Justin Holewinskiae556d32012-05-04 20:18:50 +00001621 unsigned sz = 0;
1622 if (isa<IntegerType>(Ty)) {
1623 sz = cast<IntegerType>(Ty)->getBitWidth();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001624 if (sz < 32)
1625 sz = 32;
1626 } else if (isa<PointerType>(Ty))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001627 sz = thePointerTy.getSizeInBits();
Artem Belevich64dc9be2017-01-13 20:56:17 +00001628 else if (Ty->isHalfTy())
1629 // PTX ABI requires all scalar parameters to be at least 32
1630 // bits in size. fp16 normally uses .b16 as its storage type
1631 // in PTX, so its size must be adjusted here, too.
1632 sz = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001633 else
1634 sz = Ty->getPrimitiveSizeInBits();
1635 if (isABI)
1636 O << "\t.param .b" << sz << " ";
1637 else
1638 O << "\t.reg .b" << sz << " ";
1639 printParamName(I, paramIndex, O);
1640 continue;
1641 }
1642
1643 // param has byVal attribute. So should be a pointer
Craig Toppere3dcce92015-08-01 22:20:21 +00001644 auto *PTy = dyn_cast<PointerType>(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001645 assert(PTy && "Param with byval attribute should be a pointer type");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001646 Type *ETy = PTy->getElementType();
1647
1648 if (isABI || isKernelFunc) {
Gautam Chakrabarti2c283402014-01-28 18:35:29 +00001649 // Just print .param .align <a> .b8 .param[size];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001650 // <a> = PAL.getparamalignment
1651 // size = typeallocsize of element type
Reid Kleckner859f8b52017-04-28 20:34:27 +00001652 unsigned align = PAL.getParamAlignment(paramIndex);
Justin Holewinski2dc9d072012-11-09 23:50:24 +00001653 if (align == 0)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001654 align = DL.getABITypeAlignment(ETy);
Artem Belevich052b1ed2016-07-18 19:54:56 +00001655 // Work around a bug in ptxas. When PTX code takes address of
1656 // byval parameter with alignment < 4, ptxas generates code to
1657 // spill argument into memory. Alas on sm_50+ ptxas generates
1658 // SASS code that fails with misaligned access. To work around
1659 // the problem, make sure that we align byval parameters by at
1660 // least 4. Matching change must be made in LowerCall() where we
1661 // prepare parameters for the call.
1662 //
1663 // TODO: this will need to be undone when we get to support multi-TU
1664 // device-side compilation as it breaks ABI compatibility with nvcc.
1665 // Hopefully ptxas bug is fixed by then.
1666 if (!isKernelFunc && align < 4)
1667 align = 4;
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001668 unsigned sz = DL.getTypeAllocSize(ETy);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001669 O << "\t.param .align " << align << " .b8 ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001670 printParamName(I, paramIndex, O);
1671 O << "[" << sz << "]";
1672 continue;
1673 } else {
1674 // Split the ETy into constituent parts and
1675 // print .param .b<size> <name> for each part.
1676 // Further, if a part is vector, print the above for
1677 // each vector element.
1678 SmallVector<EVT, 16> vtparts;
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001679 ComputeValueVTs(*TLI, DL, ETy, vtparts);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001680 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001681 unsigned elems = 1;
1682 EVT elemtype = vtparts[i];
1683 if (vtparts[i].isVector()) {
1684 elems = vtparts[i].getVectorNumElements();
1685 elemtype = vtparts[i].getVectorElementType();
1686 }
1687
Justin Holewinski0497ab12013-03-30 14:29:21 +00001688 for (unsigned j = 0, je = elems; j != je; ++j) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001689 unsigned sz = elemtype.getSizeInBits();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001690 if (elemtype.isInteger() && (sz < 32))
1691 sz = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001692 O << "\t.reg .b" << sz << " ";
1693 printParamName(I, paramIndex, O);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001694 if (j < je - 1)
1695 O << ",\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001696 ++paramIndex;
1697 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001698 if (i < e - 1)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001699 O << ",\n";
1700 }
1701 --paramIndex;
1702 continue;
1703 }
1704 }
1705
1706 O << "\n)\n";
1707}
1708
1709void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1710 raw_ostream &O) {
1711 const Function *F = MF.getFunction();
1712 emitFunctionParamList(F, O);
1713}
1714
Justin Holewinski0497ab12013-03-30 14:29:21 +00001715void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1716 const MachineFunction &MF) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001717 SmallString<128> Str;
1718 raw_svector_ostream O(Str);
1719
1720 // Map the global virtual register number to a register class specific
1721 // virtual register number starting from 1 with that class.
Eric Christopherfc6de422014-08-05 02:39:49 +00001722 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001723 //unsigned numRegClasses = TRI->getNumRegClasses();
1724
1725 // Emit the Fake Stack Object
Matthias Braun941a7052016-07-28 18:40:00 +00001726 const MachineFrameInfo &MFI = MF.getFrameInfo();
1727 int NumBytes = (int) MFI.getStackSize();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001728 if (NumBytes) {
Matthias Braun941a7052016-07-28 18:40:00 +00001729 O << "\t.local .align " << MFI.getMaxAlignment() << " .b8 \t" << DEPOTNAME
Justin Holewinski0497ab12013-03-30 14:29:21 +00001730 << getFunctionNumber() << "[" << NumBytes << "];\n";
Eric Christopher02389e32015-02-19 00:08:27 +00001731 if (static_cast<const NVPTXTargetMachine &>(MF.getTarget()).is64Bit()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001732 O << "\t.reg .b64 \t%SP;\n";
1733 O << "\t.reg .b64 \t%SPL;\n";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001734 } else {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001735 O << "\t.reg .b32 \t%SP;\n";
1736 O << "\t.reg .b32 \t%SPL;\n";
1737 }
1738 }
1739
1740 // Go through all virtual registers to establish the mapping between the
1741 // global virtual
1742 // register number and the per class virtual register number.
1743 // We use the per class virtual register number in the ptx output.
1744 unsigned int numVRs = MRI->getNumVirtRegs();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001745 for (unsigned i = 0; i < numVRs; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001746 unsigned int vr = TRI->index2VirtReg(i);
1747 const TargetRegisterClass *RC = MRI->getRegClass(vr);
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001748 DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001749 int n = regmap.size();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001750 regmap.insert(std::make_pair(vr, n + 1));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001751 }
1752
1753 // Emit register declarations
1754 // @TODO: Extract out the real register usage
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001755 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1756 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1757 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1758 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
Justin Holewinski3e037d92014-07-16 16:26:58 +00001759 // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001760 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
Justin Holewinski3e037d92014-07-16 16:26:58 +00001761 // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001762
1763 // Emit declaration of the virtual registers or 'physical' registers for
1764 // each register class
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001765 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1766 const TargetRegisterClass *RC = TRI->getRegClass(i);
1767 DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
1768 std::string rcname = getNVPTXRegClassName(RC);
1769 std::string rcStr = getNVPTXRegClassStr(RC);
1770 int n = regmap.size();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001771
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001772 // Only declare those registers that may be used.
1773 if (n) {
1774 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1775 << ">;\n";
1776 }
1777 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001778
Lang Hames9ff69c82015-04-24 19:11:51 +00001779 OutStreamer->EmitRawText(O.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001780}
1781
Justin Holewinskiae556d32012-05-04 20:18:50 +00001782void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001783 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
Justin Holewinskiae556d32012-05-04 20:18:50 +00001784 bool ignored;
1785 unsigned int numHex;
1786 const char *lead;
1787
Justin Holewinski0497ab12013-03-30 14:29:21 +00001788 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001789 numHex = 8;
1790 lead = "0f";
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001791 APF.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &ignored);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001792 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1793 numHex = 16;
1794 lead = "0d";
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001795 APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &ignored);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001796 } else
1797 llvm_unreachable("unsupported fp type");
1798
1799 APInt API = APF.bitcastToAPInt();
1800 std::string hexstr(utohexstr(API.getZExtValue()));
1801 O << lead;
1802 if (hexstr.length() < numHex)
1803 O << std::string(numHex - hexstr.length(), '0');
1804 O << utohexstr(API.getZExtValue());
1805}
1806
Justin Holewinski01f89f02013-05-20 12:13:32 +00001807void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1808 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001809 O << CI->getValue();
1810 return;
1811 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001812 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001813 printFPConstant(CFP, O);
1814 return;
1815 }
1816 if (isa<ConstantPointerNull>(CPV)) {
1817 O << "0";
1818 return;
1819 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001820 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
Justin Holewinski9d852a82014-04-09 15:39:11 +00001821 bool IsNonGenericPointer = false;
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001822 if (GVar->getType()->getAddressSpace() != 0) {
Justin Holewinski9d852a82014-04-09 15:39:11 +00001823 IsNonGenericPointer = true;
1824 }
1825 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1826 O << "generic(";
Matt Arsenault8b643552015-06-09 00:31:39 +00001827 getSymbol(GVar)->print(O, MAI);
Justin Holewinski9d852a82014-04-09 15:39:11 +00001828 O << ")";
1829 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001830 getSymbol(GVar)->print(O, MAI);
Justin Holewinski9d852a82014-04-09 15:39:11 +00001831 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001832 return;
1833 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001834 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1835 const Value *v = Cexpr->stripPointerCasts();
Justin Holewinski9d852a82014-04-09 15:39:11 +00001836 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1837 bool IsNonGenericPointer = false;
1838 if (PTy && PTy->getAddressSpace() != 0) {
1839 IsNonGenericPointer = true;
1840 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001841 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
Justin Holewinski9d852a82014-04-09 15:39:11 +00001842 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1843 O << "generic(";
Matt Arsenault8b643552015-06-09 00:31:39 +00001844 getSymbol(GVar)->print(O, MAI);
Justin Holewinski9d852a82014-04-09 15:39:11 +00001845 O << ")";
1846 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001847 getSymbol(GVar)->print(O, MAI);
Justin Holewinski9d852a82014-04-09 15:39:11 +00001848 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001849 return;
1850 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001851 lowerConstant(CPV)->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001852 return;
1853 }
1854 }
1855 llvm_unreachable("Not scalar type found in printScalarConstant()");
1856}
1857
Samuel Antaocd501352015-06-09 16:29:34 +00001858// These utility functions assure we get the right sequence of bytes for a given
1859// type even for big-endian machines
1860template <typename T> static void ConvertIntToBytes(unsigned char *p, T val) {
1861 int64_t vp = (int64_t)val;
1862 for (unsigned i = 0; i < sizeof(T); ++i) {
1863 p[i] = (unsigned char)vp;
1864 vp >>= 8;
1865 }
1866}
1867static void ConvertFloatToBytes(unsigned char *p, float val) {
1868 int32_t *vp = (int32_t *)&val;
1869 for (unsigned i = 0; i < sizeof(int32_t); ++i) {
1870 p[i] = (unsigned char)*vp;
1871 *vp >>= 8;
1872 }
1873}
1874static void ConvertDoubleToBytes(unsigned char *p, double val) {
1875 int64_t *vp = (int64_t *)&val;
1876 for (unsigned i = 0; i < sizeof(int64_t); ++i) {
1877 p[i] = (unsigned char)*vp;
1878 *vp >>= 8;
1879 }
1880}
1881
Justin Holewinski01f89f02013-05-20 12:13:32 +00001882void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001883 AggBuffer *aggBuffer) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001884 const DataLayout &DL = getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001885
1886 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001887 int s = DL.getTypeAllocSize(CPV->getType());
Justin Holewinski0497ab12013-03-30 14:29:21 +00001888 if (s < Bytes)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001889 s = Bytes;
1890 aggBuffer->addZeros(s);
1891 return;
1892 }
1893
Samuel Antaocd501352015-06-09 16:29:34 +00001894 unsigned char ptr[8];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001895 switch (CPV->getType()->getTypeID()) {
1896
1897 case Type::IntegerTyID: {
Craig Toppere3dcce92015-08-01 22:20:21 +00001898 Type *ETy = CPV->getType();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001899 if (ETy == Type::getInt8Ty(CPV->getContext())) {
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001900 unsigned char c = (unsigned char)cast<ConstantInt>(CPV)->getZExtValue();
Samuel Antaocd501352015-06-09 16:29:34 +00001901 ConvertIntToBytes<>(ptr, c);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001902 aggBuffer->addBytes(ptr, 1, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001903 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001904 short int16 = (short)cast<ConstantInt>(CPV)->getZExtValue();
Samuel Antaocd501352015-06-09 16:29:34 +00001905 ConvertIntToBytes<>(ptr, int16);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001906 aggBuffer->addBytes(ptr, 2, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001907 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001908 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001909 int int32 = (int)(constInt->getZExtValue());
Samuel Antaocd501352015-06-09 16:29:34 +00001910 ConvertIntToBytes<>(ptr, int32);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001911 aggBuffer->addBytes(ptr, 4, Bytes);
1912 break;
David Majnemerd536f232016-07-29 03:27:26 +00001913 } else if (const auto *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1914 if (const auto *constInt = dyn_cast_or_null<ConstantInt>(
1915 ConstantFoldConstant(Cexpr, DL))) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001916 int int32 = (int)(constInt->getZExtValue());
Samuel Antaocd501352015-06-09 16:29:34 +00001917 ConvertIntToBytes<>(ptr, int32);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001918 aggBuffer->addBytes(ptr, 4, Bytes);
1919 break;
1920 }
1921 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1922 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
Jingyue Wu312fd022015-04-24 02:57:30 +00001923 aggBuffer->addSymbol(v, Cexpr->getOperand(0));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001924 aggBuffer->addZeros(4);
1925 break;
1926 }
1927 }
Craig Topperbdf39a42012-05-24 07:02:50 +00001928 llvm_unreachable("unsupported integer const type");
Justin Holewinski0497ab12013-03-30 14:29:21 +00001929 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001930 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001931 long long int64 = (long long)(constInt->getZExtValue());
Samuel Antaocd501352015-06-09 16:29:34 +00001932 ConvertIntToBytes<>(ptr, int64);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001933 aggBuffer->addBytes(ptr, 8, Bytes);
1934 break;
Justin Holewinski01f89f02013-05-20 12:13:32 +00001935 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
David Majnemerd536f232016-07-29 03:27:26 +00001936 if (const auto *constInt = dyn_cast_or_null<ConstantInt>(
1937 ConstantFoldConstant(Cexpr, DL))) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001938 long long int64 = (long long)(constInt->getZExtValue());
Samuel Antaocd501352015-06-09 16:29:34 +00001939 ConvertIntToBytes<>(ptr, int64);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001940 aggBuffer->addBytes(ptr, 8, Bytes);
1941 break;
1942 }
1943 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1944 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
Jingyue Wu312fd022015-04-24 02:57:30 +00001945 aggBuffer->addSymbol(v, Cexpr->getOperand(0));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001946 aggBuffer->addZeros(8);
1947 break;
1948 }
1949 }
1950 llvm_unreachable("unsupported integer const type");
Craig Topperbdf39a42012-05-24 07:02:50 +00001951 } else
Justin Holewinskiae556d32012-05-04 20:18:50 +00001952 llvm_unreachable("unsupported integer const type");
1953 break;
1954 }
1955 case Type::FloatTyID:
1956 case Type::DoubleTyID: {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001957 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
Craig Toppere3dcce92015-08-01 22:20:21 +00001958 Type *Ty = CFP->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001959 if (Ty == Type::getFloatTy(CPV->getContext())) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001960 float float32 = (float) CFP->getValueAPF().convertToFloat();
Samuel Antaocd501352015-06-09 16:29:34 +00001961 ConvertFloatToBytes(ptr, float32);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001962 aggBuffer->addBytes(ptr, 4, Bytes);
1963 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1964 double float64 = CFP->getValueAPF().convertToDouble();
Samuel Antaocd501352015-06-09 16:29:34 +00001965 ConvertDoubleToBytes(ptr, float64);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001966 aggBuffer->addBytes(ptr, 8, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001967 } else {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001968 llvm_unreachable("unsupported fp const type");
1969 }
1970 break;
1971 }
1972 case Type::PointerTyID: {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001973 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
Jingyue Wu312fd022015-04-24 02:57:30 +00001974 aggBuffer->addSymbol(GVar, GVar);
Justin Holewinski01f89f02013-05-20 12:13:32 +00001975 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1976 const Value *v = Cexpr->stripPointerCasts();
Jingyue Wu312fd022015-04-24 02:57:30 +00001977 aggBuffer->addSymbol(v, Cexpr);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001978 }
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001979 unsigned int s = DL.getTypeAllocSize(CPV->getType());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001980 aggBuffer->addZeros(s);
1981 break;
1982 }
1983
1984 case Type::ArrayTyID:
1985 case Type::VectorTyID:
1986 case Type::StructTyID: {
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00001987 if (isa<ConstantAggregate>(CPV) || isa<ConstantDataSequential>(CPV)) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001988 int ElementSize = DL.getTypeAllocSize(CPV->getType());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001989 bufferAggregateConstant(CPV, aggBuffer);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001990 if (Bytes > ElementSize)
1991 aggBuffer->addZeros(Bytes - ElementSize);
1992 } else if (isa<ConstantAggregateZero>(CPV))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001993 aggBuffer->addZeros(Bytes);
1994 else
1995 llvm_unreachable("Unexpected Constant type");
1996 break;
1997 }
1998
1999 default:
2000 llvm_unreachable("unsupported type");
2001 }
2002}
2003
Justin Holewinski01f89f02013-05-20 12:13:32 +00002004void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
Justin Holewinskiae556d32012-05-04 20:18:50 +00002005 AggBuffer *aggBuffer) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00002006 const DataLayout &DL = getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00002007 int Bytes;
2008
Justin Lebar1cf6bf42017-01-18 00:29:53 +00002009 // Integers of arbitrary width
2010 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
2011 APInt Val = CI->getValue();
2012 for (unsigned I = 0, E = DL.getTypeAllocSize(CPV->getType()); I < E; ++I) {
2013 uint8_t Byte = Val.getLoBits(8).getZExtValue();
2014 aggBuffer->addBytes(&Byte, 1, 1);
Craig Topperfc947bc2017-04-18 17:14:21 +00002015 Val.lshrInPlace(8);
Justin Lebar1cf6bf42017-01-18 00:29:53 +00002016 }
2017 return;
2018 }
2019
Justin Holewinskiae556d32012-05-04 20:18:50 +00002020 // Old constants
2021 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
2022 if (CPV->getNumOperands())
2023 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
2024 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
2025 return;
2026 }
2027
2028 if (const ConstantDataSequential *CDS =
Justin Holewinski0497ab12013-03-30 14:29:21 +00002029 dyn_cast<ConstantDataSequential>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00002030 if (CDS->getNumElements())
2031 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
2032 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
2033 aggBuffer);
2034 return;
2035 }
2036
Justin Holewinskiae556d32012-05-04 20:18:50 +00002037 if (isa<ConstantStruct>(CPV)) {
2038 if (CPV->getNumOperands()) {
2039 StructType *ST = cast<StructType>(CPV->getType());
2040 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002041 if (i == (e - 1))
Mehdi Aminibd7287e2015-07-16 06:11:10 +00002042 Bytes = DL.getStructLayout(ST)->getElementOffset(0) +
2043 DL.getTypeAllocSize(ST) -
2044 DL.getStructLayout(ST)->getElementOffset(i);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002045 else
Mehdi Aminibd7287e2015-07-16 06:11:10 +00002046 Bytes = DL.getStructLayout(ST)->getElementOffset(i + 1) -
2047 DL.getStructLayout(ST)->getElementOffset(i);
Justin Holewinski0497ab12013-03-30 14:29:21 +00002048 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002049 }
2050 }
2051 return;
2052 }
Craig Topperbdf39a42012-05-24 07:02:50 +00002053 llvm_unreachable("unsupported constant type in printAggregateConstant()");
Justin Holewinskiae556d32012-05-04 20:18:50 +00002054}
2055
2056// buildTypeNameMap - Run through symbol table looking for type names.
2057//
2058
Justin Holewinski0497ab12013-03-30 14:29:21 +00002059bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
2060 switch (MI.getOpcode()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00002061 default:
2062 return false;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002063 case NVPTX::CallArgBeginInst:
2064 case NVPTX::CallArgEndInst0:
2065 case NVPTX::CallArgEndInst1:
2066 case NVPTX::CallArgF32:
2067 case NVPTX::CallArgF64:
2068 case NVPTX::CallArgI16:
2069 case NVPTX::CallArgI32:
2070 case NVPTX::CallArgI32imm:
2071 case NVPTX::CallArgI64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002072 case NVPTX::CallArgParam:
2073 case NVPTX::CallVoidInst:
2074 case NVPTX::CallVoidInstReg:
2075 case NVPTX::Callseq_End:
Justin Holewinskiae556d32012-05-04 20:18:50 +00002076 case NVPTX::CallVoidInstReg64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002077 case NVPTX::DeclareParamInst:
2078 case NVPTX::DeclareRetMemInst:
2079 case NVPTX::DeclareRetRegInst:
2080 case NVPTX::DeclareRetScalarInst:
2081 case NVPTX::DeclareScalarParamInst:
2082 case NVPTX::DeclareScalarRegInst:
2083 case NVPTX::StoreParamF32:
2084 case NVPTX::StoreParamF64:
2085 case NVPTX::StoreParamI16:
2086 case NVPTX::StoreParamI32:
2087 case NVPTX::StoreParamI64:
2088 case NVPTX::StoreParamI8:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002089 case NVPTX::StoreRetvalF32:
2090 case NVPTX::StoreRetvalF64:
2091 case NVPTX::StoreRetvalI16:
2092 case NVPTX::StoreRetvalI32:
2093 case NVPTX::StoreRetvalI64:
2094 case NVPTX::StoreRetvalI8:
2095 case NVPTX::LastCallArgF32:
2096 case NVPTX::LastCallArgF64:
2097 case NVPTX::LastCallArgI16:
2098 case NVPTX::LastCallArgI32:
2099 case NVPTX::LastCallArgI32imm:
2100 case NVPTX::LastCallArgI64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002101 case NVPTX::LastCallArgParam:
2102 case NVPTX::LoadParamMemF32:
2103 case NVPTX::LoadParamMemF64:
2104 case NVPTX::LoadParamMemI16:
2105 case NVPTX::LoadParamMemI32:
2106 case NVPTX::LoadParamMemI64:
2107 case NVPTX::LoadParamMemI8:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002108 case NVPTX::PrototypeInst:
2109 case NVPTX::DBG_VALUE:
Justin Holewinskiae556d32012-05-04 20:18:50 +00002110 return true;
2111 }
2112 return false;
2113}
2114
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002115/// lowerConstantForGV - Return an MCExpr for the given Constant. This is mostly
2116/// a copy from AsmPrinter::lowerConstant, except customized to only handle
2117/// expressions that are representable in PTX and create
2118/// NVPTXGenericMCSymbolRefExpr nodes for addrspacecast instructions.
2119const MCExpr *
2120NVPTXAsmPrinter::lowerConstantForGV(const Constant *CV, bool ProcessingGeneric) {
2121 MCContext &Ctx = OutContext;
2122
2123 if (CV->isNullValue() || isa<UndefValue>(CV))
Jim Grosbach13760bd2015-05-30 01:25:56 +00002124 return MCConstantExpr::create(0, Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002125
2126 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
Jim Grosbach13760bd2015-05-30 01:25:56 +00002127 return MCConstantExpr::create(CI->getZExtValue(), Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002128
2129 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
2130 const MCSymbolRefExpr *Expr =
Jim Grosbach13760bd2015-05-30 01:25:56 +00002131 MCSymbolRefExpr::create(getSymbol(GV), Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002132 if (ProcessingGeneric) {
Jim Grosbach13760bd2015-05-30 01:25:56 +00002133 return NVPTXGenericMCSymbolRefExpr::create(Expr, Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002134 } else {
2135 return Expr;
2136 }
2137 }
2138
2139 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
2140 if (!CE) {
2141 llvm_unreachable("Unknown constant value to lower!");
2142 }
2143
2144 switch (CE->getOpcode()) {
2145 default:
2146 // If the code isn't optimized, there may be outstanding folding
2147 // opportunities. Attempt to fold the expression using DataLayout as a
2148 // last resort before giving up.
David Majnemerd536f232016-07-29 03:27:26 +00002149 if (Constant *C = ConstantFoldConstant(CE, getDataLayout()))
2150 if (C && C != CE)
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002151 return lowerConstantForGV(C, ProcessingGeneric);
2152
2153 // Otherwise report the problem to the user.
2154 {
2155 std::string S;
2156 raw_string_ostream OS(S);
2157 OS << "Unsupported expression in static initializer: ";
2158 CE->printAsOperand(OS, /*PrintType=*/false,
2159 !MF ? nullptr : MF->getFunction()->getParent());
2160 report_fatal_error(OS.str());
2161 }
2162
2163 case Instruction::AddrSpaceCast: {
2164 // Strip the addrspacecast and pass along the operand
2165 PointerType *DstTy = cast<PointerType>(CE->getType());
2166 if (DstTy->getAddressSpace() == 0) {
2167 return lowerConstantForGV(cast<const Constant>(CE->getOperand(0)), true);
2168 }
2169 std::string S;
2170 raw_string_ostream OS(S);
2171 OS << "Unsupported expression in static initializer: ";
2172 CE->printAsOperand(OS, /*PrintType=*/ false,
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00002173 !MF ? nullptr : MF->getFunction()->getParent());
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002174 report_fatal_error(OS.str());
2175 }
2176
2177 case Instruction::GetElementPtr: {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00002178 const DataLayout &DL = getDataLayout();
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002179
2180 // Generate a symbolic expression for the byte address
2181 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
2182 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
2183
2184 const MCExpr *Base = lowerConstantForGV(CE->getOperand(0),
2185 ProcessingGeneric);
2186 if (!OffsetAI)
2187 return Base;
2188
2189 int64_t Offset = OffsetAI.getSExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00002190 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002191 Ctx);
2192 }
2193
2194 case Instruction::Trunc:
2195 // We emit the value and depend on the assembler to truncate the generated
2196 // expression properly. This is important for differences between
2197 // blockaddress labels. Since the two labels are in the same function, it
2198 // is reasonable to treat their delta as a 32-bit value.
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002199 LLVM_FALLTHROUGH;
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002200 case Instruction::BitCast:
2201 return lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2202
2203 case Instruction::IntToPtr: {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00002204 const DataLayout &DL = getDataLayout();
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002205
2206 // Handle casts to pointers by changing them into casts to the appropriate
2207 // integer type. This promotes constant folding and simplifies this code.
2208 Constant *Op = CE->getOperand(0);
2209 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
2210 false/*ZExt*/);
2211 return lowerConstantForGV(Op, ProcessingGeneric);
2212 }
2213
2214 case Instruction::PtrToInt: {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00002215 const DataLayout &DL = getDataLayout();
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002216
2217 // Support only foldable casts to/from pointers that can be eliminated by
2218 // changing the pointer to the appropriately sized integer type.
2219 Constant *Op = CE->getOperand(0);
2220 Type *Ty = CE->getType();
2221
2222 const MCExpr *OpExpr = lowerConstantForGV(Op, ProcessingGeneric);
2223
2224 // We can emit the pointer value into this slot if the slot is an
2225 // integer slot equal to the size of the pointer.
2226 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
2227 return OpExpr;
2228
2229 // Otherwise the pointer is smaller than the resultant integer, mask off
2230 // the high bits so we are sure to get a proper truncation if the input is
2231 // a constant expr.
2232 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
Jim Grosbach13760bd2015-05-30 01:25:56 +00002233 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
2234 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002235 }
2236
2237 // The MC library also has a right-shift operator, but it isn't consistently
2238 // signed or unsigned between different targets.
2239 case Instruction::Add: {
2240 const MCExpr *LHS = lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2241 const MCExpr *RHS = lowerConstantForGV(CE->getOperand(1), ProcessingGeneric);
2242 switch (CE->getOpcode()) {
2243 default: llvm_unreachable("Unknown binary operator constant cast expr");
Jim Grosbach13760bd2015-05-30 01:25:56 +00002244 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002245 }
2246 }
2247 }
2248}
2249
2250// Copy of MCExpr::print customized for NVPTX
2251void NVPTXAsmPrinter::printMCExpr(const MCExpr &Expr, raw_ostream &OS) {
2252 switch (Expr.getKind()) {
2253 case MCExpr::Target:
Matt Arsenault8b643552015-06-09 00:31:39 +00002254 return cast<MCTargetExpr>(&Expr)->printImpl(OS, MAI);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002255 case MCExpr::Constant:
2256 OS << cast<MCConstantExpr>(Expr).getValue();
2257 return;
2258
2259 case MCExpr::SymbolRef: {
2260 const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(Expr);
2261 const MCSymbol &Sym = SRE.getSymbol();
Matt Arsenault8b643552015-06-09 00:31:39 +00002262 Sym.print(OS, MAI);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002263 return;
2264 }
2265
2266 case MCExpr::Unary: {
2267 const MCUnaryExpr &UE = cast<MCUnaryExpr>(Expr);
2268 switch (UE.getOpcode()) {
2269 case MCUnaryExpr::LNot: OS << '!'; break;
2270 case MCUnaryExpr::Minus: OS << '-'; break;
2271 case MCUnaryExpr::Not: OS << '~'; break;
2272 case MCUnaryExpr::Plus: OS << '+'; break;
2273 }
2274 printMCExpr(*UE.getSubExpr(), OS);
2275 return;
2276 }
2277
2278 case MCExpr::Binary: {
2279 const MCBinaryExpr &BE = cast<MCBinaryExpr>(Expr);
2280
2281 // Only print parens around the LHS if it is non-trivial.
2282 if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS()) ||
2283 isa<NVPTXGenericMCSymbolRefExpr>(BE.getLHS())) {
2284 printMCExpr(*BE.getLHS(), OS);
2285 } else {
2286 OS << '(';
2287 printMCExpr(*BE.getLHS(), OS);
2288 OS<< ')';
2289 }
2290
2291 switch (BE.getOpcode()) {
2292 case MCBinaryExpr::Add:
2293 // Print "X-42" instead of "X+-42".
2294 if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
2295 if (RHSC->getValue() < 0) {
2296 OS << RHSC->getValue();
2297 return;
2298 }
2299 }
2300
2301 OS << '+';
2302 break;
2303 default: llvm_unreachable("Unhandled binary operator");
2304 }
2305
2306 // Only print parens around the LHS if it is non-trivial.
2307 if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
2308 printMCExpr(*BE.getRHS(), OS);
2309 } else {
2310 OS << '(';
2311 printMCExpr(*BE.getRHS(), OS);
2312 OS << ')';
2313 }
2314 return;
2315 }
2316 }
2317
2318 llvm_unreachable("Invalid expression kind!");
2319}
2320
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002321/// PrintAsmOperand - Print out an operand for an inline asm expression.
2322///
2323bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2324 unsigned AsmVariant,
2325 const char *ExtraCode, raw_ostream &O) {
2326 if (ExtraCode && ExtraCode[0]) {
2327 if (ExtraCode[1] != 0)
2328 return true; // Unknown modifier.
2329
2330 switch (ExtraCode[0]) {
2331 default:
2332 // See if this is a generic print operand
2333 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2334 case 'r':
2335 break;
2336 }
2337 }
2338
2339 printOperand(MI, OpNo, O);
2340
2341 return false;
2342}
2343
2344bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2345 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2346 const char *ExtraCode, raw_ostream &O) {
2347 if (ExtraCode && ExtraCode[0])
2348 return true; // Unknown modifier
2349
2350 O << '[';
2351 printMemOperand(MI, OpNo, O);
2352 O << ']';
2353
2354 return false;
2355}
2356
2357void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2358 raw_ostream &O, const char *Modifier) {
2359 const MachineOperand &MO = MI->getOperand(opNum);
2360 switch (MO.getType()) {
2361 case MachineOperand::MO_Register:
2362 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2363 if (MO.getReg() == NVPTX::VRDepot)
2364 O << DEPOTNAME << getFunctionNumber();
2365 else
2366 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2367 } else {
Justin Holewinski660597d2013-10-11 12:39:36 +00002368 emitVirtualRegister(MO.getReg(), O);
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002369 }
2370 return;
2371
2372 case MachineOperand::MO_Immediate:
2373 if (!Modifier)
2374 O << MO.getImm();
2375 else if (strstr(Modifier, "vec") == Modifier)
2376 printVecModifiedImmediate(MO, Modifier, O);
2377 else
2378 llvm_unreachable(
2379 "Don't know how to handle modifier on immediate operand");
2380 return;
2381
2382 case MachineOperand::MO_FPImmediate:
2383 printFPConstant(MO.getFPImm(), O);
2384 break;
2385
2386 case MachineOperand::MO_GlobalAddress:
Matt Arsenault8b643552015-06-09 00:31:39 +00002387 getSymbol(MO.getGlobal())->print(O, MAI);
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002388 break;
2389
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002390 case MachineOperand::MO_MachineBasicBlock:
Matt Arsenault8b643552015-06-09 00:31:39 +00002391 MO.getMBB()->getSymbol()->print(O, MAI);
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002392 return;
2393
2394 default:
2395 llvm_unreachable("Operand type not supported.");
2396 }
2397}
2398
2399void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2400 raw_ostream &O, const char *Modifier) {
2401 printOperand(MI, opNum, O);
2402
Eugene Zelenkoc9f1f6b2017-01-09 22:16:51 +00002403 if (Modifier && strcmp(Modifier, "add") == 0) {
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002404 O << ", ";
2405 printOperand(MI, opNum + 1, O);
2406 } else {
2407 if (MI->getOperand(opNum + 1).isImm() &&
2408 MI->getOperand(opNum + 1).getImm() == 0)
2409 return; // don't print ',0' or '+0'
2410 O << "+";
2411 printOperand(MI, opNum + 1, O);
2412 }
2413}
2414
Justin Holewinskiae556d32012-05-04 20:18:50 +00002415void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2416 std::stringstream temp;
Yaron Keren075759a2015-03-30 15:42:36 +00002417 LineReader *reader = this->getReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002418 temp << "\n//";
2419 temp << filename.str();
2420 temp << ":";
2421 temp << line;
2422 temp << " ";
2423 temp << reader->readLine(line);
2424 temp << "\n";
Lang Hames9ff69c82015-04-24 19:11:51 +00002425 this->OutStreamer->EmitRawText(temp.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +00002426}
2427
Benjamin Kramerc321e532016-06-08 19:09:22 +00002428LineReader *NVPTXAsmPrinter::getReader(const std::string &filename) {
Craig Topper062a2ba2014-04-25 05:30:21 +00002429 if (!reader) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002430 reader = new LineReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002431 }
2432
2433 if (reader->fileName() != filename) {
2434 delete reader;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002435 reader = new LineReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002436 }
2437
2438 return reader;
2439}
2440
Justin Holewinski0497ab12013-03-30 14:29:21 +00002441std::string LineReader::readLine(unsigned lineNum) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00002442 if (lineNum < theCurLine) {
2443 theCurLine = 0;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002444 fstr.seekg(0, std::ios::beg);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002445 }
2446 while (theCurLine < lineNum) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002447 fstr.getline(buff, 500);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002448 theCurLine++;
2449 }
2450 return buff;
2451}
2452
2453// Force static initialization.
2454extern "C" void LLVMInitializeNVPTXAsmPrinter() {
Mehdi Aminif42454b2016-10-09 23:00:34 +00002455 RegisterAsmPrinter<NVPTXAsmPrinter> X(getTheNVPTXTarget32());
2456 RegisterAsmPrinter<NVPTXAsmPrinter> Y(getTheNVPTXTarget64());
Justin Holewinskiae556d32012-05-04 20:18:50 +00002457}