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 if (addressSpace <= 255)
108 // TODO Add more state spaces
110 llvm_unreachable("Unknown state space");
114 bool PTXAsmPrinter::doFinalization(Module &M) {
115 // XXX Temproarily remove global variables so that doFinalization() will not
116 // emit them again (global variables are emitted at beginning).
118 Module::GlobalListType &global_list = M.getGlobalList();
119 int i, n = global_list.size();
120 GlobalVariable **gv_array = new GlobalVariable* [n];
122 // first, back-up GlobalVariable in gv_array
124 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
128 // second, empty global_list
129 while (!global_list.empty())
130 global_list.remove(global_list.begin());
132 // call doFinalization
133 bool ret = AsmPrinter::doFinalization(M);
135 // now we restore global variables
136 for (i = 0; i < n; i ++)
137 global_list.insert(global_list.end(), gv_array[i]);
143 void PTXAsmPrinter::EmitStartOfAsmFile(Module &M)
145 OutStreamer.EmitRawText(Twine("\t.version " + OptPTXVersion));
146 OutStreamer.EmitRawText(Twine("\t.target " + OptPTXTarget));
147 OutStreamer.AddBlankLine();
149 // declare global variables
150 for (Module::const_global_iterator i = M.global_begin(), e = M.global_end();
152 EmitVariableDeclaration(i);
155 bool PTXAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
156 SetupMachineFunction(MF);
157 EmitFunctionDeclaration();
162 void PTXAsmPrinter::EmitFunctionBodyStart() {
163 OutStreamer.EmitRawText(Twine("{"));
165 const PTXMachineFunctionInfo *MFI = MF->getInfo<PTXMachineFunctionInfo>();
167 // Print local variable definition
168 for (PTXMachineFunctionInfo::reg_iterator
169 i = MFI->localVarRegBegin(), e = MFI->localVarRegEnd(); i != e; ++ i) {
172 std::string def = "\t.reg .";
173 def += getRegisterTypeName(reg);
175 def += getRegisterName(reg);
177 OutStreamer.EmitRawText(Twine(def));
181 void PTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
185 // Write instruction to str
186 raw_string_ostream OS(str);
187 printInstruction(MI, OS);
191 // Replace "%type" if found
193 if ((pos = str.find("%type")) != std::string::npos)
194 str.replace(pos, /*strlen("%type")==*/5, getInstructionTypeName(MI));
196 StringRef strref = StringRef(str);
197 OutStreamer.EmitRawText(strref);
200 void PTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
202 const MachineOperand &MO = MI->getOperand(opNum);
204 switch (MO.getType()) {
206 llvm_unreachable("<unknown operand type>");
208 case MachineOperand::MO_GlobalAddress:
209 OS << *Mang->getSymbol(MO.getGlobal());
211 case MachineOperand::MO_Immediate:
212 OS << (int) MO.getImm();
214 case MachineOperand::MO_Register:
215 OS << getRegisterName(MO.getReg());
220 void PTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
221 raw_ostream &OS, const char *Modifier) {
222 printOperand(MI, opNum, OS);
224 if (MI->getOperand(opNum+1).isImm() && MI->getOperand(opNum+1).getImm() == 0)
225 return; // don't print "+0"
228 printOperand(MI, opNum+1, OS);
231 void PTXAsmPrinter::EmitVariableDeclaration(const GlobalVariable *gv) {
232 // Check to see if this is a special global used by LLVM, if so, emit it.
233 if (EmitSpecialLLVMGlobal(gv))
236 MCSymbol *gvsym = Mang->getSymbol(gv);
238 assert(gvsym->isUndefined() && "Cannot define a symbol twice!");
242 // check if it is defined in some other translation unit
243 if (gv->isDeclaration())
246 // state space: e.g., .global
248 decl += getStateSpaceName(gv->getType()->getAddressSpace());
251 // alignment (optional)
252 unsigned alignment = gv->getAlignment();
253 if (alignment != 0) {
255 decl += utostr(Log2_32(gv->getAlignment()));
262 decl += gvsym->getName();
264 if (ArrayType::classof(gv->getType()) || PointerType::classof(gv->getType()))
269 OutStreamer.EmitRawText(Twine(decl));
271 OutStreamer.AddBlankLine();
274 void PTXAsmPrinter::EmitFunctionDeclaration() {
275 // The function label could have already been emitted if two symbols end up
276 // conflicting due to asm renaming. Detect this and emit an error.
277 if (!CurrentFnSym->isUndefined()) {
278 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
279 "' label emitted multiple times to assembly file");
283 const PTXMachineFunctionInfo *MFI = MF->getInfo<PTXMachineFunctionInfo>();
284 const bool isKernel = MFI->isKernel();
287 std::string decl = isKernel ? ".entry" : ".func";
289 // Print return register
291 if (!isKernel && reg != PTX::NoRegister) {
292 decl += " (.reg ."; // FIXME: could it return in .param space?
293 decl += getRegisterTypeName(reg);
295 decl += getRegisterName(reg);
299 // Print function name
301 decl += CurrentFnSym->getName().str();
303 // Print parameter list
304 if (!MFI->argRegEmpty()) {
307 for (int i = 0, e = MFI->getNumArg(); i != e; ++i) {
310 decl += ".param .s32 "; // TODO: add types
311 decl += PARAM_PREFIX;
312 decl += utostr(i + 1);
315 for (PTXMachineFunctionInfo::reg_iterator
316 i = MFI->argRegBegin(), e = MFI->argRegEnd(), b = i; i != e; ++i) {
318 assert(reg != PTX::NoRegister && "Not a valid register!");
322 decl += getRegisterTypeName(reg);
324 decl += getRegisterName(reg);
330 OutStreamer.EmitRawText(Twine(decl));
333 #include "PTXGenAsmWriter.inc"
335 // Force static initialization.
336 extern "C" void LLVMInitializePTXAsmPrinter() {
337 RegisterAsmPrinter<PTXAsmPrinter> X(ThePTXTarget);