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/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"
42 class PTXAsmPrinter : public AsmPrinter {
44 explicit PTXAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
45 : AsmPrinter(TM, Streamer) {}
47 const char *getPassName() const { return "PTX Assembly Printer"; }
49 bool doFinalization(Module &M);
51 virtual void EmitStartOfAsmFile(Module &M);
53 virtual bool runOnMachineFunction(MachineFunction &MF);
55 virtual void EmitFunctionBodyStart();
56 virtual void EmitFunctionBodyEnd() { OutStreamer.EmitRawText(Twine("}")); }
58 virtual void EmitInstruction(const MachineInstr *MI);
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 void printPredicateOperand(const MachineInstr *MI, raw_ostream &O);
68 void printInstruction(const MachineInstr *MI, raw_ostream &OS);
69 static const char *getRegisterName(unsigned RegNo);
72 void EmitVariableDeclaration(const GlobalVariable *gv);
73 void EmitFunctionDeclaration();
74 }; // class PTXAsmPrinter
77 static const char PARAM_PREFIX[] = "__param_";
79 static const char *getRegisterTypeName(unsigned RegNo) {
80 #define TEST_REGCLS(cls, clsstr) \
81 if (PTX::cls ## RegisterClass->contains(RegNo)) return # clsstr;
82 TEST_REGCLS(Preds, pred);
83 TEST_REGCLS(RRegu16, u16);
84 TEST_REGCLS(RRegu32, u32);
85 TEST_REGCLS(RRegu64, u64);
86 TEST_REGCLS(RRegf32, f32);
87 TEST_REGCLS(RRegf64, f64);
90 llvm_unreachable("Not in any register class!");
94 static const char *getStateSpaceName(unsigned addressSpace) {
95 switch (addressSpace) {
96 default: llvm_unreachable("Unknown state space");
97 case PTX::GLOBAL: return "global";
98 case PTX::CONSTANT: return "const";
99 case PTX::LOCAL: return "local";
100 case PTX::PARAMETER: return "param";
101 case PTX::SHARED: return "shared";
106 static const char *getTypeName(const Type* type) {
108 switch (type->getTypeID()) {
109 default: llvm_unreachable("Unknown type");
110 case Type::FloatTyID: return ".f32";
111 case Type::DoubleTyID: return ".f64";
112 case Type::IntegerTyID:
113 switch (type->getPrimitiveSizeInBits()) {
114 default: llvm_unreachable("Unknown integer bit-width");
115 case 16: return ".u16";
116 case 32: return ".u32";
117 case 64: return ".u64";
119 case Type::ArrayTyID:
120 case Type::PointerTyID:
121 type = dyn_cast<const SequentialType>(type)->getElementType();
128 bool PTXAsmPrinter::doFinalization(Module &M) {
129 // XXX Temproarily remove global variables so that doFinalization() will not
130 // emit them again (global variables are emitted at beginning).
132 Module::GlobalListType &global_list = M.getGlobalList();
133 int i, n = global_list.size();
134 GlobalVariable **gv_array = new GlobalVariable* [n];
136 // first, back-up GlobalVariable in gv_array
138 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
142 // second, empty global_list
143 while (!global_list.empty())
144 global_list.remove(global_list.begin());
146 // call doFinalization
147 bool ret = AsmPrinter::doFinalization(M);
149 // now we restore global variables
150 for (i = 0; i < n; i ++)
151 global_list.insert(global_list.end(), gv_array[i]);
157 void PTXAsmPrinter::EmitStartOfAsmFile(Module &M)
159 const PTXSubtarget& ST = TM.getSubtarget<PTXSubtarget>();
161 OutStreamer.EmitRawText(Twine("\t.version " + ST.getPTXVersionString()));
162 OutStreamer.EmitRawText(Twine("\t.target " + ST.getTargetString() +
163 (ST.supportsDouble() ? ""
164 : ", map_f64_to_f32")));
165 OutStreamer.AddBlankLine();
167 // declare global variables
168 for (Module::const_global_iterator i = M.global_begin(), e = M.global_end();
170 EmitVariableDeclaration(i);
173 bool PTXAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
174 SetupMachineFunction(MF);
175 EmitFunctionDeclaration();
180 void PTXAsmPrinter::EmitFunctionBodyStart() {
181 OutStreamer.EmitRawText(Twine("{"));
183 const PTXMachineFunctionInfo *MFI = MF->getInfo<PTXMachineFunctionInfo>();
185 // Print local variable definition
186 for (PTXMachineFunctionInfo::reg_iterator
187 i = MFI->localVarRegBegin(), e = MFI->localVarRegEnd(); i != e; ++ i) {
190 std::string def = "\t.reg .";
191 def += getRegisterTypeName(reg);
193 def += getRegisterName(reg);
195 OutStreamer.EmitRawText(Twine(def));
199 void PTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
203 raw_string_ostream OS(str);
206 printPredicateOperand(MI, OS);
208 // Write instruction to str
209 printInstruction(MI, OS);
213 StringRef strref = StringRef(str);
214 OutStreamer.EmitRawText(strref);
217 void PTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
219 const MachineOperand &MO = MI->getOperand(opNum);
221 switch (MO.getType()) {
223 llvm_unreachable("<unknown operand type>");
225 case MachineOperand::MO_GlobalAddress:
226 OS << *Mang->getSymbol(MO.getGlobal());
228 case MachineOperand::MO_Immediate:
229 OS << (int) MO.getImm();
231 case MachineOperand::MO_MachineBasicBlock:
232 OS << *MO.getMBB()->getSymbol();
234 case MachineOperand::MO_Register:
235 OS << getRegisterName(MO.getReg());
237 case MachineOperand::MO_FPImmediate:
238 APInt constFP = MO.getFPImm()->getValueAPF().bitcastToAPInt();
239 bool isFloat = MO.getFPImm()->getType()->getTypeID() == Type::FloatTyID;
240 // Emit 0F for 32-bit floats and 0D for 64-bit doubles.
247 // Emit the encoded floating-point value.
248 if (constFP.getZExtValue() > 0) {
249 OS << constFP.toString(16, false);
253 // If We have a double-precision zero, pad to 8-bytes.
262 void PTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
263 raw_ostream &OS, const char *Modifier) {
264 printOperand(MI, opNum, OS);
266 if (MI->getOperand(opNum+1).isImm() && MI->getOperand(opNum+1).getImm() == 0)
267 return; // don't print "+0"
270 printOperand(MI, opNum+1, OS);
273 void PTXAsmPrinter::printParamOperand(const MachineInstr *MI, int opNum,
274 raw_ostream &OS, const char *Modifier) {
275 OS << PARAM_PREFIX << (int) MI->getOperand(opNum).getImm() + 1;
278 void PTXAsmPrinter::EmitVariableDeclaration(const GlobalVariable *gv) {
279 // Check to see if this is a special global used by LLVM, if so, emit it.
280 if (EmitSpecialLLVMGlobal(gv))
283 MCSymbol *gvsym = Mang->getSymbol(gv);
285 assert(gvsym->isUndefined() && "Cannot define a symbol twice!");
289 // check if it is defined in some other translation unit
290 if (gv->isDeclaration())
293 // state space: e.g., .global
295 decl += getStateSpaceName(gv->getType()->getAddressSpace());
298 // alignment (optional)
299 unsigned alignment = gv->getAlignment();
300 if (alignment != 0) {
302 decl += utostr(Log2_32(gv->getAlignment()));
307 if (PointerType::classof(gv->getType())) {
308 const PointerType* pointerTy = dyn_cast<const PointerType>(gv->getType());
309 const Type* elementTy = pointerTy->getElementType();
311 assert(elementTy->isArrayTy() && "Only pointers to arrays are supported");
313 const ArrayType* arrayTy = dyn_cast<const ArrayType>(elementTy);
314 elementTy = arrayTy->getElementType();
316 unsigned numElements = arrayTy->getNumElements();
318 while (elementTy->isArrayTy()) {
320 arrayTy = dyn_cast<const ArrayType>(elementTy);
321 elementTy = arrayTy->getElementType();
323 numElements *= arrayTy->getNumElements();
326 // FIXME: isPrimitiveType() == false for i16?
327 assert(elementTy->isSingleValueType() &&
328 "Non-primitive types are not handled");
330 // Compute the size of the array, in bytes.
331 uint64_t arraySize = (elementTy->getPrimitiveSizeInBits() >> 3)
335 decl += gvsym->getName();
337 decl += utostr(arraySize);
341 // Note: this is currently the fall-through case and most likely generates
343 decl += getTypeName(gv->getType());
346 decl += gvsym->getName();
348 if (ArrayType::classof(gv->getType()) ||
349 PointerType::classof(gv->getType()))
355 OutStreamer.EmitRawText(Twine(decl));
357 OutStreamer.AddBlankLine();
360 void PTXAsmPrinter::EmitFunctionDeclaration() {
361 // The function label could have already been emitted if two symbols end up
362 // conflicting due to asm renaming. Detect this and emit an error.
363 if (!CurrentFnSym->isUndefined()) {
364 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
365 "' label emitted multiple times to assembly file");
369 const PTXMachineFunctionInfo *MFI = MF->getInfo<PTXMachineFunctionInfo>();
370 const bool isKernel = MFI->isKernel();
373 std::string decl = isKernel ? ".entry" : ".func";
375 // Print return register
377 if (!isKernel && reg != PTX::NoRegister) {
378 decl += " (.reg ."; // FIXME: could it return in .param space?
379 decl += getRegisterTypeName(reg);
381 decl += getRegisterName(reg);
385 // Print function name
387 decl += CurrentFnSym->getName().str();
389 // Print parameter list
390 if (!MFI->argRegEmpty()) {
394 for(PTXMachineFunctionInfo::reg_iterator
395 i = MFI->argRegBegin(), e = MFI->argRegEnd(), b = i;
398 assert(reg != PTX::NoRegister && "Not a valid register!");
402 decl += getRegisterTypeName(reg);
404 decl += PARAM_PREFIX;
405 decl += utostr(++cnt);
408 for (PTXMachineFunctionInfo::reg_iterator
409 i = MFI->argRegBegin(), e = MFI->argRegEnd(), b = i;
412 assert(reg != PTX::NoRegister && "Not a valid register!");
416 decl += getRegisterTypeName(reg);
418 decl += getRegisterName(reg);
424 OutStreamer.EmitRawText(Twine(decl));
428 printPredicateOperand(const MachineInstr *MI, raw_ostream &O) {
429 int i = MI->findFirstPredOperandIdx();
431 llvm_unreachable("missing predicate operand");
433 unsigned reg = MI->getOperand(i).getReg();
434 int predOp = MI->getOperand(i+1).getImm();
436 DEBUG(dbgs() << "predicate: (" << reg << ", " << predOp << ")\n");
438 if (reg != PTX::NoRegister) {
440 if (predOp == PTX::PRED_NEGATE)
442 O << getRegisterName(reg);
446 #include "PTXGenAsmWriter.inc"
448 // Force static initialization.
449 extern "C" void LLVMInitializePTXAsmPrinter() {
450 RegisterAsmPrinter<PTXAsmPrinter> X(ThePTXTarget);