Silence wrong warnings from GCC about variables possibly being used
[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 "PTXAsmPrinter.h"
19 #include "PTXMachineFunctionInfo.h"
20 #include "PTXParamManager.h"
21 #include "PTXRegisterInfo.h"
22 #include "PTXTargetMachine.h"
23 #include "llvm/Argument.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Function.h"
26 #include "llvm/Module.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Analysis/DebugInfo.h"
30 #include "llvm/CodeGen/AsmPrinter.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/MC/MCContext.h"
35 #include "llvm/MC/MCExpr.h"
36 #include "llvm/MC/MCInst.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Target/Mangler.h"
40 #include "llvm/Target/TargetLoweringObjectFile.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Support/Path.h"
46 #include "llvm/Support/TargetRegistry.h"
47 #include "llvm/Support/raw_ostream.h"
48
49 using namespace llvm;
50
51 static const char PARAM_PREFIX[] = "__param_";
52 static const char RETURN_PREFIX[] = "__ret_";
53
54 static const char *getRegisterTypeName(unsigned RegNo,
55                                        const MachineRegisterInfo& MRI) {
56   const TargetRegisterClass *TRC = MRI.getRegClass(RegNo);
57
58 #define TEST_REGCLS(cls, clsstr) \
59   if (PTX::cls ## RegisterClass == TRC) return # clsstr;
60
61   TEST_REGCLS(RegPred, pred);
62   TEST_REGCLS(RegI16, b16);
63   TEST_REGCLS(RegI32, b32);
64   TEST_REGCLS(RegI64, b64);
65   TEST_REGCLS(RegF32, b32);
66   TEST_REGCLS(RegF64, b64);
67 #undef TEST_REGCLS
68
69   llvm_unreachable("Not in any register class!");
70   return NULL;
71 }
72
73 static const char *getStateSpaceName(unsigned addressSpace) {
74   switch (addressSpace) {
75   default: llvm_unreachable("Unknown state space");
76   case PTXStateSpace::Global:    return "global";
77   case PTXStateSpace::Constant:  return "const";
78   case PTXStateSpace::Local:     return "local";
79   case PTXStateSpace::Parameter: return "param";
80   case PTXStateSpace::Shared:    return "shared";
81   }
82   return NULL;
83 }
84
85 static const char *getTypeName(Type* type) {
86   while (true) {
87     switch (type->getTypeID()) {
88       default: llvm_unreachable("Unknown type");
89       case Type::FloatTyID: return ".f32";
90       case Type::DoubleTyID: return ".f64";
91       case Type::IntegerTyID:
92         switch (type->getPrimitiveSizeInBits()) {
93           default: llvm_unreachable("Unknown integer bit-width");
94           case 16: return ".u16";
95           case 32: return ".u32";
96           case 64: return ".u64";
97         }
98       case Type::ArrayTyID:
99       case Type::PointerTyID:
100         type = dyn_cast<SequentialType>(type)->getElementType();
101         break;
102     }
103   }
104   return NULL;
105 }
106
107 bool PTXAsmPrinter::doFinalization(Module &M) {
108   // XXX Temproarily remove global variables so that doFinalization() will not
109   // emit them again (global variables are emitted at beginning).
110
111   Module::GlobalListType &global_list = M.getGlobalList();
112   int i, n = global_list.size();
113   GlobalVariable **gv_array = new GlobalVariable* [n];
114
115   // first, back-up GlobalVariable in gv_array
116   i = 0;
117   for (Module::global_iterator I = global_list.begin(), E = global_list.end();
118        I != E; ++I)
119     gv_array[i++] = &*I;
120
121   // second, empty global_list
122   while (!global_list.empty())
123     global_list.remove(global_list.begin());
124
125   // call doFinalization
126   bool ret = AsmPrinter::doFinalization(M);
127
128   // now we restore global variables
129   for (i = 0; i < n; i ++)
130     global_list.insert(global_list.end(), gv_array[i]);
131
132   delete[] gv_array;
133   return ret;
134 }
135
136 void PTXAsmPrinter::EmitStartOfAsmFile(Module &M)
137 {
138   const PTXSubtarget& ST = TM.getSubtarget<PTXSubtarget>();
139
140   // Emit the PTX .version and .target attributes
141   OutStreamer.EmitRawText(Twine("\t.version ") + ST.getPTXVersionString());
142   OutStreamer.EmitRawText(Twine("\t.target ") + ST.getTargetString() +
143                                 (ST.supportsDouble() ? ""
144                                                      : ", map_f64_to_f32"));
145   // .address_size directive is optional, but it must immediately follow
146   // the .target directive if present within a module
147   if (ST.supportsPTX23()) {
148     const char *addrSize = ST.is64Bit() ? "64" : "32";
149     OutStreamer.EmitRawText(Twine("\t.address_size ") + addrSize);
150   }
151
152   OutStreamer.AddBlankLine();
153
154   // Define any .file directives
155   DebugInfoFinder DbgFinder;
156   DbgFinder.processModule(M);
157
158   for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
159        E = DbgFinder.compile_unit_end(); I != E; ++I) {
160     DICompileUnit DIUnit(*I);
161     StringRef FN = DIUnit.getFilename();
162     StringRef Dir = DIUnit.getDirectory();
163     GetOrCreateSourceID(FN, Dir);
164   }
165
166   OutStreamer.AddBlankLine();
167
168   // declare external functions
169   for (Module::const_iterator i = M.begin(), e = M.end();
170        i != e; ++i)
171     EmitFunctionDeclaration(i);
172   
173   // declare global variables
174   for (Module::const_global_iterator i = M.global_begin(), e = M.global_end();
175        i != e; ++i)
176     EmitVariableDeclaration(i);
177 }
178
179 void PTXAsmPrinter::EmitFunctionBodyStart() {
180   OutStreamer.EmitRawText(Twine("{"));
181
182   const PTXMachineFunctionInfo *MFI = MF->getInfo<PTXMachineFunctionInfo>();
183   const PTXParamManager &PM = MFI->getParamManager();
184
185   // Print register definitions
186   SmallString<128> regDefs;
187   raw_svector_ostream os(regDefs);
188   unsigned numRegs;
189
190   // pred
191   numRegs = MFI->getNumRegistersForClass(PTX::RegPredRegisterClass);
192   if(numRegs > 0)
193     os << "\t.reg .pred %p<" << numRegs << ">;\n";
194
195   // i16
196   numRegs = MFI->getNumRegistersForClass(PTX::RegI16RegisterClass);
197   if(numRegs > 0)
198     os << "\t.reg .b16 %rh<" << numRegs << ">;\n";
199
200   // i32
201   numRegs = MFI->getNumRegistersForClass(PTX::RegI32RegisterClass);
202   if(numRegs > 0)
203     os << "\t.reg .b32 %r<" << numRegs << ">;\n";
204
205   // i64
206   numRegs = MFI->getNumRegistersForClass(PTX::RegI64RegisterClass);
207   if(numRegs > 0)
208     os << "\t.reg .b64 %rd<" << numRegs << ">;\n";
209
210   // f32
211   numRegs = MFI->getNumRegistersForClass(PTX::RegF32RegisterClass);
212   if(numRegs > 0)
213     os << "\t.reg .f32 %f<" << numRegs << ">;\n";
214
215   // f64
216   numRegs = MFI->getNumRegistersForClass(PTX::RegF64RegisterClass);
217   if(numRegs > 0)
218     os << "\t.reg .f64 %fd<" << numRegs << ">;\n";
219
220   // Local params
221   for (PTXParamManager::param_iterator i = PM.local_begin(), e = PM.local_end();
222        i != e; ++i)
223     os << "\t.param .b" << PM.getParamSize(*i) << ' ' << PM.getParamName(*i)
224        << ";\n";
225
226   OutStreamer.EmitRawText(os.str());
227
228
229   const MachineFrameInfo* FrameInfo = MF->getFrameInfo();
230   DEBUG(dbgs() << "Have " << FrameInfo->getNumObjects()
231                << " frame object(s)\n");
232   for (unsigned i = 0, e = FrameInfo->getNumObjects(); i != e; ++i) {
233     DEBUG(dbgs() << "Size of object: " << FrameInfo->getObjectSize(i) << "\n");
234     if (FrameInfo->getObjectSize(i) > 0) {
235       OutStreamer.EmitRawText("\t.local .align " +
236                               Twine(FrameInfo->getObjectAlignment(i)) +
237                               " .b8 __local" +
238                               Twine(i) +
239                               "[" +
240                               Twine(FrameInfo->getObjectSize(i)) +
241                               "];");
242     }
243   }
244
245   //unsigned Index = 1;
246   // Print parameter passing params
247   //for (PTXMachineFunctionInfo::param_iterator
248   //     i = MFI->paramBegin(), e = MFI->paramEnd(); i != e; ++i) {
249   //  std::string def = "\t.param .b";
250   //  def += utostr(*i);
251   //  def += " __ret_";
252   //  def += utostr(Index);
253   //  Index++;
254   //  def += ";";
255   //  OutStreamer.EmitRawText(Twine(def));
256   //}
257 }
258
259 void PTXAsmPrinter::EmitFunctionBodyEnd() {
260   OutStreamer.EmitRawText(Twine("}"));
261 }
262
263 void PTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
264   MCInst TmpInst;
265   LowerPTXMachineInstrToMCInst(MI, TmpInst, *this);
266   OutStreamer.EmitInstruction(TmpInst);
267 }
268
269 void PTXAsmPrinter::EmitVariableDeclaration(const GlobalVariable *gv) {
270   // Check to see if this is a special global used by LLVM, if so, emit it.
271   if (EmitSpecialLLVMGlobal(gv))
272     return;
273
274   MCSymbol *gvsym = Mang->getSymbol(gv);
275
276   assert(gvsym->isUndefined() && "Cannot define a symbol twice!");
277
278   SmallString<128> decl;
279   raw_svector_ostream os(decl);
280
281   // check if it is defined in some other translation unit
282   if (gv->isDeclaration())
283     os << ".extern ";
284
285   // state space: e.g., .global
286   os << '.' << getStateSpaceName(gv->getType()->getAddressSpace()) << ' ';
287
288   // alignment (optional)
289   unsigned alignment = gv->getAlignment();
290   if (alignment != 0)
291     os << ".align " << gv->getAlignment() << ' ';
292
293
294   if (PointerType::classof(gv->getType())) {
295     PointerType* pointerTy = dyn_cast<PointerType>(gv->getType());
296     Type* elementTy = pointerTy->getElementType();
297
298     if (elementTy->isArrayTy()) {
299       assert(elementTy->isArrayTy() && "Only pointers to arrays are supported");
300
301       ArrayType* arrayTy = dyn_cast<ArrayType>(elementTy);
302       elementTy = arrayTy->getElementType();
303
304       unsigned numElements = arrayTy->getNumElements();
305
306       while (elementTy->isArrayTy()) {
307         arrayTy = dyn_cast<ArrayType>(elementTy);
308         elementTy = arrayTy->getElementType();
309
310         numElements *= arrayTy->getNumElements();
311       }
312
313       // FIXME: isPrimitiveType() == false for i16?
314       assert(elementTy->isSingleValueType() &&
315              "Non-primitive types are not handled");
316
317       // Find the size of the element in bits
318       unsigned elementSize = elementTy->getPrimitiveSizeInBits();
319
320       os << ".b" << elementSize << ' ' << gvsym->getName()
321          << '[' << numElements << ']';
322     } else {
323       os << ".b8" << gvsym->getName() << "[]";
324     }
325
326     // handle string constants (assume ConstantArray means string)
327     if (gv->hasInitializer()) {
328       const Constant *C = gv->getInitializer();
329       if (const ConstantArray *CA = dyn_cast<ConstantArray>(C)) {
330         os << " = {";
331
332         for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
333           if (i > 0)
334             os << ',';
335
336           os << "0x";
337           os.write_hex(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
338         }
339
340         os << '}';
341       }
342     }
343   } else {
344     // Note: this is currently the fall-through case and most likely generates
345     //       incorrect code.
346     os << getTypeName(gv->getType()) << ' ' << gvsym->getName();
347
348     if (isa<ArrayType>(gv->getType()) || isa<PointerType>(gv->getType()))
349       os << "[]";
350   }
351
352   os << ';';
353
354   OutStreamer.EmitRawText(os.str());
355   OutStreamer.AddBlankLine();
356 }
357
358 void PTXAsmPrinter::EmitFunctionEntryLabel() {
359   // The function label could have already been emitted if two symbols end up
360   // conflicting due to asm renaming.  Detect this and emit an error.
361   if (!CurrentFnSym->isUndefined()) {
362     report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
363                        "' label emitted multiple times to assembly file");
364     return;
365   }
366
367   const PTXMachineFunctionInfo *MFI = MF->getInfo<PTXMachineFunctionInfo>();
368   const PTXParamManager &PM = MFI->getParamManager();
369   const bool isKernel = MFI->isKernel();
370   const PTXSubtarget& ST = TM.getSubtarget<PTXSubtarget>();
371   const MachineRegisterInfo& MRI = MF->getRegInfo();
372
373   SmallString<128> decl;
374   raw_svector_ostream os(decl);
375   os << (isKernel ? ".entry" : ".func");
376
377   if (!isKernel) {
378     os << " (";
379     if (ST.useParamSpaceForDeviceArgs()) {
380       for (PTXParamManager::param_iterator i = PM.ret_begin(), e = PM.ret_end(),
381            b = i; i != e; ++i) {
382         if (i != b)
383           os << ", ";
384
385         os << ".param .b" << PM.getParamSize(*i) << ' ' << PM.getParamName(*i);
386       }
387     } else {
388       for (PTXMachineFunctionInfo::reg_iterator
389            i = MFI->retreg_begin(), e = MFI->retreg_end(), b = i;
390            i != e; ++i) {
391         if (i != b)
392           os << ", ";
393
394         os << ".reg ." << getRegisterTypeName(*i, MRI) << ' '
395            << MFI->getRegisterName(*i);
396       }
397     }
398     os << ')';
399   }
400
401   // Print function name
402   os << ' ' << CurrentFnSym->getName() << " (";
403
404   const Function *F = MF->getFunction();
405
406   // Print parameters
407   if (isKernel || ST.useParamSpaceForDeviceArgs()) {
408     /*for (PTXParamManager::param_iterator i = PM.arg_begin(), e = PM.arg_end(),
409          b = i; i != e; ++i) {
410       if (i != b)
411         os << ", ";
412
413       os << ".param .b" << PM.getParamSize(*i) << ' ' << PM.getParamName(*i);
414     }*/
415     int Counter = 1;
416     for (Function::const_arg_iterator i = F->arg_begin(), e = F->arg_end(),
417          b = i; i != e; ++i) {
418       if (i != b)
419         os << ", ";
420       const Type *ArgType = (*i).getType();
421       os << ".param .b";
422       if (ArgType->isPointerTy()) {
423         if (ST.is64Bit())
424           os << "64";
425         else
426           os << "32";
427       } else {
428         os << ArgType->getPrimitiveSizeInBits();
429       }
430       if (ArgType->isPointerTy() && ST.emitPtrAttribute()) {
431         const PointerType *PtrType = dyn_cast<const PointerType>(ArgType);
432         os << " .ptr";
433         switch (PtrType->getAddressSpace()) {
434         default:
435           llvm_unreachable("Unknown address space in argument");
436         case PTXStateSpace::Global:
437           os << " .global";
438           break;
439         case PTXStateSpace::Shared:
440           os << " .shared";
441           break;
442         }
443       }
444       os << " __param_" << Counter++;
445     }
446   } else {
447     for (PTXMachineFunctionInfo::reg_iterator
448          i = MFI->argreg_begin(), e = MFI->argreg_end(), b = i;
449          i != e; ++i) {
450       if (i != b)
451         os << ", ";
452
453       os << ".reg ." << getRegisterTypeName(*i, MRI) << ' '
454          << MFI->getRegisterName(*i);
455     }
456   }
457   os << ')';
458
459   OutStreamer.EmitRawText(os.str());
460 }
461
462 void PTXAsmPrinter::EmitFunctionDeclaration(const Function* func)
463 {
464   const PTXSubtarget& ST = TM.getSubtarget<PTXSubtarget>();
465         
466   std::string decl = "";
467
468   // hard-coded emission of extern vprintf function 
469   
470   if (func->getName() == "printf" || func->getName() == "puts") {               
471     decl += ".extern .func (.param .b32 __param_1) vprintf (.param .b";
472     if (ST.is64Bit())   
473       decl += "64";
474     else                                
475       decl += "32";
476     decl += " __param_2, .param .b";
477     if (ST.is64Bit())   
478       decl += "64";
479     else                                
480       decl += "32";
481     decl += " __param_3)\n";
482   }
483   
484   OutStreamer.EmitRawText(Twine(decl));
485 }
486
487 unsigned PTXAsmPrinter::GetOrCreateSourceID(StringRef FileName,
488                                             StringRef DirName) {
489   // If FE did not provide a file name, then assume stdin.
490   if (FileName.empty())
491     return GetOrCreateSourceID("<stdin>", StringRef());
492
493   // MCStream expects full path name as filename.
494   if (!DirName.empty() && !sys::path::is_absolute(FileName)) {
495     SmallString<128> FullPathName = DirName;
496     sys::path::append(FullPathName, FileName);
497     // Here FullPathName will be copied into StringMap by GetOrCreateSourceID.
498     return GetOrCreateSourceID(StringRef(FullPathName), StringRef());
499   }
500
501   StringMapEntry<unsigned> &Entry = SourceIdMap.GetOrCreateValue(FileName);
502   if (Entry.getValue())
503     return Entry.getValue();
504
505   unsigned SrcId = SourceIdMap.size();
506   Entry.setValue(SrcId);
507
508   // Print out a .file directive to specify files for .loc directives.
509   OutStreamer.EmitDwarfFileDirective(SrcId, "", Entry.getKey());
510
511   return SrcId;
512 }
513
514 MCOperand PTXAsmPrinter::GetSymbolRef(const MachineOperand &MO,
515                                       const MCSymbol *Symbol) {
516   const MCExpr *Expr;
517   Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None, OutContext);
518   return MCOperand::CreateExpr(Expr);
519 }
520
521 MCOperand PTXAsmPrinter::lowerOperand(const MachineOperand &MO) {
522   MCOperand MCOp;
523   const PTXMachineFunctionInfo *MFI = MF->getInfo<PTXMachineFunctionInfo>();
524   const MCExpr *Expr;
525   const char *RegSymbolName;
526   switch (MO.getType()) {
527   default:
528     llvm_unreachable("Unknown operand type");
529   case MachineOperand::MO_Register:
530     // We create register operands as symbols, since the PTXInstPrinter class
531     // has no way to map virtual registers back to a name without some ugly
532     // hacks.
533     // FIXME: Figure out a better way to handle virtual register naming.
534     RegSymbolName = MFI->getRegisterName(MO.getReg());
535     Expr = MCSymbolRefExpr::Create(RegSymbolName, MCSymbolRefExpr::VK_None,
536                                    OutContext);
537     MCOp = MCOperand::CreateExpr(Expr);
538     break;
539   case MachineOperand::MO_Immediate:
540     MCOp = MCOperand::CreateImm(MO.getImm());
541     break;
542   case MachineOperand::MO_MachineBasicBlock:
543     MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
544                                  MO.getMBB()->getSymbol(), OutContext));
545     break;
546   case MachineOperand::MO_GlobalAddress:
547     MCOp = GetSymbolRef(MO, Mang->getSymbol(MO.getGlobal()));
548     break;
549   case MachineOperand::MO_ExternalSymbol:
550     MCOp = GetSymbolRef(MO, GetExternalSymbolSymbol(MO.getSymbolName()));
551     break;
552   case MachineOperand::MO_FPImmediate:
553     APFloat Val = MO.getFPImm()->getValueAPF();
554     bool ignored;
555     Val.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &ignored);
556     MCOp = MCOperand::CreateFPImm(Val.convertToDouble());
557     break;
558   }
559
560   return MCOp;
561 }
562
563 // Force static initialization.
564 extern "C" void LLVMInitializePTXAsmPrinter() {
565   RegisterAsmPrinter<PTXAsmPrinter> X(ThePTX32Target);
566   RegisterAsmPrinter<PTXAsmPrinter> Y(ThePTX64Target);
567 }