For ARM subtargets with useNEONForSinglePrecisionFP, double count uses
[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   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";
113   }
114   return NULL;
115 }
116
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).
120
121   Module::GlobalListType &global_list = M.getGlobalList();
122   int i, n = global_list.size();
123   GlobalVariable **gv_array = new GlobalVariable* [n];
124
125   // first, back-up GlobalVariable in gv_array
126   i = 0;
127   for (Module::global_iterator I = global_list.begin(), E = global_list.end();
128        I != E; ++I)
129     gv_array[i++] = &*I;
130
131   // second, empty global_list
132   while (!global_list.empty())
133     global_list.remove(global_list.begin());
134
135   // call doFinalization
136   bool ret = AsmPrinter::doFinalization(M);
137
138   // now we restore global variables
139   for (i = 0; i < n; i ++)
140     global_list.insert(global_list.end(), gv_array[i]);
141
142   delete[] gv_array;
143   return ret;
144 }
145
146 void PTXAsmPrinter::EmitStartOfAsmFile(Module &M)
147 {
148   OutStreamer.EmitRawText(Twine("\t.version " + OptPTXVersion));
149   OutStreamer.EmitRawText(Twine("\t.target " + OptPTXTarget));
150   OutStreamer.AddBlankLine();
151
152   // declare global variables
153   for (Module::const_global_iterator i = M.global_begin(), e = M.global_end();
154        i != e; ++i)
155     EmitVariableDeclaration(i);
156 }
157
158 bool PTXAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
159   SetupMachineFunction(MF);
160   EmitFunctionDeclaration();
161   EmitFunctionBody();
162   return false;
163 }
164
165 void PTXAsmPrinter::EmitFunctionBodyStart() {
166   OutStreamer.EmitRawText(Twine("{"));
167
168   const PTXMachineFunctionInfo *MFI = MF->getInfo<PTXMachineFunctionInfo>();
169
170   // Print local variable definition
171   for (PTXMachineFunctionInfo::reg_iterator
172        i = MFI->localVarRegBegin(), e = MFI->localVarRegEnd(); i != e; ++ i) {
173     unsigned reg = *i;
174
175     std::string def = "\t.reg .";
176     def += getRegisterTypeName(reg);
177     def += ' ';
178     def += getRegisterName(reg);
179     def += ';';
180     OutStreamer.EmitRawText(Twine(def));
181   }
182 }
183
184 void PTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
185   std::string str;
186   str.reserve(64);
187
188   // Write instruction to str
189   raw_string_ostream OS(str);
190   printInstruction(MI, OS);
191   OS << ';';
192   OS.flush();
193
194   // Replace "%type" if found
195   size_t pos;
196   if ((pos = str.find("%type")) != std::string::npos)
197     str.replace(pos, /*strlen("%type")==*/5, getInstructionTypeName(MI));
198
199   StringRef strref = StringRef(str);
200   OutStreamer.EmitRawText(strref);
201 }
202
203 void PTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
204                                  raw_ostream &OS) {
205   const MachineOperand &MO = MI->getOperand(opNum);
206
207   switch (MO.getType()) {
208     default:
209       llvm_unreachable("<unknown operand type>");
210       break;
211     case MachineOperand::MO_GlobalAddress:
212       OS << *Mang->getSymbol(MO.getGlobal());
213       break;
214     case MachineOperand::MO_Immediate:
215       OS << (int) MO.getImm();
216       break;
217     case MachineOperand::MO_Register:
218       OS << getRegisterName(MO.getReg());
219       break;
220   }
221 }
222
223 void PTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
224                                     raw_ostream &OS, const char *Modifier) {
225   printOperand(MI, opNum, OS);
226
227   if (MI->getOperand(opNum+1).isImm() && MI->getOperand(opNum+1).getImm() == 0)
228     return; // don't print "+0"
229
230   OS << "+";
231   printOperand(MI, opNum+1, OS);
232 }
233
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))
237     return;
238
239   MCSymbol *gvsym = Mang->getSymbol(gv);
240
241   assert(gvsym->isUndefined() && "Cannot define a symbol twice!");
242
243   std::string decl;
244
245   // check if it is defined in some other translation unit
246   if (gv->isDeclaration())
247     decl += ".extern ";
248
249   // state space: e.g., .global
250   decl += ".";
251   decl += getStateSpaceName(gv->getType()->getAddressSpace());
252   decl += " ";
253
254   // alignment (optional)
255   unsigned alignment = gv->getAlignment();
256   if (alignment != 0) {
257     decl += ".align ";
258     decl += utostr(Log2_32(gv->getAlignment()));
259     decl += " ";
260   }
261
262   // TODO: add types
263   decl += ".s32 ";
264
265   decl += gvsym->getName();
266
267   if (ArrayType::classof(gv->getType()) || PointerType::classof(gv->getType()))
268     decl += "[]";
269
270   decl += ";";
271
272   OutStreamer.EmitRawText(Twine(decl));
273
274   OutStreamer.AddBlankLine();
275 }
276
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");
283     return;
284   }
285
286   const PTXMachineFunctionInfo *MFI = MF->getInfo<PTXMachineFunctionInfo>();
287   const bool isKernel = MFI->isKernel();
288   unsigned reg;
289
290   std::string decl = isKernel ? ".entry" : ".func";
291
292   // Print return register
293   reg = MFI->retReg();
294   if (!isKernel && reg != PTX::NoRegister) {
295     decl += " (.reg ."; // FIXME: could it return in .param space?
296     decl += getRegisterTypeName(reg);
297     decl += " ";
298     decl += getRegisterName(reg);
299     decl += ")";
300   }
301
302   // Print function name
303   decl += " ";
304   decl += CurrentFnSym->getName().str();
305
306   // Print parameter list
307   if (!MFI->argRegEmpty()) {
308     decl += " (";
309     if (isKernel) {
310       for (int i = 0, e = MFI->getNumArg(); i != e; ++i) {
311         if (i != 0)
312           decl += ", ";
313         decl += ".param .s32 "; // TODO: add types
314         decl += PARAM_PREFIX;
315         decl += utostr(i + 1);
316       }
317     } else {
318       for (PTXMachineFunctionInfo::reg_iterator
319            i = MFI->argRegBegin(), e = MFI->argRegEnd(), b = i; i != e; ++i) {
320         reg = *i;
321         assert(reg != PTX::NoRegister && "Not a valid register!");
322         if (i != b)
323           decl += ", ";
324         decl += ".reg .";
325         decl += getRegisterTypeName(reg);
326         decl += " ";
327         decl += getRegisterName(reg);
328       }
329     }
330     decl += ")";
331   }
332
333   OutStreamer.EmitRawText(Twine(decl));
334 }
335
336 #include "PTXGenAsmWriter.inc"
337
338 // Force static initialization.
339 extern "C" void LLVMInitializePTXAsmPrinter() {
340   RegisterAsmPrinter<PTXAsmPrinter> X(ThePTXTarget);
341 }