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/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/Target/Mangler.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetRegistry.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
43 class PTXAsmPrinter : public AsmPrinter {
45 explicit PTXAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
46 : AsmPrinter(TM, Streamer) {}
48 const char *getPassName() const { return "PTX Assembly Printer"; }
50 bool doFinalization(Module &M);
52 virtual void EmitStartOfAsmFile(Module &M);
54 virtual bool runOnMachineFunction(MachineFunction &MF);
56 virtual void EmitFunctionBodyStart();
57 virtual void EmitFunctionBodyEnd() { OutStreamer.EmitRawText(Twine("}")); }
59 virtual void EmitInstruction(const MachineInstr *MI);
61 void printOperand(const MachineInstr *MI, int opNum, raw_ostream &OS);
62 void printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &OS,
63 const char *Modifier = 0);
64 void printParamOperand(const MachineInstr *MI, int opNum, raw_ostream &OS,
65 const char *Modifier = 0);
66 void printReturnOperand(const MachineInstr *MI, int opNum, raw_ostream &OS,
67 const char *Modifier = 0);
68 void printPredicateOperand(const MachineInstr *MI, raw_ostream &O);
71 void printInstruction(const MachineInstr *MI, raw_ostream &OS);
72 static const char *getRegisterName(unsigned RegNo);
75 void EmitVariableDeclaration(const GlobalVariable *gv);
76 void EmitFunctionDeclaration();
77 }; // class PTXAsmPrinter
80 static const char PARAM_PREFIX[] = "__param_";
81 static const char RETURN_PREFIX[] = "__ret_";
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(RegPred, pred);
87 TEST_REGCLS(RegI16, b16);
88 TEST_REGCLS(RegI32, b32);
89 TEST_REGCLS(RegI64, b64);
90 TEST_REGCLS(RegF32, b32);
91 TEST_REGCLS(RegF64, b64);
94 llvm_unreachable("Not in any register class!");
98 static const char *getStateSpaceName(unsigned addressSpace) {
99 switch (addressSpace) {
100 default: llvm_unreachable("Unknown state space");
101 case PTX::GLOBAL: return "global";
102 case PTX::CONSTANT: return "const";
103 case PTX::LOCAL: return "local";
104 case PTX::PARAMETER: return "param";
105 case PTX::SHARED: return "shared";
110 static const char *getTypeName(const Type* type) {
112 switch (type->getTypeID()) {
113 default: llvm_unreachable("Unknown type");
114 case Type::FloatTyID: return ".f32";
115 case Type::DoubleTyID: return ".f64";
116 case Type::IntegerTyID:
117 switch (type->getPrimitiveSizeInBits()) {
118 default: llvm_unreachable("Unknown integer bit-width");
119 case 16: return ".u16";
120 case 32: return ".u32";
121 case 64: return ".u64";
123 case Type::ArrayTyID:
124 case Type::PointerTyID:
125 type = dyn_cast<const SequentialType>(type)->getElementType();
132 bool PTXAsmPrinter::doFinalization(Module &M) {
133 // XXX Temproarily remove global variables so that doFinalization() will not
134 // emit them again (global variables are emitted at beginning).
136 Module::GlobalListType &global_list = M.getGlobalList();
137 int i, n = global_list.size();
138 GlobalVariable **gv_array = new GlobalVariable* [n];
140 // first, back-up GlobalVariable in gv_array
142 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
146 // second, empty global_list
147 while (!global_list.empty())
148 global_list.remove(global_list.begin());
150 // call doFinalization
151 bool ret = AsmPrinter::doFinalization(M);
153 // now we restore global variables
154 for (i = 0; i < n; i ++)
155 global_list.insert(global_list.end(), gv_array[i]);
161 void PTXAsmPrinter::EmitStartOfAsmFile(Module &M)
163 const PTXSubtarget& ST = TM.getSubtarget<PTXSubtarget>();
165 OutStreamer.EmitRawText(Twine("\t.version " + ST.getPTXVersionString()));
166 OutStreamer.EmitRawText(Twine("\t.target " + ST.getTargetString() +
167 (ST.supportsDouble() ? ""
168 : ", map_f64_to_f32")));
169 // .address_size directive is optional, but it must immediately follow
170 // the .target directive if present within a module
171 if (ST.supportsPTX23()) {
172 std::string addrSize = ST.is64Bit() ? "64" : "32";
173 OutStreamer.EmitRawText(Twine("\t.address_size " + addrSize));
176 OutStreamer.AddBlankLine();
178 // declare global variables
179 for (Module::const_global_iterator i = M.global_begin(), e = M.global_end();
181 EmitVariableDeclaration(i);
184 bool PTXAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
185 SetupMachineFunction(MF);
186 EmitFunctionDeclaration();
191 void PTXAsmPrinter::EmitFunctionBodyStart() {
192 OutStreamer.EmitRawText(Twine("{"));
194 const PTXMachineFunctionInfo *MFI = MF->getInfo<PTXMachineFunctionInfo>();
196 // Print local variable definition
197 for (PTXMachineFunctionInfo::reg_iterator
198 i = MFI->localVarRegBegin(), e = MFI->localVarRegEnd(); i != e; ++ i) {
201 std::string def = "\t.reg .";
202 def += getRegisterTypeName(reg);
204 def += getRegisterName(reg);
206 OutStreamer.EmitRawText(Twine(def));
209 const MachineFrameInfo* FrameInfo = MF->getFrameInfo();
210 DEBUG(dbgs() << "Have " << FrameInfo->getNumObjects()
211 << " frame object(s)\n");
212 for (unsigned i = 0, e = FrameInfo->getNumObjects(); i != e; ++i) {
213 DEBUG(dbgs() << "Size of object: " << FrameInfo->getObjectSize(i) << "\n");
214 if (FrameInfo->getObjectSize(i) > 0) {
215 std::string def = "\t.reg .b";
216 def += utostr(FrameInfo->getObjectSize(i)*8); // Convert to bits
220 OutStreamer.EmitRawText(Twine(def));
225 void PTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
229 raw_string_ostream OS(str);
232 printPredicateOperand(MI, OS);
234 // Write instruction to str
235 printInstruction(MI, OS);
239 StringRef strref = StringRef(str);
240 OutStreamer.EmitRawText(strref);
243 void PTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
245 const MachineOperand &MO = MI->getOperand(opNum);
247 switch (MO.getType()) {
249 llvm_unreachable("<unknown operand type>");
251 case MachineOperand::MO_GlobalAddress:
252 OS << *Mang->getSymbol(MO.getGlobal());
254 case MachineOperand::MO_Immediate:
255 OS << (long) MO.getImm();
257 case MachineOperand::MO_MachineBasicBlock:
258 OS << *MO.getMBB()->getSymbol();
260 case MachineOperand::MO_Register:
261 OS << getRegisterName(MO.getReg());
263 case MachineOperand::MO_FPImmediate:
264 APInt constFP = MO.getFPImm()->getValueAPF().bitcastToAPInt();
265 bool isFloat = MO.getFPImm()->getType()->getTypeID() == Type::FloatTyID;
266 // Emit 0F for 32-bit floats and 0D for 64-bit doubles.
273 // Emit the encoded floating-point value.
274 if (constFP.getZExtValue() > 0) {
275 OS << constFP.toString(16, false);
279 // If We have a double-precision zero, pad to 8-bytes.
288 void PTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
289 raw_ostream &OS, const char *Modifier) {
290 printOperand(MI, opNum, OS);
292 if (MI->getOperand(opNum+1).isImm() && MI->getOperand(opNum+1).getImm() == 0)
293 return; // don't print "+0"
296 printOperand(MI, opNum+1, OS);
299 void PTXAsmPrinter::printParamOperand(const MachineInstr *MI, int opNum,
300 raw_ostream &OS, const char *Modifier) {
301 OS << PARAM_PREFIX << (int) MI->getOperand(opNum).getImm() + 1;
304 void PTXAsmPrinter::printReturnOperand(const MachineInstr *MI, int opNum,
305 raw_ostream &OS, const char *Modifier) {
306 OS << RETURN_PREFIX << (int) MI->getOperand(opNum).getImm() + 1;
309 void PTXAsmPrinter::EmitVariableDeclaration(const GlobalVariable *gv) {
310 // Check to see if this is a special global used by LLVM, if so, emit it.
311 if (EmitSpecialLLVMGlobal(gv))
314 MCSymbol *gvsym = Mang->getSymbol(gv);
316 assert(gvsym->isUndefined() && "Cannot define a symbol twice!");
320 // check if it is defined in some other translation unit
321 if (gv->isDeclaration())
324 // state space: e.g., .global
326 decl += getStateSpaceName(gv->getType()->getAddressSpace());
329 // alignment (optional)
330 unsigned alignment = gv->getAlignment();
331 if (alignment != 0) {
333 decl += utostr(Log2_32(gv->getAlignment()));
338 if (PointerType::classof(gv->getType())) {
339 const PointerType* pointerTy = dyn_cast<const PointerType>(gv->getType());
340 const Type* elementTy = pointerTy->getElementType();
343 decl += gvsym->getName();
346 if (elementTy->isArrayTy())
348 assert(elementTy->isArrayTy() && "Only pointers to arrays are supported");
350 const ArrayType* arrayTy = dyn_cast<const ArrayType>(elementTy);
351 elementTy = arrayTy->getElementType();
353 unsigned numElements = arrayTy->getNumElements();
355 while (elementTy->isArrayTy()) {
357 arrayTy = dyn_cast<const ArrayType>(elementTy);
358 elementTy = arrayTy->getElementType();
360 numElements *= arrayTy->getNumElements();
363 // FIXME: isPrimitiveType() == false for i16?
364 assert(elementTy->isSingleValueType() &&
365 "Non-primitive types are not handled");
367 // Compute the size of the array, in bytes.
368 uint64_t arraySize = (elementTy->getPrimitiveSizeInBits() >> 3)
371 decl += utostr(arraySize);
376 // handle string constants (assume ConstantArray means string)
378 if (gv->hasInitializer())
380 const Constant *C = gv->getInitializer();
381 if (const ConstantArray *CA = dyn_cast<ConstantArray>(C))
385 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
387 if (i > 0) decl += ",";
390 utohexstr(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
398 // Note: this is currently the fall-through case and most likely generates
400 decl += getTypeName(gv->getType());
403 decl += gvsym->getName();
405 if (ArrayType::classof(gv->getType()) ||
406 PointerType::classof(gv->getType()))
412 OutStreamer.EmitRawText(Twine(decl));
414 OutStreamer.AddBlankLine();
417 void PTXAsmPrinter::EmitFunctionDeclaration() {
418 // The function label could have already been emitted if two symbols end up
419 // conflicting due to asm renaming. Detect this and emit an error.
420 if (!CurrentFnSym->isUndefined()) {
421 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
422 "' label emitted multiple times to assembly file");
426 const PTXMachineFunctionInfo *MFI = MF->getInfo<PTXMachineFunctionInfo>();
427 const bool isKernel = MFI->isKernel();
428 const PTXSubtarget& ST = TM.getSubtarget<PTXSubtarget>();
430 std::string decl = isKernel ? ".entry" : ".func";
436 for (PTXMachineFunctionInfo::ret_iterator
437 i = MFI->retRegBegin(), e = MFI->retRegEnd(), b = i;
443 decl += getRegisterTypeName(*i);
445 decl += getRegisterName(*i);
450 // Print function name
452 decl += CurrentFnSym->getName().str();
459 for (PTXMachineFunctionInfo::reg_iterator
460 i = MFI->argRegBegin(), e = MFI->argRegEnd(), b = i;
465 if (isKernel || ST.getShaderModel() >= PTXSubtarget::PTX_SM_2_0) {
469 decl += PARAM_PREFIX;
470 decl += utostr(++cnt);
473 decl += getRegisterTypeName(*i);
475 decl += getRegisterName(*i);
480 OutStreamer.EmitRawText(Twine(decl));
484 printPredicateOperand(const MachineInstr *MI, raw_ostream &O) {
485 int i = MI->findFirstPredOperandIdx();
487 llvm_unreachable("missing predicate operand");
489 unsigned reg = MI->getOperand(i).getReg();
490 int predOp = MI->getOperand(i+1).getImm();
492 DEBUG(dbgs() << "predicate: (" << reg << ", " << predOp << ")\n");
494 if (reg != PTX::NoRegister) {
496 if (predOp == PTX::PRED_NEGATE)
498 O << getRegisterName(reg);
502 #include "PTXGenAsmWriter.inc"
504 // Force static initialization.
505 extern "C" void LLVMInitializePTXAsmPrinter() {
506 RegisterAsmPrinter<PTXAsmPrinter> X(ThePTX32Target);
507 RegisterAsmPrinter<PTXAsmPrinter> Y(ThePTX64Target);