ptx: add ld instruction and test
[oota-llvm.git] / lib / Target / PTX / PTXAsmPrinter.cpp
1 //===-- PTXAsmPrinter.cpp - PTX 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 PTX assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "ptx-asm-printer"
16
17 #include "PTX.h"
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"
37
38 using namespace llvm;
39
40 static cl::opt<std::string>
41 OptPTXVersion("ptx-version", cl::desc("Set PTX version"),
42            cl::init("1.4"));
43
44 static cl::opt<std::string>
45 OptPTXTarget("ptx-target", cl::desc("Set GPU target (comma-separated list)"),
46            cl::init("sm_10"));
47
48 namespace {
49 class PTXAsmPrinter : public AsmPrinter {
50 public:
51   explicit PTXAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
52     : AsmPrinter(TM, Streamer) {}
53
54   const char *getPassName() const { return "PTX Assembly Printer"; }
55
56   bool doFinalization(Module &M);
57
58   virtual void EmitStartOfAsmFile(Module &M);
59
60   virtual bool runOnMachineFunction(MachineFunction &MF);
61
62   virtual void EmitFunctionBodyStart();
63   virtual void EmitFunctionBodyEnd() { OutStreamer.EmitRawText(Twine("}")); }
64
65   virtual void EmitInstruction(const MachineInstr *MI);
66
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);
70
71   // autogen'd.
72   void printInstruction(const MachineInstr *MI, raw_ostream &OS);
73   static const char *getRegisterName(unsigned RegNo);
74
75 private:
76   void EmitVariableDeclaration(const GlobalVariable *gv);
77   void EmitFunctionDeclaration();
78 }; // class PTXAsmPrinter
79 } // namespace
80
81 static const char PARAM_PREFIX[] = "__param_";
82
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);
88 #undef TEST_REGCLS
89
90   llvm_unreachable("Not in any register class!");
91   return NULL;
92 }
93
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());
99   }
100
101   llvm_unreachable("No reg operand found in instruction!");
102   return NULL;
103 }
104
105 static const char *getStateSpaceName(unsigned addressSpace) {
106   if (addressSpace <= 255)
107     return "global";
108   // TODO Add more state spaces
109
110   llvm_unreachable("Unknown state space");
111   return NULL;
112 }
113
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).
117
118   Module::GlobalListType &global_list = M.getGlobalList();
119   int i, n = global_list.size();
120   GlobalVariable **gv_array = new GlobalVariable* [n];
121
122   // first, back-up GlobalVariable in gv_array
123   i = 0;
124   for (Module::global_iterator I = global_list.begin(), E = global_list.end();
125        I != E; ++I)
126     gv_array[i++] = &*I;
127
128   // second, empty global_list
129   while (!global_list.empty())
130     global_list.remove(global_list.begin());
131
132   // call doFinalization
133   bool ret = AsmPrinter::doFinalization(M);
134
135   // now we restore global variables
136   for (i = 0; i < n; i ++)
137     global_list.insert(global_list.end(), gv_array[i]);
138
139   delete[] gv_array;
140   return ret;
141 }
142
143 void PTXAsmPrinter::EmitStartOfAsmFile(Module &M)
144 {
145   OutStreamer.EmitRawText(Twine("\t.version " + OptPTXVersion));
146   OutStreamer.EmitRawText(Twine("\t.target " + OptPTXTarget));
147   OutStreamer.AddBlankLine();
148
149   // declare global variables
150   for (Module::const_global_iterator i = M.global_begin(), e = M.global_end();
151        i != e; ++i)
152     EmitVariableDeclaration(i);
153 }
154
155 bool PTXAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
156   SetupMachineFunction(MF);
157   EmitFunctionDeclaration();
158   EmitFunctionBody();
159   return false;
160 }
161
162 void PTXAsmPrinter::EmitFunctionBodyStart() {
163   OutStreamer.EmitRawText(Twine("{"));
164
165   const PTXMachineFunctionInfo *MFI = MF->getInfo<PTXMachineFunctionInfo>();
166
167   // Print local variable definition
168   for (PTXMachineFunctionInfo::reg_iterator
169        i = MFI->localVarRegBegin(), e = MFI->localVarRegEnd(); i != e; ++ i) {
170     unsigned reg = *i;
171
172     std::string def = "\t.reg .";
173     def += getRegisterTypeName(reg);
174     def += ' ';
175     def += getRegisterName(reg);
176     def += ';';
177     OutStreamer.EmitRawText(Twine(def));
178   }
179 }
180
181 void PTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
182   std::string str;
183   str.reserve(64);
184
185   // Write instruction to str
186   raw_string_ostream OS(str);
187   printInstruction(MI, OS);
188   OS << ';';
189   OS.flush();
190
191   // Replace "%type" if found
192   size_t pos;
193   if ((pos = str.find("%type")) != std::string::npos)
194     str.replace(pos, /*strlen("%type")==*/5, getInstructionTypeName(MI));
195
196   StringRef strref = StringRef(str);
197   OutStreamer.EmitRawText(strref);
198 }
199
200 void PTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
201                                  raw_ostream &OS) {
202   const MachineOperand &MO = MI->getOperand(opNum);
203
204   switch (MO.getType()) {
205     default:
206       llvm_unreachable("<unknown operand type>");
207       break;
208     case MachineOperand::MO_GlobalAddress:
209       OS << *Mang->getSymbol(MO.getGlobal());
210       break;
211     case MachineOperand::MO_Immediate:
212       OS << (int) MO.getImm();
213       break;
214     case MachineOperand::MO_Register:
215       OS << getRegisterName(MO.getReg());
216       break;
217   }
218 }
219
220 void PTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
221                                     raw_ostream &OS, const char *Modifier) {
222   printOperand(MI, opNum, OS);
223
224   if (MI->getOperand(opNum+1).isImm() && MI->getOperand(opNum+1).getImm() == 0)
225     return; // don't print "+0"
226
227   OS << "+";
228   printOperand(MI, opNum+1, OS);
229 }
230
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))
234     return;
235
236   MCSymbol *gvsym = Mang->getSymbol(gv);
237
238   assert(gvsym->isUndefined() && "Cannot define a symbol twice!");
239
240   std::string decl;
241
242   // check if it is defined in some other translation unit
243   if (gv->isDeclaration())
244     decl += ".extern ";
245
246   // state space: e.g., .global
247   decl += ".";
248   decl += getStateSpaceName(gv->getType()->getAddressSpace());
249   decl += " ";
250
251   // alignment (optional)
252   unsigned alignment = gv->getAlignment();
253   if (alignment != 0) {
254     decl += ".align ";
255     decl += utostr(Log2_32(gv->getAlignment()));
256     decl += " ";
257   }
258
259   // TODO: add types
260   decl += ".s32 ";
261
262   decl += gvsym->getName();
263
264   if (ArrayType::classof(gv->getType()) || PointerType::classof(gv->getType()))
265     decl += "[]";
266
267   decl += ";";
268
269   OutStreamer.EmitRawText(Twine(decl));
270
271   OutStreamer.AddBlankLine();
272 }
273
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");
280     return;
281   }
282
283   const PTXMachineFunctionInfo *MFI = MF->getInfo<PTXMachineFunctionInfo>();
284   const bool isKernel = MFI->isKernel();
285   unsigned reg;
286
287   std::string decl = isKernel ? ".entry" : ".func";
288
289   // Print return register
290   reg = MFI->retReg();
291   if (!isKernel && reg != PTX::NoRegister) {
292     decl += " (.reg ."; // FIXME: could it return in .param space?
293     decl += getRegisterTypeName(reg);
294     decl += " ";
295     decl += getRegisterName(reg);
296     decl += ")";
297   }
298
299   // Print function name
300   decl += " ";
301   decl += CurrentFnSym->getName().str();
302
303   // Print parameter list
304   if (!MFI->argRegEmpty()) {
305     decl += " (";
306     if (isKernel) {
307       for (int i = 0, e = MFI->getNumArg(); i != e; ++i) {
308         if (i != 0)
309           decl += ", ";
310         decl += ".param .s32 "; // TODO: add types
311         decl += PARAM_PREFIX;
312         decl += utostr(i + 1);
313       }
314     } else {
315       for (PTXMachineFunctionInfo::reg_iterator
316            i = MFI->argRegBegin(), e = MFI->argRegEnd(), b = i; i != e; ++i) {
317         reg = *i;
318         assert(reg != PTX::NoRegister && "Not a valid register!");
319         if (i != b)
320           decl += ", ";
321         decl += ".reg .";
322         decl += getRegisterTypeName(reg);
323         decl += " ";
324         decl += getRegisterName(reg);
325       }
326     }
327     decl += ")";
328   }
329
330   OutStreamer.EmitRawText(Twine(decl));
331 }
332
333 #include "PTXGenAsmWriter.inc"
334
335 // Force static initialization.
336 extern "C" void LLVMInitializePTXAsmPrinter() {
337   RegisterAsmPrinter<PTXAsmPrinter> X(ThePTXTarget);
338 }