1 //===-- PTXAsmPrinter.cpp - PTX LLVM assembly writer ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to PTX assembly language.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "ptx-asm-printer"
18 #include "PTXMachineFunctionInfo.h"
19 #include "PTXTargetMachine.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Module.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/CodeGen/AsmPrinter.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/Target/Mangler.h"
30 #include "llvm/Target/TargetLoweringObjectFile.h"
31 #include "llvm/Target/TargetRegistry.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
40 static cl::opt<std::string>
41 OptPTXVersion("ptx-version", cl::desc("Set PTX version"),
44 static cl::opt<std::string>
45 OptPTXTarget("ptx-target", cl::desc("Set GPU target (comma-separated list)"),
49 class PTXAsmPrinter : public AsmPrinter {
51 explicit PTXAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
52 : AsmPrinter(TM, Streamer) {}
54 const char *getPassName() const { return "PTX Assembly Printer"; }
56 bool doFinalization(Module &M);
58 virtual void EmitStartOfAsmFile(Module &M);
60 virtual bool runOnMachineFunction(MachineFunction &MF);
62 virtual void EmitFunctionBodyStart();
63 virtual void EmitFunctionBodyEnd() { OutStreamer.EmitRawText(Twine("}")); }
65 virtual void EmitInstruction(const MachineInstr *MI);
67 void printOperand(const MachineInstr *MI, int opNum, raw_ostream &OS);
68 void printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &OS,
69 const char *Modifier = 0);
72 void printInstruction(const MachineInstr *MI, raw_ostream &OS);
73 static const char *getRegisterName(unsigned RegNo);
76 void EmitVariableDeclaration(const GlobalVariable *gv);
77 void EmitFunctionDeclaration();
78 }; // class PTXAsmPrinter
81 static const char PARAM_PREFIX[] = "__param_";
83 static const char *getRegisterTypeName(unsigned RegNo) {
84 #define TEST_REGCLS(cls, clsstr) \
85 if (PTX::cls ## RegisterClass->contains(RegNo)) return # clsstr;
86 TEST_REGCLS(RRegs32, s32);
87 TEST_REGCLS(Preds, pred);
90 llvm_unreachable("Not in any register class!");
94 static const char *getInstructionTypeName(const MachineInstr *MI) {
95 for (int i = 0, e = MI->getNumOperands(); i != e; ++i) {
96 const MachineOperand &MO = MI->getOperand(i);
97 if (MO.getType() == MachineOperand::MO_Register)
98 return getRegisterTypeName(MO.getReg());
101 llvm_unreachable("No reg operand found in instruction!");
105 static const char *getStateSpaceName(unsigned addressSpace) {
106 switch (addressSpace) {
107 default: llvm_unreachable("Unknown state space");
108 case PTX::GLOBAL: return "global";
109 case PTX::CONSTANT: return "const";
110 case PTX::LOCAL: return "local";
111 case PTX::PARAMETER: return "param";
112 case PTX::SHARED: return "shared";
117 bool PTXAsmPrinter::doFinalization(Module &M) {
118 // XXX Temproarily remove global variables so that doFinalization() will not
119 // emit them again (global variables are emitted at beginning).
121 Module::GlobalListType &global_list = M.getGlobalList();
122 int i, n = global_list.size();
123 GlobalVariable **gv_array = new GlobalVariable* [n];
125 // first, back-up GlobalVariable in gv_array
127 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
131 // second, empty global_list
132 while (!global_list.empty())
133 global_list.remove(global_list.begin());
135 // call doFinalization
136 bool ret = AsmPrinter::doFinalization(M);
138 // now we restore global variables
139 for (i = 0; i < n; i ++)
140 global_list.insert(global_list.end(), gv_array[i]);
146 void PTXAsmPrinter::EmitStartOfAsmFile(Module &M)
148 OutStreamer.EmitRawText(Twine("\t.version " + OptPTXVersion));
149 OutStreamer.EmitRawText(Twine("\t.target " + OptPTXTarget));
150 OutStreamer.AddBlankLine();
152 // declare global variables
153 for (Module::const_global_iterator i = M.global_begin(), e = M.global_end();
155 EmitVariableDeclaration(i);
158 bool PTXAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
159 SetupMachineFunction(MF);
160 EmitFunctionDeclaration();
165 void PTXAsmPrinter::EmitFunctionBodyStart() {
166 OutStreamer.EmitRawText(Twine("{"));
168 const PTXMachineFunctionInfo *MFI = MF->getInfo<PTXMachineFunctionInfo>();
170 // Print local variable definition
171 for (PTXMachineFunctionInfo::reg_iterator
172 i = MFI->localVarRegBegin(), e = MFI->localVarRegEnd(); i != e; ++ i) {
175 std::string def = "\t.reg .";
176 def += getRegisterTypeName(reg);
178 def += getRegisterName(reg);
180 OutStreamer.EmitRawText(Twine(def));
184 void PTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
188 // Write instruction to str
189 raw_string_ostream OS(str);
190 printInstruction(MI, OS);
194 // Replace "%type" if found
196 if ((pos = str.find("%type")) != std::string::npos)
197 str.replace(pos, /*strlen("%type")==*/5, getInstructionTypeName(MI));
199 StringRef strref = StringRef(str);
200 OutStreamer.EmitRawText(strref);
203 void PTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
205 const MachineOperand &MO = MI->getOperand(opNum);
207 switch (MO.getType()) {
209 llvm_unreachable("<unknown operand type>");
211 case MachineOperand::MO_GlobalAddress:
212 OS << *Mang->getSymbol(MO.getGlobal());
214 case MachineOperand::MO_Immediate:
215 OS << (int) MO.getImm();
217 case MachineOperand::MO_Register:
218 OS << getRegisterName(MO.getReg());
223 void PTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
224 raw_ostream &OS, const char *Modifier) {
225 printOperand(MI, opNum, OS);
227 if (MI->getOperand(opNum+1).isImm() && MI->getOperand(opNum+1).getImm() == 0)
228 return; // don't print "+0"
231 printOperand(MI, opNum+1, OS);
234 void PTXAsmPrinter::EmitVariableDeclaration(const GlobalVariable *gv) {
235 // Check to see if this is a special global used by LLVM, if so, emit it.
236 if (EmitSpecialLLVMGlobal(gv))
239 MCSymbol *gvsym = Mang->getSymbol(gv);
241 assert(gvsym->isUndefined() && "Cannot define a symbol twice!");
245 // check if it is defined in some other translation unit
246 if (gv->isDeclaration())
249 // state space: e.g., .global
251 decl += getStateSpaceName(gv->getType()->getAddressSpace());
254 // alignment (optional)
255 unsigned alignment = gv->getAlignment();
256 if (alignment != 0) {
258 decl += utostr(Log2_32(gv->getAlignment()));
265 decl += gvsym->getName();
267 if (ArrayType::classof(gv->getType()) || PointerType::classof(gv->getType()))
272 OutStreamer.EmitRawText(Twine(decl));
274 OutStreamer.AddBlankLine();
277 void PTXAsmPrinter::EmitFunctionDeclaration() {
278 // The function label could have already been emitted if two symbols end up
279 // conflicting due to asm renaming. Detect this and emit an error.
280 if (!CurrentFnSym->isUndefined()) {
281 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
282 "' label emitted multiple times to assembly file");
286 const PTXMachineFunctionInfo *MFI = MF->getInfo<PTXMachineFunctionInfo>();
287 const bool isKernel = MFI->isKernel();
290 std::string decl = isKernel ? ".entry" : ".func";
292 // Print return register
294 if (!isKernel && reg != PTX::NoRegister) {
295 decl += " (.reg ."; // FIXME: could it return in .param space?
296 decl += getRegisterTypeName(reg);
298 decl += getRegisterName(reg);
302 // Print function name
304 decl += CurrentFnSym->getName().str();
306 // Print parameter list
307 if (!MFI->argRegEmpty()) {
310 for (int i = 0, e = MFI->getNumArg(); i != e; ++i) {
313 decl += ".param .s32 "; // TODO: add types
314 decl += PARAM_PREFIX;
315 decl += utostr(i + 1);
318 for (PTXMachineFunctionInfo::reg_iterator
319 i = MFI->argRegBegin(), e = MFI->argRegEnd(), b = i; i != e; ++i) {
321 assert(reg != PTX::NoRegister && "Not a valid register!");
325 decl += getRegisterTypeName(reg);
327 decl += getRegisterName(reg);
333 OutStreamer.EmitRawText(Twine(decl));
336 #include "PTXGenAsmWriter.inc"
338 // Force static initialization.
339 extern "C" void LLVMInitializePTXAsmPrinter() {
340 RegisterAsmPrinter<PTXAsmPrinter> X(ThePTXTarget);