PTX: Add preliminary support for floating-point divide and multiply-and-add
[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/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/Target/Mangler.h"
31 #include "llvm/Target/TargetLoweringObjectFile.h"
32 #include "llvm/Target/TargetRegistry.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38
39 using namespace llvm;
40
41 namespace {
42 class PTXAsmPrinter : public AsmPrinter {
43 public:
44   explicit PTXAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
45     : AsmPrinter(TM, Streamer) {}
46
47   const char *getPassName() const { return "PTX Assembly Printer"; }
48
49   bool doFinalization(Module &M);
50
51   virtual void EmitStartOfAsmFile(Module &M);
52
53   virtual bool runOnMachineFunction(MachineFunction &MF);
54
55   virtual void EmitFunctionBodyStart();
56   virtual void EmitFunctionBodyEnd() { OutStreamer.EmitRawText(Twine("}")); }
57
58   virtual void EmitInstruction(const MachineInstr *MI);
59
60   void printOperand(const MachineInstr *MI, int opNum, raw_ostream &OS);
61   void printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &OS,
62                        const char *Modifier = 0);
63   void printParamOperand(const MachineInstr *MI, int opNum, raw_ostream &OS,
64                          const char *Modifier = 0);
65
66   // autogen'd.
67   void printInstruction(const MachineInstr *MI, raw_ostream &OS);
68   static const char *getRegisterName(unsigned RegNo);
69
70 private:
71   void EmitVariableDeclaration(const GlobalVariable *gv);
72   void EmitFunctionDeclaration();
73 }; // class PTXAsmPrinter
74 } // namespace
75
76 static const char PARAM_PREFIX[] = "__param_";
77
78 static const char *getRegisterTypeName(unsigned RegNo) {
79 #define TEST_REGCLS(cls, clsstr)                \
80   if (PTX::cls ## RegisterClass->contains(RegNo)) return # clsstr;
81   TEST_REGCLS(Preds, pred);
82   TEST_REGCLS(RRegu16, u16);
83   TEST_REGCLS(RRegu32, u32);
84   TEST_REGCLS(RRegu64, u64);
85   TEST_REGCLS(RRegf32, f32);
86   TEST_REGCLS(RRegf64, f64);
87 #undef TEST_REGCLS
88
89   llvm_unreachable("Not in any register class!");
90   return NULL;
91 }
92
93 static const char *getInstructionTypeName(const MachineInstr *MI) {
94   for (int i = 0, e = MI->getNumOperands(); i != e; ++i) {
95     const MachineOperand &MO = MI->getOperand(i);
96     if (MO.getType() == MachineOperand::MO_Register)
97       return getRegisterTypeName(MO.getReg());
98   }
99
100   llvm_unreachable("No reg operand found in instruction!");
101   return NULL;
102 }
103
104 static const char *getStateSpaceName(unsigned addressSpace) {
105   switch (addressSpace) {
106   default: llvm_unreachable("Unknown state space");
107   case PTX::GLOBAL:    return "global";
108   case PTX::CONSTANT:  return "const";
109   case PTX::LOCAL:     return "local";
110   case PTX::PARAMETER: return "param";
111   case PTX::SHARED:    return "shared";
112   }
113   return NULL;
114 }
115
116 static const char *getTypeName(const Type* type) {
117   while (true) {
118     switch (type->getTypeID()) {
119       default: llvm_unreachable("Unknown type");
120       case Type::FloatTyID: return ".f32";
121       case Type::DoubleTyID: return ".f64";
122       case Type::IntegerTyID:
123         switch (type->getPrimitiveSizeInBits()) {
124           default: llvm_unreachable("Unknown integer bit-width");
125           case 16: return ".u16";
126           case 32: return ".u32";
127           case 64: return ".u64";
128         }
129       case Type::ArrayTyID:
130       case Type::PointerTyID:
131         type = dyn_cast<const SequentialType>(type)->getElementType();
132         break;
133     }
134   }
135   return NULL;
136 }
137
138 bool PTXAsmPrinter::doFinalization(Module &M) {
139   // XXX Temproarily remove global variables so that doFinalization() will not
140   // emit them again (global variables are emitted at beginning).
141
142   Module::GlobalListType &global_list = M.getGlobalList();
143   int i, n = global_list.size();
144   GlobalVariable **gv_array = new GlobalVariable* [n];
145
146   // first, back-up GlobalVariable in gv_array
147   i = 0;
148   for (Module::global_iterator I = global_list.begin(), E = global_list.end();
149        I != E; ++I)
150     gv_array[i++] = &*I;
151
152   // second, empty global_list
153   while (!global_list.empty())
154     global_list.remove(global_list.begin());
155
156   // call doFinalization
157   bool ret = AsmPrinter::doFinalization(M);
158
159   // now we restore global variables
160   for (i = 0; i < n; i ++)
161     global_list.insert(global_list.end(), gv_array[i]);
162
163   delete[] gv_array;
164   return ret;
165 }
166
167 void PTXAsmPrinter::EmitStartOfAsmFile(Module &M)
168 {
169   const PTXSubtarget& ST = TM.getSubtarget<PTXSubtarget>();
170
171   OutStreamer.EmitRawText(Twine("\t.version " + ST.getPTXVersionString()));
172   OutStreamer.EmitRawText(Twine("\t.target " + ST.getTargetString() +
173                                 (ST.supportsDouble() ? ""
174                                                      : ", map_f64_to_f32")));
175   OutStreamer.AddBlankLine();
176
177   // declare global variables
178   for (Module::const_global_iterator i = M.global_begin(), e = M.global_end();
179        i != e; ++i)
180     EmitVariableDeclaration(i);
181 }
182
183 bool PTXAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
184   SetupMachineFunction(MF);
185   EmitFunctionDeclaration();
186   EmitFunctionBody();
187   return false;
188 }
189
190 void PTXAsmPrinter::EmitFunctionBodyStart() {
191   OutStreamer.EmitRawText(Twine("{"));
192
193   const PTXMachineFunctionInfo *MFI = MF->getInfo<PTXMachineFunctionInfo>();
194
195   // Print local variable definition
196   for (PTXMachineFunctionInfo::reg_iterator
197        i = MFI->localVarRegBegin(), e = MFI->localVarRegEnd(); i != e; ++ i) {
198     unsigned reg = *i;
199
200     std::string def = "\t.reg .";
201     def += getRegisterTypeName(reg);
202     def += ' ';
203     def += getRegisterName(reg);
204     def += ';';
205     OutStreamer.EmitRawText(Twine(def));
206   }
207 }
208
209 void PTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
210   std::string str;
211   str.reserve(64);
212
213   // Write instruction to str
214   raw_string_ostream OS(str);
215   printInstruction(MI, OS);
216   OS << ';';
217   OS.flush();
218
219   // Replace "%type" if found
220   size_t pos;
221   if ((pos = str.find("%type")) != std::string::npos)
222     str.replace(pos, /*strlen("%type")==*/5, getInstructionTypeName(MI));
223
224   StringRef strref = StringRef(str);
225   OutStreamer.EmitRawText(strref);
226 }
227
228 void PTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
229                                  raw_ostream &OS) {
230   const MachineOperand &MO = MI->getOperand(opNum);
231
232   switch (MO.getType()) {
233     default:
234       llvm_unreachable("<unknown operand type>");
235       break;
236     case MachineOperand::MO_GlobalAddress:
237       OS << *Mang->getSymbol(MO.getGlobal());
238       break;
239     case MachineOperand::MO_Immediate:
240       OS << (int) MO.getImm();
241       break;
242     case MachineOperand::MO_Register:
243       OS << getRegisterName(MO.getReg());
244       break;
245     case MachineOperand::MO_FPImmediate:
246       APInt constFP = MO.getFPImm()->getValueAPF().bitcastToAPInt();
247       bool  isFloat = MO.getFPImm()->getType()->getTypeID() == Type::FloatTyID;
248       // Emit 0F for 32-bit floats and 0D for 64-bit doubles.
249       if (isFloat) {
250         OS << "0F";
251       }
252       else {
253         OS << "0D";
254       }
255       // Emit the encoded floating-point value.
256       if (constFP.getZExtValue() > 0) {
257         OS << constFP.toString(16, false);
258       }
259       else {
260         OS << "00000000";
261         // If We have a double-precision zero, pad to 8-bytes.
262         if (!isFloat) {
263           OS << "00000000";
264         }
265       }
266       break;
267   }
268 }
269
270 void PTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
271                                     raw_ostream &OS, const char *Modifier) {
272   printOperand(MI, opNum, OS);
273
274   if (MI->getOperand(opNum+1).isImm() && MI->getOperand(opNum+1).getImm() == 0)
275     return; // don't print "+0"
276
277   OS << "+";
278   printOperand(MI, opNum+1, OS);
279 }
280
281 void PTXAsmPrinter::printParamOperand(const MachineInstr *MI, int opNum,
282                                       raw_ostream &OS, const char *Modifier) {
283   OS << PARAM_PREFIX << (int) MI->getOperand(opNum).getImm() + 1;
284 }
285
286 void PTXAsmPrinter::EmitVariableDeclaration(const GlobalVariable *gv) {
287   // Check to see if this is a special global used by LLVM, if so, emit it.
288   if (EmitSpecialLLVMGlobal(gv))
289     return;
290
291   MCSymbol *gvsym = Mang->getSymbol(gv);
292
293   assert(gvsym->isUndefined() && "Cannot define a symbol twice!");
294
295   std::string decl;
296
297   // check if it is defined in some other translation unit
298   if (gv->isDeclaration())
299     decl += ".extern ";
300
301   // state space: e.g., .global
302   decl += ".";
303   decl += getStateSpaceName(gv->getType()->getAddressSpace());
304   decl += " ";
305
306   // alignment (optional)
307   unsigned alignment = gv->getAlignment();
308   if (alignment != 0) {
309     decl += ".align ";
310     decl += utostr(Log2_32(gv->getAlignment()));
311     decl += " ";
312   }
313
314   decl += getTypeName(gv->getType());
315   decl += " ";
316
317   decl += gvsym->getName();
318
319   if (ArrayType::classof(gv->getType()) || PointerType::classof(gv->getType()))
320     decl += "[]";
321
322   decl += ";";
323
324   OutStreamer.EmitRawText(Twine(decl));
325
326   OutStreamer.AddBlankLine();
327 }
328
329 void PTXAsmPrinter::EmitFunctionDeclaration() {
330   // The function label could have already been emitted if two symbols end up
331   // conflicting due to asm renaming.  Detect this and emit an error.
332   if (!CurrentFnSym->isUndefined()) {
333     report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
334                        "' label emitted multiple times to assembly file");
335     return;
336   }
337
338   const PTXMachineFunctionInfo *MFI = MF->getInfo<PTXMachineFunctionInfo>();
339   const bool isKernel = MFI->isKernel();
340   unsigned reg;
341
342   std::string decl = isKernel ? ".entry" : ".func";
343
344   // Print return register
345   reg = MFI->retReg();
346   if (!isKernel && reg != PTX::NoRegister) {
347     decl += " (.reg ."; // FIXME: could it return in .param space?
348     decl += getRegisterTypeName(reg);
349     decl += " ";
350     decl += getRegisterName(reg);
351     decl += ")";
352   }
353
354   // Print function name
355   decl += " ";
356   decl += CurrentFnSym->getName().str();
357
358   // Print parameter list
359   if (!MFI->argRegEmpty()) {
360     decl += " (";
361     if (isKernel) {
362       unsigned cnt = 0;
363       //for (int i = 0, e = MFI->getNumArg(); i != e; ++i) {
364       for(PTXMachineFunctionInfo::reg_reverse_iterator
365           i = MFI->argRegReverseBegin(), e = MFI->argRegReverseEnd(), b = i;
366           i != e; ++i) {
367         reg = *i;
368         assert(reg != PTX::NoRegister && "Not a valid register!");
369         if (i != b)
370           decl += ", ";
371         decl += ".param .";
372         decl += getRegisterTypeName(reg);
373         decl += " ";
374         decl += PARAM_PREFIX;
375         decl += utostr(++cnt);
376       }
377     } else {
378       for (PTXMachineFunctionInfo::reg_reverse_iterator
379            i = MFI->argRegReverseBegin(), e = MFI->argRegReverseEnd(), b = i;
380            i != e; ++i) {
381         reg = *i;
382         assert(reg != PTX::NoRegister && "Not a valid register!");
383         if (i != b)
384           decl += ", ";
385         decl += ".reg .";
386         decl += getRegisterTypeName(reg);
387         decl += " ";
388         decl += getRegisterName(reg);
389       }
390     }
391     decl += ")";
392   }
393
394   OutStreamer.EmitRawText(Twine(decl));
395 }
396
397 #include "PTXGenAsmWriter.inc"
398
399 // Force static initialization.
400 extern "C" void LLVMInitializePTXAsmPrinter() {
401   RegisterAsmPrinter<PTXAsmPrinter> X(ThePTXTarget);
402 }